1 //===- FoldUtils.cpp ---- Fold Utilities ----------------------------------===//
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 defines various operation fold utilities. These utilities are
10 // intended to be used by passes to unify and simply their logic.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Transforms/FoldUtils.h"
15 
16 #include "mlir/Dialect/StandardOps/IR/Ops.h"
17 #include "mlir/IR/Builders.h"
18 #include "mlir/IR/Matchers.h"
19 #include "mlir/IR/Operation.h"
20 
21 using namespace mlir;
22 
23 /// Given an operation, find the parent region that folded constants should be
24 /// inserted into.
25 static Region *getInsertionRegion(
26     DialectInterfaceCollection<OpFolderDialectInterface> &interfaces,
27     Operation *op) {
28   while (Region *region = op->getParentRegion()) {
29     // Insert in this region for any of the following scenarios:
30     //  * The parent is unregistered, or is known to be isolated from above.
31     //  * The parent is a top-level operation.
32     auto *parentOp = region->getParentOp();
33     if (!parentOp->isRegistered() || parentOp->isKnownIsolatedFromAbove() ||
34         !parentOp->getBlock())
35       return region;
36 
37     // Otherwise, check if this region is a desired insertion region.
38     auto *interface = interfaces.getInterfaceFor(parentOp);
39     if (LLVM_UNLIKELY(interface && interface->shouldMaterializeInto(region)))
40       return region;
41 
42     // Traverse up the parent looking for an insertion region.
43     op = parentOp;
44   }
45   llvm_unreachable("expected valid insertion region");
46 }
47 
48 /// A utility function used to materialize a constant for a given attribute and
49 /// type. On success, a valid constant value is returned. Otherwise, null is
50 /// returned
51 static Operation *materializeConstant(Dialect *dialect, OpBuilder &builder,
52                                       Attribute value, Type type,
53                                       Location loc) {
54   auto insertPt = builder.getInsertionPoint();
55   (void)insertPt;
56 
57   // Ask the dialect to materialize a constant operation for this value.
58   if (auto *constOp = dialect->materializeConstant(builder, value, type, loc)) {
59     assert(insertPt == builder.getInsertionPoint());
60     assert(matchPattern(constOp, m_Constant(&value)));
61     return constOp;
62   }
63 
64   // If the dialect is unable to materialize a constant, check to see if the
65   // standard constant can be used.
66   if (ConstantOp::isBuildableWith(value, type))
67     return builder.create<ConstantOp>(loc, type, value);
68   return nullptr;
69 }
70 
71 //===----------------------------------------------------------------------===//
72 // OperationFolder
73 //===----------------------------------------------------------------------===//
74 
75 LogicalResult OperationFolder::tryToFold(
76     Operation *op, function_ref<void(Operation *)> processGeneratedConstants,
77     function_ref<void(Operation *)> preReplaceAction) {
78   // If this is a unique'd constant, return failure as we know that it has
79   // already been folded.
80   if (referencedDialects.count(op))
81     return failure();
82 
83   // Try to fold the operation.
84   SmallVector<Value, 8> results;
85   if (failed(tryToFold(op, results, processGeneratedConstants)))
86     return failure();
87 
88   // Constant folding succeeded. We will start replacing this op's uses and
89   // eventually erase this op. Invoke the callback provided by the caller to
90   // perform any pre-replacement action.
91   if (preReplaceAction)
92     preReplaceAction(op);
93 
94   // Check to see if the operation was just updated in place.
95   if (results.empty())
96     return success();
97 
98   // Otherwise, replace all of the result values and erase the operation.
99   for (unsigned i = 0, e = results.size(); i != e; ++i)
100     op->getResult(i).replaceAllUsesWith(results[i]);
101   op->erase();
102   return success();
103 }
104 
105 /// Notifies that the given constant `op` should be remove from this
106 /// OperationFolder's internal bookkeeping.
107 void OperationFolder::notifyRemoval(Operation *op) {
108   // Check to see if this operation is uniqued within the folder.
109   auto it = referencedDialects.find(op);
110   if (it == referencedDialects.end())
111     return;
112 
113   // Get the constant value for this operation, this is the value that was used
114   // to unique the operation internally.
115   Attribute constValue;
116   matchPattern(op, m_Constant(&constValue));
117   assert(constValue);
118 
119   // Get the constant map that this operation was uniqued in.
120   auto &uniquedConstants = foldScopes[getInsertionRegion(interfaces, op)];
121 
122   // Erase all of the references to this operation.
123   auto type = op->getResult(0).getType();
124   for (auto *dialect : it->second)
125     uniquedConstants.erase(std::make_tuple(dialect, constValue, type));
126   referencedDialects.erase(it);
127 }
128 
129 /// Tries to perform folding on the given `op`. If successful, populates
130 /// `results` with the results of the folding.
131 LogicalResult OperationFolder::tryToFold(
132     Operation *op, SmallVectorImpl<Value> &results,
133     function_ref<void(Operation *)> processGeneratedConstants) {
134   SmallVector<Attribute, 8> operandConstants;
135   SmallVector<OpFoldResult, 8> foldResults;
136 
137   // If this is a commutative operation, move constants to be trailing operands.
138   if (op->getNumOperands() >= 2 && op->isCommutative()) {
139     std::stable_partition(
140         op->getOpOperands().begin(), op->getOpOperands().end(),
141         [&](OpOperand &O) { return !matchPattern(O.get(), m_Constant()); });
142   }
143 
144   // Check to see if any operands to the operation is constant and whether
145   // the operation knows how to constant fold itself.
146   operandConstants.assign(op->getNumOperands(), Attribute());
147   for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i)
148     matchPattern(op->getOperand(i), m_Constant(&operandConstants[i]));
149 
150   // Attempt to constant fold the operation.
151   if (failed(op->fold(operandConstants, foldResults)))
152     return failure();
153 
154   // Check to see if the operation was just updated in place.
155   if (foldResults.empty())
156     return success();
157   assert(foldResults.size() == op->getNumResults());
158 
159   // Create a builder to insert new operations into the entry block of the
160   // insertion region.
161   auto *insertRegion = getInsertionRegion(interfaces, op);
162   auto &entry = insertRegion->front();
163   OpBuilder builder(&entry, entry.begin());
164 
165   // Get the constant map for the insertion region of this operation.
166   auto &uniquedConstants = foldScopes[insertRegion];
167 
168   // Create the result constants and replace the results.
169   auto *dialect = op->getDialect();
170   for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) {
171     assert(!foldResults[i].isNull() && "expected valid OpFoldResult");
172 
173     // Check if the result was an SSA value.
174     if (auto repl = foldResults[i].dyn_cast<Value>()) {
175       results.emplace_back(repl);
176       continue;
177     }
178 
179     // Check to see if there is a canonicalized version of this constant.
180     auto res = op->getResult(i);
181     Attribute attrRepl = foldResults[i].get<Attribute>();
182     if (auto *constOp =
183             tryGetOrCreateConstant(uniquedConstants, dialect, builder, attrRepl,
184                                    res.getType(), op->getLoc())) {
185       results.push_back(constOp->getResult(0));
186       continue;
187     }
188     // If materialization fails, cleanup any operations generated for the
189     // previous results and return failure.
190     for (Operation &op : llvm::make_early_inc_range(
191              llvm::make_range(entry.begin(), builder.getInsertionPoint()))) {
192       notifyRemoval(&op);
193       op.erase();
194     }
195     return failure();
196   }
197 
198   // Process any newly generated operations.
199   if (processGeneratedConstants) {
200     for (auto i = entry.begin(), e = builder.getInsertionPoint(); i != e; ++i)
201       processGeneratedConstants(&*i);
202   }
203 
204   return success();
205 }
206 
207 /// Try to get or create a new constant entry. On success this returns the
208 /// constant operation value, nullptr otherwise.
209 Operation *OperationFolder::tryGetOrCreateConstant(
210     ConstantMap &uniquedConstants, Dialect *dialect, OpBuilder &builder,
211     Attribute value, Type type, Location loc) {
212   // Check if an existing mapping already exists.
213   auto constKey = std::make_tuple(dialect, value, type);
214   auto *&constInst = uniquedConstants[constKey];
215   if (constInst)
216     return constInst;
217 
218   // If one doesn't exist, try to materialize one.
219   if (!(constInst = materializeConstant(dialect, builder, value, type, loc)))
220     return nullptr;
221 
222   // Check to see if the generated constant is in the expected dialect.
223   auto *newDialect = constInst->getDialect();
224   if (newDialect == dialect) {
225     referencedDialects[constInst].push_back(dialect);
226     return constInst;
227   }
228 
229   // If it isn't, then we also need to make sure that the mapping for the new
230   // dialect is valid.
231   auto newKey = std::make_tuple(newDialect, value, type);
232 
233   // If an existing operation in the new dialect already exists, delete the
234   // materialized operation in favor of the existing one.
235   if (auto *existingOp = uniquedConstants.lookup(newKey)) {
236     constInst->erase();
237     referencedDialects[existingOp].push_back(dialect);
238     return constInst = existingOp;
239   }
240 
241   // Otherwise, update the new dialect to the materialized operation.
242   referencedDialects[constInst].assign({dialect, newDialect});
243   auto newIt = uniquedConstants.insert({newKey, constInst});
244   return newIt.first->second;
245 }
246