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