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 #include <atomic>
39 
40 using namespace mlir;
41 
42 namespace {
43 /// This class encapsulates all the state used to verify an operation region.
44 class OperationVerifier {
45 public:
46   explicit OperationVerifier() {}
47 
48   /// Verify the given operation.
49   LogicalResult verifyOpAndDominance(Operation &op);
50 
51 private:
52   /// Verify the given potentially nested region or block.
53   LogicalResult verifyRegion(Region &region);
54   LogicalResult verifyBlock(Block &block);
55   LogicalResult verifyOperation(Operation &op);
56 
57   /// Verify the dominance property of regions contained within the given
58   /// Operation.
59   LogicalResult verifyDominanceOfContainedRegions(Operation &op);
60 
61   /// Emit an error for the given block.
62   InFlightDiagnostic emitError(Block &bb, const Twine &message) {
63     // Take the location information for the first operation in the block.
64     if (!bb.empty())
65       return bb.front().emitError(message);
66 
67     // Worst case, fall back to using the parent's location.
68     return mlir::emitError(bb.getParent()->getLoc(), message);
69   }
70 
71   /// Dominance information for this operation, when checking dominance.
72   DominanceInfo *domInfo = nullptr;
73 };
74 } // end anonymous namespace
75 
76 /// Verify the given operation.
77 LogicalResult OperationVerifier::verifyOpAndDominance(Operation &op) {
78   // Verify the operation first.
79   if (failed(verifyOperation(op)))
80     return failure();
81 
82   // Since everything looks structurally ok to this point, we do a dominance
83   // check for any nested regions. We do this as a second pass since malformed
84   // CFG's can cause dominator analysis constructure to crash and we want the
85   // verifier to be resilient to malformed code.
86   DominanceInfo theDomInfo;
87   domInfo = &theDomInfo;
88   if (failed(verifyDominanceOfContainedRegions(op)))
89     return failure();
90 
91   domInfo = nullptr;
92   return success();
93 }
94 
95 LogicalResult OperationVerifier::verifyRegion(Region &region) {
96   if (region.empty())
97     return success();
98 
99   // Verify the first block has no predecessors.
100   auto *firstBB = &region.front();
101   if (!firstBB->hasNoPredecessors())
102     return mlir::emitError(region.getLoc(),
103                            "entry block of region may not have predecessors");
104 
105   // Verify each of the blocks within the region.
106   for (Block &block : region)
107     if (failed(verifyBlock(block)))
108       return failure();
109   return success();
110 }
111 
112 /// Returns true if this block may be valid without terminator. That is if:
113 /// - it does not have a parent region.
114 /// - Or the parent region have a single block and:
115 ///    - This region does not have a parent op.
116 ///    - Or the parent op is unregistered.
117 ///    - Or the parent op has the NoTerminator trait.
118 static bool mayBeValidWithoutTerminator(Block *block) {
119   if (!block->getParent())
120     return true;
121   if (!llvm::hasSingleElement(*block->getParent()))
122     return false;
123   Operation *op = block->getParentOp();
124   return !op || op->mightHaveTrait<OpTrait::NoTerminator>();
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     if (mayBeValidWithoutTerminator(&block))
135       return success();
136     return emitError(block, "empty block: expect at least a terminator");
137   }
138 
139   // Check each operation, and make sure there are no branches out of the
140   // middle of this block.
141   for (auto &op : llvm::make_range(block.begin(), block.end())) {
142     // Only the last instructions is allowed to have successors.
143     if (op.getNumSuccessors() != 0 && &op != &block.back())
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 that this block is not branching to a block of a different
152   // region.
153   for (Block *successor : block.getSuccessors())
154     if (successor->getParent() != block.getParent())
155       return block.back().emitOpError(
156           "branching to block of a different region");
157 
158   // If this block doesn't have to have a terminator, don't require it.
159   if (mayBeValidWithoutTerminator(&block))
160     return success();
161 
162   Operation &terminator = block.back();
163   if (!terminator.mightHaveTrait<OpTrait::IsTerminator>())
164     return block.back().emitError("block with no terminator, has ")
165            << terminator;
166 
167   return success();
168 }
169 
170 LogicalResult OperationVerifier::verifyOperation(Operation &op) {
171   // Check that operands are non-nil and structurally ok.
172   for (auto operand : op.getOperands())
173     if (!operand)
174       return op.emitError("null operand found");
175 
176   /// Verify that all of the attributes are okay.
177   for (auto attr : op.getAttrs()) {
178     // Check for any optional dialect specific attributes.
179     if (auto *dialect = attr.first.getDialect())
180       if (failed(dialect->verifyOperationAttribute(&op, attr)))
181         return failure();
182   }
183 
184   // If we can get operation info for this, check the custom hook.
185   OperationName opName = op.getName();
186   auto *opInfo = opName.getAbstractOperation();
187   if (opInfo && failed(opInfo->verifyInvariants(&op)))
188     return failure();
189 
190   if (unsigned numRegions = op.getNumRegions()) {
191     auto kindInterface = dyn_cast<mlir::RegionKindInterface>(op);
192 
193     // Verify that all child regions are ok.
194     for (unsigned i = 0; i < numRegions; ++i) {
195       Region &region = op.getRegion(i);
196       RegionKind kind =
197           kindInterface ? kindInterface.getRegionKind(i) : RegionKind::SSACFG;
198       // Check that Graph Regions only have a single basic block. This is
199       // similar to the code in SingleBlockImplicitTerminator, but doesn't
200       // require the trait to be specified. This arbitrary limitation is
201       // designed to limit the number of cases that have to be handled by
202       // transforms and conversions.
203       if (op.isRegistered() && kind == RegionKind::Graph) {
204         // Empty regions are fine.
205         if (region.empty())
206           continue;
207 
208         // Non-empty regions must contain a single basic block.
209         if (std::next(region.begin()) != region.end())
210           return op.emitOpError("expects graph region #")
211                  << i << " to have 0 or 1 blocks";
212       }
213       if (failed(verifyRegion(region)))
214         return failure();
215     }
216   }
217 
218   // If this is a registered operation, there is nothing left to do.
219   if (opInfo)
220     return success();
221 
222   // Otherwise, verify that the parent dialect allows un-registered operations.
223   Dialect *dialect = opName.getDialect();
224   if (!dialect) {
225     if (!op.getContext()->allowsUnregisteredDialects()) {
226       return op.emitOpError()
227              << "created with unregistered dialect. If this is "
228                 "intended, please call allowUnregisteredDialects() on the "
229                 "MLIRContext, or use -allow-unregistered-dialect with "
230                 "mlir-opt";
231     }
232     return success();
233   }
234 
235   if (!dialect->allowsUnknownOperations()) {
236     return op.emitError("unregistered operation '")
237            << op.getName() << "' found in dialect ('" << dialect->getNamespace()
238            << "') that does not allow unknown operations";
239   }
240 
241   return success();
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // Dominance Checking
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 /// Verify the dominance of each of the nested blocks within the given operation
305 LogicalResult
306 OperationVerifier::verifyDominanceOfContainedRegions(Operation &op) {
307   for (Region &region : op.getRegions()) {
308     // Verify the dominance of each of the held operations.
309     for (Block &block : region) {
310       // Dominance is only meaningful inside reachable blocks.
311       bool isReachable = domInfo->isReachableFromEntry(&block);
312 
313       for (Operation &op : block) {
314         if (isReachable) {
315           // Check that operands properly dominate this use.
316           for (unsigned operandNo = 0, e = op.getNumOperands(); operandNo != e;
317                ++operandNo) {
318             if (domInfo->properlyDominates(op.getOperand(operandNo), &op))
319               continue;
320 
321             diagnoseInvalidOperandDominance(op, operandNo);
322             return failure();
323           }
324         }
325 
326         // Recursively verify dominance within each operation in the
327         // block, even if the block itself is not reachable, or we are in
328         // a region which doesn't respect dominance.
329         if (op.getNumRegions() != 0)
330           if (failed(verifyDominanceOfContainedRegions(op)))
331             return failure();
332       }
333     }
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().verifyOpAndDominance(*op);
347 }
348