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