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