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() {}
45 
46   /// Verify the given operation.
47   LogicalResult verifyOpAndDominance(Operation &op);
48 
49 private:
50   /// Verify the given potentially nested region or block.
51   LogicalResult verifyRegion(Region &region);
52   LogicalResult verifyBlock(Block &block);
53   LogicalResult verifyOperation(Operation &op);
54 
55   /// Verify the dominance property of operations within the given Region.
56   LogicalResult verifyDominance(Region &region);
57 
58   /// Verify the dominance property of regions contained within the given
59   /// Operation.
60   LogicalResult verifyDominanceOfContainedRegions(Operation &op);
61 
62   /// Emit an error for the given block.
63   InFlightDiagnostic emitError(Block &bb, const Twine &message) {
64     // Take the location information for the first operation in the block.
65     if (!bb.empty())
66       return bb.front().emitError(message);
67 
68     // Worst case, fall back to using the parent's location.
69     return mlir::emitError(bb.getParent()->getLoc(), message);
70   }
71 
72   /// Dominance information for this operation, when checking dominance.
73   DominanceInfo *domInfo = nullptr;
74 };
75 } // end anonymous namespace
76 
77 /// Verify the given operation.
78 LogicalResult OperationVerifier::verifyOpAndDominance(Operation &op) {
79   // Verify the operation first.
80   if (failed(verifyOperation(op)))
81     return failure();
82 
83   // Since everything looks structurally ok to this point, we do a dominance
84   // check for any nested regions. We do this as a second pass since malformed
85   // CFG's can cause dominator analysis constructure to crash and we want the
86   // verifier to be resilient to malformed code.
87   DominanceInfo theDomInfo(&op);
88   domInfo = &theDomInfo;
89   if (failed(verifyDominanceOfContainedRegions(op)))
90     return failure();
91 
92   domInfo = nullptr;
93   return success();
94 }
95 
96 LogicalResult OperationVerifier::verifyRegion(Region &region) {
97   if (region.empty())
98     return success();
99 
100   // Verify the first block has no predecessors.
101   auto *firstBB = &region.front();
102   if (!firstBB->hasNoPredecessors())
103     return mlir::emitError(region.getLoc(),
104                            "entry block of region may not have predecessors");
105 
106   // Verify each of the blocks within the region.
107   for (Block &block : region)
108     if (failed(verifyBlock(block)))
109       return failure();
110   return success();
111 }
112 
113 /// Returns true if this block may be valid without terminator. That is if:
114 /// - it does not have a parent region.
115 /// - Or the parent region have a single block and:
116 ///    - This region does not have a parent op.
117 ///    - Or the parent op is unregistered.
118 ///    - Or the parent op has the NoTerminator trait.
119 static bool mayBeValidWithoutTerminator(Block *block) {
120   if (!block->getParent())
121     return true;
122   if (!llvm::hasSingleElement(*block->getParent()))
123     return false;
124   Operation *op = block->getParentOp();
125   return !op || op->mightHaveTrait<OpTrait::NoTerminator>();
126 }
127 
128 LogicalResult OperationVerifier::verifyBlock(Block &block) {
129   for (auto arg : block.getArguments())
130     if (arg.getOwner() != &block)
131       return emitError(block, "block argument not owned by block");
132 
133   // Verify that this block has a terminator.
134   if (block.empty()) {
135     if (mayBeValidWithoutTerminator(&block))
136       return success();
137     return emitError(block, "empty block: expect at least a terminator");
138   }
139 
140   // Verify the non-terminator operations separately so that we can verify
141   // they have no successors.
142   for (auto &op : llvm::make_range(block.begin(), std::prev(block.end()))) {
143     if (op.getNumSuccessors() != 0)
144       return op.emitError(
145           "operation with block successors must terminate its parent block");
146 
147     if (failed(verifyOperation(op)))
148       return failure();
149   }
150 
151   // Verify the terminator.
152   Operation &terminator = block.back();
153   if (failed(verifyOperation(terminator)))
154     return failure();
155 
156   // Verify that this block is not branching to a block of a different
157   // region.
158   for (Block *successor : block.getSuccessors())
159     if (successor->getParent() != block.getParent())
160       return block.back().emitOpError(
161           "branching to block of a different region");
162 
163   // If this block doesn't have to have a terminator, don't require it.
164   if (mayBeValidWithoutTerminator(&block))
165     return success();
166 
167   if (!terminator.mightHaveTrait<OpTrait::IsTerminator>())
168     return block.back().emitError("block with no terminator, has ")
169            << terminator;
170 
171   return success();
172 }
173 
174 LogicalResult OperationVerifier::verifyOperation(Operation &op) {
175   // Check that operands are non-nil and structurally ok.
176   for (auto operand : op.getOperands())
177     if (!operand)
178       return op.emitError("null operand found");
179 
180   /// Verify that all of the attributes are okay.
181   for (auto attr : op.getAttrs()) {
182     // Check for any optional dialect specific attributes.
183     if (auto *dialect = attr.first.getDialect())
184       if (failed(dialect->verifyOperationAttribute(&op, attr)))
185         return failure();
186   }
187 
188   // If we can get operation info for this, check the custom hook.
189   OperationName opName = op.getName();
190   auto *opInfo = opName.getAbstractOperation();
191   if (opInfo && failed(opInfo->verifyInvariants(&op)))
192     return failure();
193 
194   if (unsigned numRegions = op.getNumRegions()) {
195     auto kindInterface = dyn_cast<mlir::RegionKindInterface>(op);
196 
197     // Verify that all child regions are ok.
198     for (unsigned i = 0; i < numRegions; ++i) {
199       Region &region = op.getRegion(i);
200       RegionKind kind =
201           kindInterface ? kindInterface.getRegionKind(i) : RegionKind::SSACFG;
202       // Check that Graph Regions only have a single basic block. This is
203       // similar to the code in SingleBlockImplicitTerminator, but doesn't
204       // require the trait to be specified. This arbitrary limitation is
205       // designed to limit the number of cases that have to be handled by
206       // transforms and conversions.
207       if (op.isRegistered() && kind == RegionKind::Graph) {
208         // Empty regions are fine.
209         if (region.empty())
210           continue;
211 
212         // Non-empty regions must contain a single basic block.
213         if (std::next(region.begin()) != region.end())
214           return op.emitOpError("expects graph region #")
215                  << i << " to have 0 or 1 blocks";
216       }
217       if (failed(verifyRegion(region)))
218         return failure();
219     }
220   }
221 
222   // If this is a registered operation, there is nothing left to do.
223   if (opInfo)
224     return success();
225 
226   // Otherwise, verify that the parent dialect allows un-registered operations.
227   Dialect *dialect = opName.getDialect();
228   if (!dialect) {
229     if (!op.getContext()->allowsUnregisteredDialects()) {
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     return success();
237   }
238 
239   if (!dialect->allowsUnknownOperations()) {
240     return op.emitError("unregistered operation '")
241            << op.getName() << "' found in dialect ('" << dialect->getNamespace()
242            << "') that does not allow unknown operations";
243   }
244 
245   return success();
246 }
247 
248 /// Emit an error when the specified operand of the specified operation is an
249 /// invalid use because of dominance properties.
250 static void diagnoseInvalidOperandDominance(Operation &op, unsigned operandNo) {
251   InFlightDiagnostic diag = op.emitError("operand #")
252                             << operandNo << " does not dominate this use";
253 
254   Value operand = op.getOperand(operandNo);
255 
256   /// Attach a note to an in-flight diagnostic that provide more information
257   /// about where an op operand is defined.
258   if (auto *useOp = operand.getDefiningOp()) {
259     Diagnostic &note = diag.attachNote(useOp->getLoc());
260     note << "operand defined here";
261     Block *block1 = op.getBlock();
262     Block *block2 = useOp->getBlock();
263     Region *region1 = block1->getParent();
264     Region *region2 = block2->getParent();
265     if (block1 == block2)
266       note << " (op in the same block)";
267     else if (region1 == region2)
268       note << " (op in the same region)";
269     else if (region2->isProperAncestor(region1))
270       note << " (op in a parent region)";
271     else if (region1->isProperAncestor(region2))
272       note << " (op in a child region)";
273     else
274       note << " (op is neither in a parent nor in a child region)";
275     return;
276   }
277   // Block argument case.
278   Block *block1 = op.getBlock();
279   Block *block2 = operand.cast<BlockArgument>().getOwner();
280   Region *region1 = block1->getParent();
281   Region *region2 = block2->getParent();
282   Location loc = UnknownLoc::get(op.getContext());
283   if (block2->getParentOp())
284     loc = block2->getParentOp()->getLoc();
285   Diagnostic &note = diag.attachNote(loc);
286   if (!region2) {
287     note << " (block without parent)";
288     return;
289   }
290   if (block1 == block2)
291     llvm::report_fatal_error("Internal error in dominance verification");
292   int index = std::distance(region2->begin(), block2->getIterator());
293   note << "operand defined as a block argument (block #" << index;
294   if (region1 == region2)
295     note << " in the same region)";
296   else if (region2->isProperAncestor(region1))
297     note << " in a parent region)";
298   else if (region1->isProperAncestor(region2))
299     note << " in a child region)";
300   else
301     note << " neither in a parent nor in a child region)";
302 }
303 
304 LogicalResult OperationVerifier::verifyDominance(Region &region) {
305   // Verify the dominance of each of the held operations.
306   for (Block &block : region) {
307     // Dominance is only meaningful inside reachable blocks.
308     bool isReachable = domInfo->isReachableFromEntry(&block);
309 
310     for (Operation &op : block) {
311       if (isReachable) {
312         // Check that operands properly dominate this use.
313         for (unsigned operandNo = 0, e = op.getNumOperands(); operandNo != e;
314              ++operandNo) {
315           if (domInfo->properlyDominates(op.getOperand(operandNo), &op))
316             continue;
317 
318           diagnoseInvalidOperandDominance(op, operandNo);
319           return failure();
320         }
321       }
322 
323       // Recursively verify dominance within each operation in the
324       // block, even if the block itself is not reachable, or we are in
325       // a region which doesn't respect dominance.
326       if (failed(verifyDominanceOfContainedRegions(op)))
327         return failure();
328     }
329   }
330   return success();
331 }
332 
333 /// Verify the dominance of each of the nested blocks within the given operation
334 LogicalResult
335 OperationVerifier::verifyDominanceOfContainedRegions(Operation &op) {
336   for (Region &region : op.getRegions()) {
337     if (failed(verifyDominance(region)))
338       return failure();
339   }
340   return success();
341 }
342 
343 //===----------------------------------------------------------------------===//
344 // Entrypoint
345 //===----------------------------------------------------------------------===//
346 
347 /// Perform (potentially expensive) checks of invariants, used to detect
348 /// compiler bugs.  On error, this reports the error through the MLIRContext and
349 /// returns failure.
350 LogicalResult mlir::verify(Operation *op) {
351   return OperationVerifier().verifyOpAndDominance(*op);
352 }
353