1 //===- Verifier.cpp - MLIR Verifier Implementation ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the verify() methods on the various IR types, performing
10 // (potentially expensive) checks on the holistic structure of the code.  This
11 // can be used for detecting bugs in compiler transformations and hand written
12 // .mlir files.
13 //
14 // The checks in this file are only for things that can occur as part of IR
15 // transformations: e.g. violation of dominance information, malformed operation
16 // attributes, etc.  MLIR supports transformations moving IR through locally
17 // invalid states (e.g. unlinking an operation from a block before re-inserting
18 // it in a new place), but each transformation must complete with the IR in a
19 // valid form.
20 //
21 // This should not check for things that are always wrong by construction (e.g.
22 // attributes or other immutable structures that are incorrect), because those
23 // are not mutable and can be checked at time of construction.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "mlir/IR/Verifier.h"
28 #include "mlir/IR/Attributes.h"
29 #include "mlir/IR/Dialect.h"
30 #include "mlir/IR/Dominance.h"
31 #include "mlir/IR/Operation.h"
32 #include "mlir/IR/RegionKindInterface.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/Support/FormatVariadic.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Regex.h"
37 
38 using namespace mlir;
39 
40 namespace {
41 /// This class encapsulates all the state used to verify an operation region.
42 class OperationVerifier {
43 public:
44   explicit OperationVerifier(MLIRContext *ctx) : ctx(ctx) {}
45 
46   /// Verify the given operation.
47   LogicalResult verify(Operation &op);
48 
49   /// Returns the registered dialect for a dialect-specific attribute.
50   Dialect *getDialectForAttribute(const NamedAttribute &attr) {
51     assert(attr.first.strref().contains('.') && "expected dialect attribute");
52     auto dialectNamePair = attr.first.strref().split('.');
53     return ctx->getLoadedDialect(dialectNamePair.first);
54   }
55 
56 private:
57   /// Verify the given potentially nested region or block.
58   LogicalResult verifyRegion(Region &region);
59   LogicalResult verifyBlock(Block &block);
60   LogicalResult verifyOperation(Operation &op);
61 
62   /// Verify the dominance property of operations within the given Region.
63   LogicalResult verifyDominance(Region &region);
64 
65   /// Verify the dominance property of regions contained within the given
66   /// Operation.
67   LogicalResult verifyDominanceOfContainedRegions(Operation &op);
68 
69   /// Emit an error for the given block.
70   InFlightDiagnostic emitError(Block &bb, const Twine &message) {
71     // Take the location information for the first operation in the block.
72     if (!bb.empty())
73       return bb.front().emitError(message);
74 
75     // Worst case, fall back to using the parent's location.
76     return mlir::emitError(bb.getParent()->getLoc(), message);
77   }
78 
79   /// The current context for the verifier.
80   MLIRContext *ctx;
81 
82   /// Dominance information for this operation, when checking dominance.
83   DominanceInfo *domInfo = nullptr;
84 
85   /// Mapping between dialect namespace and if that dialect supports
86   /// unregistered operations.
87   llvm::StringMap<bool> dialectAllowsUnknownOps;
88 };
89 } // end anonymous namespace
90 
91 /// Verify the given operation.
92 LogicalResult OperationVerifier::verify(Operation &op) {
93   // Verify the operation first.
94   if (failed(verifyOperation(op)))
95     return failure();
96 
97   // Since everything looks structurally ok to this point, we do a dominance
98   // check for any nested regions. We do this as a second pass since malformed
99   // CFG's can cause dominator analysis constructure to crash and we want the
100   // verifier to be resilient to malformed code.
101   DominanceInfo theDomInfo(&op);
102   domInfo = &theDomInfo;
103   if (failed(verifyDominanceOfContainedRegions(op)))
104     return failure();
105 
106   domInfo = nullptr;
107   return success();
108 }
109 
110 LogicalResult OperationVerifier::verifyRegion(Region &region) {
111   if (region.empty())
112     return success();
113 
114   // Verify the first block has no predecessors.
115   auto *firstBB = &region.front();
116   if (!firstBB->hasNoPredecessors())
117     return mlir::emitError(region.getLoc(),
118                            "entry block of region may not have predecessors");
119 
120   // Verify each of the blocks within the region.
121   for (Block &block : region)
122     if (failed(verifyBlock(block)))
123       return failure();
124   return success();
125 }
126 
127 LogicalResult OperationVerifier::verifyBlock(Block &block) {
128   for (auto arg : block.getArguments())
129     if (arg.getOwner() != &block)
130       return emitError(block, "block argument not owned by block");
131 
132   // Verify that this block has a terminator.
133   if (block.empty())
134     return emitError(block, "block with no terminator");
135 
136   // Verify the non-terminator operations separately so that we can verify
137   // they has no successors.
138   for (auto &op : llvm::make_range(block.begin(), std::prev(block.end()))) {
139     if (op.getNumSuccessors() != 0)
140       return op.emitError(
141           "operation with block successors must terminate its parent block");
142 
143     if (failed(verifyOperation(op)))
144       return failure();
145   }
146 
147   // Verify the terminator.
148   Operation &terminator = block.back();
149   if (failed(verifyOperation(terminator)))
150     return failure();
151   if (!terminator.mightHaveTrait<OpTrait::IsTerminator>())
152     return block.back().emitError("block with no terminator");
153 
154   // Verify that this block is not branching to a block of a different
155   // region.
156   for (Block *successor : block.getSuccessors())
157     if (successor->getParent() != block.getParent())
158       return block.back().emitOpError(
159           "branching to block of a different region");
160 
161   return success();
162 }
163 
164 LogicalResult OperationVerifier::verifyOperation(Operation &op) {
165   // Check that operands are non-nil and structurally ok.
166   for (auto operand : op.getOperands())
167     if (!operand)
168       return op.emitError("null operand found");
169 
170   /// Verify that all of the attributes are okay.
171   for (auto attr : op.getAttrs()) {
172     // Check for any optional dialect specific attributes.
173     if (!attr.first.strref().contains('.'))
174       continue;
175     if (auto *dialect = getDialectForAttribute(attr))
176       if (failed(dialect->verifyOperationAttribute(&op, attr)))
177         return failure();
178   }
179 
180   // If we can get operation info for this, check the custom hook.
181   auto *opInfo = op.getAbstractOperation();
182   if (opInfo && failed(opInfo->verifyInvariants(&op)))
183     return failure();
184 
185   auto kindInterface = dyn_cast<mlir::RegionKindInterface>(op);
186 
187   // Verify that all child regions are ok.
188   unsigned numRegions = op.getNumRegions();
189   for (unsigned i = 0; i < numRegions; i++) {
190     Region &region = op.getRegion(i);
191     // Check that Graph Regions only have a single basic block. This is
192     // similar to the code in SingleBlockImplicitTerminator, but doesn't
193     // require the trait to be specified. This arbitrary limitation is
194     // designed to limit the number of cases that have to be handled by
195     // transforms and conversions until the concept stabilizes.
196     if (op.isRegistered() && kindInterface &&
197         kindInterface.getRegionKind(i) == RegionKind::Graph) {
198       // Empty regions are fine.
199       if (region.empty())
200         continue;
201 
202       // Non-empty regions must contain a single basic block.
203       if (std::next(region.begin()) != region.end())
204         return op.emitOpError("expects graph region #")
205                << i << " to have 0 or 1 blocks";
206     }
207     if (failed(verifyRegion(region)))
208       return failure();
209   }
210 
211   // If this is a registered operation, there is nothing left to do.
212   if (opInfo)
213     return success();
214 
215   // Otherwise, verify that the parent dialect allows un-registered operations.
216   auto dialectPrefix = op.getName().getDialect();
217 
218   // Check for an existing answer for the operation dialect.
219   auto it = dialectAllowsUnknownOps.find(dialectPrefix);
220   if (it == dialectAllowsUnknownOps.end()) {
221     // If the operation dialect is registered, query it directly.
222     if (auto *dialect = ctx->getLoadedDialect(dialectPrefix))
223       it = dialectAllowsUnknownOps
224                .try_emplace(dialectPrefix, dialect->allowsUnknownOperations())
225                .first;
226     // Otherwise, unregistered dialects (when allowed by the context)
227     // conservatively allow unknown operations.
228     else {
229       if (!op.getContext()->allowsUnregisteredDialects() && !op.getDialect())
230         return op.emitOpError()
231                << "created with unregistered dialect. If this is "
232                   "intended, please call allowUnregisteredDialects() on the "
233                   "MLIRContext, or use -allow-unregistered-dialect with "
234                   "mlir-opt";
235 
236       it = dialectAllowsUnknownOps.try_emplace(dialectPrefix, true).first;
237     }
238   }
239 
240   if (!it->second) {
241     return op.emitError("unregistered operation '")
242            << op.getName() << "' found in dialect ('" << dialectPrefix
243            << "') that does not allow unknown operations";
244   }
245 
246   return success();
247 }
248 
249 /// Attach a note to an in-flight diagnostic that provide more information about
250 /// where an op operand is defined.
251 static void attachNoteForOperandDefinition(InFlightDiagnostic &diag,
252                                            Operation &op, Value operand) {
253   if (auto *useOp = operand.getDefiningOp()) {
254     Diagnostic &note = diag.attachNote(useOp->getLoc());
255     note << "operand defined here";
256     Block *block1 = op.getBlock();
257     Block *block2 = useOp->getBlock();
258     Region *region1 = block1->getParent();
259     Region *region2 = block2->getParent();
260     if (block1 == block2)
261       note << " (op in the same block)";
262     else if (region1 == region2)
263       note << " (op in the same region)";
264     else if (region2->isProperAncestor(region1))
265       note << " (op in a parent region)";
266     else if (region1->isProperAncestor(region2))
267       note << " (op in a child region)";
268     else
269       note << " (op is neither in a parent nor in a child region)";
270     return;
271   }
272   // Block argument case.
273   Block *block1 = op.getBlock();
274   Block *block2 = operand.cast<BlockArgument>().getOwner();
275   Region *region1 = block1->getParent();
276   Region *region2 = block2->getParent();
277   Location loc = UnknownLoc::get(op.getContext());
278   if (block2->getParentOp())
279     loc = block2->getParentOp()->getLoc();
280   Diagnostic &note = diag.attachNote(loc);
281   if (!region2) {
282     note << " (block without parent)";
283     return;
284   }
285   if (block1 == block2)
286     llvm::report_fatal_error("Internal error in dominance verification");
287   int index = std::distance(region2->begin(), block2->getIterator());
288   note << "operand defined as a block argument (block #" << index;
289   if (region1 == region2)
290     note << " in the same region)";
291   else if (region2->isProperAncestor(region1))
292     note << " in a parent region)";
293   else if (region1->isProperAncestor(region2))
294     note << " in a child region)";
295   else
296     note << " neither in a parent nor in a child region)";
297 }
298 
299 LogicalResult OperationVerifier::verifyDominance(Region &region) {
300   // Verify the dominance of each of the held operations.
301   for (Block &block : region) {
302     // Dominance is only meaningful inside reachable blocks.
303     if (domInfo->isReachableFromEntry(&block))
304       for (Operation &op : block)
305         // Check that operands properly dominate this use.
306         for (unsigned operandNo = 0, e = op.getNumOperands(); operandNo != e;
307              ++operandNo) {
308           Value operand = op.getOperand(operandNo);
309           if (domInfo->properlyDominates(operand, &op))
310             continue;
311 
312           InFlightDiagnostic diag = op.emitError("operand #")
313                                     << operandNo
314                                     << " does not dominate this use";
315           attachNoteForOperandDefinition(diag, op, operand);
316           return failure();
317         }
318     // Recursively verify dominance within each operation in the
319     // block, even if the block itself is not reachable, or we are in
320     // a region which doesn't respect dominance.
321     for (Operation &op : block)
322       if (failed(verifyDominanceOfContainedRegions(op)))
323         return failure();
324   }
325   return success();
326 }
327 
328 /// Verify the dominance of each of the nested blocks within the given operation
329 LogicalResult
330 OperationVerifier::verifyDominanceOfContainedRegions(Operation &op) {
331   for (Region &region : op.getRegions()) {
332     if (failed(verifyDominance(region)))
333       return failure();
334   }
335   return success();
336 }
337 
338 //===----------------------------------------------------------------------===//
339 // Entrypoint
340 //===----------------------------------------------------------------------===//
341 
342 /// Perform (potentially expensive) checks of invariants, used to detect
343 /// compiler bugs.  On error, this reports the error through the MLIRContext and
344 /// returns failure.
345 LogicalResult mlir::verify(Operation *op) {
346   return OperationVerifier(op->getContext()).verify(*op);
347 }
348