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