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 Block *insertionBlock) { 28 while (Region *region = insertionBlock->getParent()) { 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 insertionBlock = parentOp->getBlock(); 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())); 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, bool *inPlaceUpdate) { 78 if (inPlaceUpdate) 79 *inPlaceUpdate = false; 80 81 // If this is a unique'd constant, return failure as we know that it has 82 // already been folded. 83 if (referencedDialects.count(op)) 84 return failure(); 85 86 // Try to fold the operation. 87 SmallVector<Value, 8> results; 88 OpBuilder builder(op); 89 if (failed(tryToFold(builder, op, results, processGeneratedConstants))) 90 return failure(); 91 92 // Check to see if the operation was just updated in place. 93 if (results.empty()) { 94 if (inPlaceUpdate) 95 *inPlaceUpdate = true; 96 return success(); 97 } 98 99 // Constant folding succeeded. We will start replacing this op's uses and 100 // erase this op. Invoke the callback provided by the caller to perform any 101 // pre-replacement action. 102 if (preReplaceAction) 103 preReplaceAction(op); 104 105 // Replace all of the result values and erase the operation. 106 for (unsigned i = 0, e = results.size(); i != e; ++i) 107 op->getResult(i).replaceAllUsesWith(results[i]); 108 op->erase(); 109 return success(); 110 } 111 112 /// Notifies that the given constant `op` should be remove from this 113 /// OperationFolder's internal bookkeeping. 114 void OperationFolder::notifyRemoval(Operation *op) { 115 // Check to see if this operation is uniqued within the folder. 116 auto it = referencedDialects.find(op); 117 if (it == referencedDialects.end()) 118 return; 119 120 // Get the constant value for this operation, this is the value that was used 121 // to unique the operation internally. 122 Attribute constValue; 123 matchPattern(op, m_Constant(&constValue)); 124 assert(constValue); 125 126 // Get the constant map that this operation was uniqued in. 127 auto &uniquedConstants = 128 foldScopes[getInsertionRegion(interfaces, op->getBlock())]; 129 130 // Erase all of the references to this operation. 131 auto type = op->getResult(0).getType(); 132 for (auto *dialect : it->second) 133 uniquedConstants.erase(std::make_tuple(dialect, constValue, type)); 134 referencedDialects.erase(it); 135 } 136 137 /// Clear out any constants cached inside of the folder. 138 void OperationFolder::clear() { 139 foldScopes.clear(); 140 referencedDialects.clear(); 141 } 142 143 /// Tries to perform folding on the given `op`. If successful, populates 144 /// `results` with the results of the folding. 145 LogicalResult OperationFolder::tryToFold( 146 OpBuilder &builder, Operation *op, SmallVectorImpl<Value> &results, 147 function_ref<void(Operation *)> processGeneratedConstants) { 148 SmallVector<Attribute, 8> operandConstants; 149 SmallVector<OpFoldResult, 8> foldResults; 150 151 // If this is a commutative operation, move constants to be trailing operands. 152 if (op->getNumOperands() >= 2 && op->isCommutative()) { 153 std::stable_partition( 154 op->getOpOperands().begin(), op->getOpOperands().end(), 155 [&](OpOperand &O) { return !matchPattern(O.get(), m_Constant()); }); 156 } 157 158 // Check to see if any operands to the operation is constant and whether 159 // the operation knows how to constant fold itself. 160 operandConstants.assign(op->getNumOperands(), Attribute()); 161 for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i) 162 matchPattern(op->getOperand(i), m_Constant(&operandConstants[i])); 163 164 // Attempt to constant fold the operation. 165 if (failed(op->fold(operandConstants, foldResults))) 166 return failure(); 167 168 // Check to see if the operation was just updated in place. 169 if (foldResults.empty()) 170 return success(); 171 assert(foldResults.size() == op->getNumResults()); 172 173 // Create a builder to insert new operations into the entry block of the 174 // insertion region. 175 auto *insertRegion = 176 getInsertionRegion(interfaces, builder.getInsertionBlock()); 177 auto &entry = insertRegion->front(); 178 OpBuilder::InsertionGuard foldGuard(builder); 179 builder.setInsertionPoint(&entry, entry.begin()); 180 181 // Get the constant map for the insertion region of this operation. 182 auto &uniquedConstants = foldScopes[insertRegion]; 183 184 // Create the result constants and replace the results. 185 auto *dialect = op->getDialect(); 186 for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) { 187 assert(!foldResults[i].isNull() && "expected valid OpFoldResult"); 188 189 // Check if the result was an SSA value. 190 if (auto repl = foldResults[i].dyn_cast<Value>()) { 191 results.emplace_back(repl); 192 continue; 193 } 194 195 // Check to see if there is a canonicalized version of this constant. 196 auto res = op->getResult(i); 197 Attribute attrRepl = foldResults[i].get<Attribute>(); 198 if (auto *constOp = 199 tryGetOrCreateConstant(uniquedConstants, dialect, builder, attrRepl, 200 res.getType(), op->getLoc())) { 201 results.push_back(constOp->getResult(0)); 202 continue; 203 } 204 // If materialization fails, cleanup any operations generated for the 205 // previous results and return failure. 206 for (Operation &op : llvm::make_early_inc_range( 207 llvm::make_range(entry.begin(), builder.getInsertionPoint()))) { 208 notifyRemoval(&op); 209 op.erase(); 210 } 211 return failure(); 212 } 213 214 // Process any newly generated operations. 215 if (processGeneratedConstants) { 216 for (auto i = entry.begin(), e = builder.getInsertionPoint(); i != e; ++i) 217 processGeneratedConstants(&*i); 218 } 219 220 return success(); 221 } 222 223 /// Try to get or create a new constant entry. On success this returns the 224 /// constant operation value, nullptr otherwise. 225 Operation *OperationFolder::tryGetOrCreateConstant( 226 ConstantMap &uniquedConstants, Dialect *dialect, OpBuilder &builder, 227 Attribute value, Type type, Location loc) { 228 // Check if an existing mapping already exists. 229 auto constKey = std::make_tuple(dialect, value, type); 230 auto *&constInst = uniquedConstants[constKey]; 231 if (constInst) 232 return constInst; 233 234 // If one doesn't exist, try to materialize one. 235 if (!(constInst = materializeConstant(dialect, builder, value, type, loc))) 236 return nullptr; 237 238 // Check to see if the generated constant is in the expected dialect. 239 auto *newDialect = constInst->getDialect(); 240 if (newDialect == dialect) { 241 referencedDialects[constInst].push_back(dialect); 242 return constInst; 243 } 244 245 // If it isn't, then we also need to make sure that the mapping for the new 246 // dialect is valid. 247 auto newKey = std::make_tuple(newDialect, value, type); 248 249 // If an existing operation in the new dialect already exists, delete the 250 // materialized operation in favor of the existing one. 251 if (auto *existingOp = uniquedConstants.lookup(newKey)) { 252 constInst->erase(); 253 referencedDialects[existingOp].push_back(dialect); 254 return constInst = existingOp; 255 } 256 257 // Otherwise, update the new dialect to the materialized operation. 258 referencedDialects[constInst].assign({dialect, newDialect}); 259 auto newIt = uniquedConstants.insert({newKey, constInst}); 260 return newIt.first->second; 261 } 262