#include "mlir/IR/Verifier.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Dominance.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/RegionKindInterface.h"
#include "mlir/IR/Threading.h"
#include "llvm/ADT/DenseMapInfoVariant.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Regex.h"
#include <atomic>
#include <optional>
using namespace mlir;
namespace {
class OperationVerifier {
public:
explicit OperationVerifier(bool verifyRecursively)
: verifyRecursively(verifyRecursively) {}
LogicalResult verifyOpAndDominance(Operation &op);
private:
using WorkItem = llvm::PointerUnion<Operation *, Block *>;
LogicalResult verifyOnEntrance(Block &block);
LogicalResult verifyOnEntrance(Operation &op);
LogicalResult verifyOnExit(Block &block);
LogicalResult verifyOnExit(Operation &op);
LogicalResult verifyOperation(Operation &op);
LogicalResult verifyDominanceOfContainedRegions(Operation &op,
DominanceInfo &domInfo);
bool verifyRecursively;
};
}
LogicalResult OperationVerifier::verifyOpAndDominance(Operation &op) {
if (failed(verifyOperation(op)))
return failure();
if (op.getNumRegions() != 0) {
DominanceInfo domInfo;
if (failed(verifyDominanceOfContainedRegions(op, domInfo)))
return failure();
}
return success();
}
static bool mayBeValidWithoutTerminator(Block *block) {
if (!block->getParent())
return true;
if (!llvm::hasSingleElement(*block->getParent()))
return false;
Operation *op = block->getParentOp();
return !op || op->mightHaveTrait<OpTrait::NoTerminator>();
}
LogicalResult OperationVerifier::verifyOnEntrance(Block &block) {
for (auto arg : block.getArguments())
if (arg.getOwner() != &block)
return emitError(arg.getLoc(), "block argument not owned by block");
if (block.empty()) {
if (mayBeValidWithoutTerminator(&block))
return success();
return emitError(block.getParent()->getLoc(),
"empty block: expect at least a terminator");
}
for (Operation &op : block) {
if (op.getNumSuccessors() != 0 && &op != &block.back())
return op.emitError(
"operation with block successors must terminate its parent block");
}
return success();
}
LogicalResult OperationVerifier::verifyOnExit(Block &block) {
for (Block *successor : block.getSuccessors())
if (successor->getParent() != block.getParent())
return block.back().emitOpError(
"branching to block of a different region");
if (mayBeValidWithoutTerminator(&block))
return success();
Operation &terminator = block.back();
if (!terminator.mightHaveTrait<OpTrait::IsTerminator>())
return block.back().emitError("block with no terminator, has ")
<< terminator;
return success();
}
LogicalResult OperationVerifier::verifyOnEntrance(Operation &op) {
for (auto operand : op.getOperands())
if (!operand)
return op.emitError("null operand found");
for (auto attr : op.getDiscardableAttrDictionary()) {
if (auto *dialect = attr.getNameDialect())
if (failed(dialect->verifyOperationAttribute(&op, attr)))
return failure();
}
OperationName opName = op.getName();
std::optional<RegisteredOperationName> registeredInfo =
opName.getRegisteredInfo();
if (registeredInfo && failed(registeredInfo->verifyInvariants(&op)))
return failure();
unsigned numRegions = op.getNumRegions();
if (!numRegions)
return success();
auto kindInterface = dyn_cast<RegionKindInterface>(&op);
SmallVector<Operation *> opsWithIsolatedRegions;
MutableArrayRef<Region> regions = op.getRegions();
for (unsigned i = 0; i < numRegions; ++i) {
Region ®ion = regions[i];
RegionKind kind =
kindInterface ? kindInterface.getRegionKind(i) : RegionKind::SSACFG;
if (op.isRegistered() && kind == RegionKind::Graph) {
if (!region.empty() && !region.hasOneBlock())
return op.emitOpError("expects graph region #")
<< i << " to have 0 or 1 blocks";
}
if (region.empty())
continue;
Block *firstBB = ®ion.front();
if (!firstBB->hasNoPredecessors())
return emitError(op.getLoc(),
"entry block of region may not have predecessors");
}
return success();
}
LogicalResult OperationVerifier::verifyOnExit(Operation &op) {
SmallVector<Operation *> opsWithIsolatedRegions;
if (verifyRecursively) {
for (Region ®ion : op.getRegions())
for (Block &block : region)
for (Operation &o : block)
if (o.getNumRegions() != 0 &&
o.hasTrait<OpTrait::IsIsolatedFromAbove>())
opsWithIsolatedRegions.push_back(&o);
}
if (failed(failableParallelForEach(
op.getContext(), opsWithIsolatedRegions,
[&](Operation *o) { return verifyOpAndDominance(*o); })))
return failure();
OperationName opName = op.getName();
std::optional<RegisteredOperationName> registeredInfo =
opName.getRegisteredInfo();
if (registeredInfo && failed(registeredInfo->verifyRegionInvariants(&op)))
return failure();
if (registeredInfo)
return success();
Dialect *dialect = opName.getDialect();
if (!dialect) {
if (!op.getContext()->allowsUnregisteredDialects()) {
return op.emitOpError()
<< "created with unregistered dialect. If this is "
"intended, please call allowUnregisteredDialects() on the "
"MLIRContext, or use -allow-unregistered-dialect with "
"the MLIR opt tool used";
}
return success();
}
if (!dialect->allowsUnknownOperations()) {
return op.emitError("unregistered operation '")
<< op.getName() << "' found in dialect ('" << dialect->getNamespace()
<< "') that does not allow unknown operations";
}
return success();
}
LogicalResult OperationVerifier::verifyOperation(Operation &op) {
SmallVector<WorkItem> worklist{{&op}};
DenseSet<WorkItem> seen;
while (!worklist.empty()) {
WorkItem top = worklist.back();
auto visit = [](auto &&visitor, WorkItem w) {
if (w.is<Operation *>())
return visitor(w.get<Operation *>());
return visitor(w.get<Block *>());
};
const bool isExit = !seen.insert(top).second;
if (isExit) {
worklist.pop_back();
if (failed(visit(
[this](auto *workItem) { return verifyOnExit(*workItem); }, top)))
return failure();
continue;
}
if (failed(visit(
[this](auto *workItem) { return verifyOnEntrance(*workItem); },
top)))
return failure();
if (top.is<Block *>()) {
Block ¤tBlock = *top.get<Block *>();
for (Operation &o : llvm::reverse(currentBlock)) {
if (o.getNumRegions() == 0 ||
!o.hasTrait<OpTrait::IsIsolatedFromAbove>())
worklist.emplace_back(&o);
}
continue;
}
Operation ¤tOp = *top.get<Operation *>();
if (verifyRecursively)
for (Region ®ion : llvm::reverse(currentOp.getRegions()))
for (Block &block : llvm::reverse(region))
worklist.emplace_back(&block);
}
return success();
}
static void diagnoseInvalidOperandDominance(Operation &op, unsigned operandNo) {
InFlightDiagnostic diag = op.emitError("operand #")
<< operandNo << " does not dominate this use";
Value operand = op.getOperand(operandNo);
if (auto *useOp = operand.getDefiningOp()) {
Diagnostic ¬e = diag.attachNote(useOp->getLoc());
note << "operand defined here";
Block *block1 = op.getBlock();
Block *block2 = useOp->getBlock();
Region *region1 = block1->getParent();
Region *region2 = block2->getParent();
if (block1 == block2)
note << " (op in the same block)";
else if (region1 == region2)
note << " (op in the same region)";
else if (region2->isProperAncestor(region1))
note << " (op in a parent region)";
else if (region1->isProperAncestor(region2))
note << " (op in a child region)";
else
note << " (op is neither in a parent nor in a child region)";
return;
}
Block *block1 = op.getBlock();
Block *block2 = llvm::cast<BlockArgument>(operand).getOwner();
Region *region1 = block1->getParent();
Region *region2 = block2->getParent();
Location loc = UnknownLoc::get(op.getContext());
if (block2->getParentOp())
loc = block2->getParentOp()->getLoc();
Diagnostic ¬e = diag.attachNote(loc);
if (!region2) {
note << " (block without parent)";
return;
}
if (block1 == block2)
llvm::report_fatal_error("Internal error in dominance verification");
int index = std::distance(region2->begin(), block2->getIterator());
note << "operand defined as a block argument (block #" << index;
if (region1 == region2)
note << " in the same region)";
else if (region2->isProperAncestor(region1))
note << " in a parent region)";
else if (region1->isProperAncestor(region2))
note << " in a child region)";
else
note << " neither in a parent nor in a child region)";
}
LogicalResult
OperationVerifier::verifyDominanceOfContainedRegions(Operation &op,
DominanceInfo &domInfo) {
llvm::SmallVector<Operation *, 8> worklist{&op};
while (!worklist.empty()) {
auto *op = worklist.pop_back_val();
for (auto ®ion : op->getRegions())
for (auto &block : region.getBlocks()) {
bool isReachable = domInfo.isReachableFromEntry(&block);
for (auto &op : block) {
if (isReachable) {
for (const auto &operand : llvm::enumerate(op.getOperands())) {
if (domInfo.properlyDominates(operand.value(), &op))
continue;
diagnoseInvalidOperandDominance(op, operand.index());
return failure();
}
}
if (verifyRecursively && op.getNumRegions() != 0) {
if (op.hasTrait<OpTrait::IsIsolatedFromAbove>())
continue;
worklist.push_back(&op);
}
}
}
}
return success();
}
LogicalResult mlir::verify(Operation *op, bool verifyRecursively) {
OperationVerifier verifier(verifyRecursively);
return verifier.verifyOpAndDominance(*op);
}