1 //===- FoldUtils.cpp ---- Fold Utilities ----------------------------------===// 2 // 3 // Part of the MLIR 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/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 // Check to see if any operands to the operation is constant and whether 138 // the operation knows how to constant fold itself. 139 operandConstants.assign(op->getNumOperands(), Attribute()); 140 for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i) 141 matchPattern(op->getOperand(i), m_Constant(&operandConstants[i])); 142 143 // If this is a commutative binary operation with a constant on the left 144 // side move it to the right side. 145 if (operandConstants.size() == 2 && operandConstants[0] && 146 !operandConstants[1] && op->isCommutative()) { 147 std::swap(op->getOpOperand(0), op->getOpOperand(1)); 148 std::swap(operandConstants[0], operandConstants[1]); 149 } 150 151 // Attempt to constant fold the operation. 152 if (failed(op->fold(operandConstants, foldResults))) 153 return failure(); 154 155 // Check to see if the operation was just updated in place. 156 if (foldResults.empty()) 157 return success(); 158 assert(foldResults.size() == op->getNumResults()); 159 160 // Create a builder to insert new operations into the entry block of the 161 // insertion region. 162 auto *insertRegion = getInsertionRegion(interfaces, op); 163 auto &entry = insertRegion->front(); 164 OpBuilder builder(&entry, entry.begin()); 165 166 // Get the constant map for the insertion region of this operation. 167 auto &uniquedConstants = foldScopes[insertRegion]; 168 169 // Create the result constants and replace the results. 170 auto *dialect = op->getDialect(); 171 for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) { 172 assert(!foldResults[i].isNull() && "expected valid OpFoldResult"); 173 174 // Check if the result was an SSA value. 175 if (auto repl = foldResults[i].dyn_cast<Value>()) { 176 results.emplace_back(repl); 177 continue; 178 } 179 180 // Check to see if there is a canonicalized version of this constant. 181 auto res = op->getResult(i); 182 Attribute attrRepl = foldResults[i].get<Attribute>(); 183 if (auto *constOp = 184 tryGetOrCreateConstant(uniquedConstants, dialect, builder, attrRepl, 185 res.getType(), op->getLoc())) { 186 results.push_back(constOp->getResult(0)); 187 continue; 188 } 189 // If materialization fails, cleanup any operations generated for the 190 // previous results and return failure. 191 for (Operation &op : llvm::make_early_inc_range( 192 llvm::make_range(entry.begin(), builder.getInsertionPoint()))) { 193 notifyRemoval(&op); 194 op.erase(); 195 } 196 return failure(); 197 } 198 199 // Process any newly generated operations. 200 if (processGeneratedConstants) { 201 for (auto i = entry.begin(), e = builder.getInsertionPoint(); i != e; ++i) 202 processGeneratedConstants(&*i); 203 } 204 205 return success(); 206 } 207 208 /// Try to get or create a new constant entry. On success this returns the 209 /// constant operation value, nullptr otherwise. 210 Operation *OperationFolder::tryGetOrCreateConstant( 211 ConstantMap &uniquedConstants, Dialect *dialect, OpBuilder &builder, 212 Attribute value, Type type, Location loc) { 213 // Check if an existing mapping already exists. 214 auto constKey = std::make_tuple(dialect, value, type); 215 auto *&constInst = uniquedConstants[constKey]; 216 if (constInst) 217 return constInst; 218 219 // If one doesn't exist, try to materialize one. 220 if (!(constInst = materializeConstant(dialect, builder, value, type, loc))) 221 return nullptr; 222 223 // Check to see if the generated constant is in the expected dialect. 224 auto *newDialect = constInst->getDialect(); 225 if (newDialect == dialect) { 226 referencedDialects[constInst].push_back(dialect); 227 return constInst; 228 } 229 230 // If it isn't, then we also need to make sure that the mapping for the new 231 // dialect is valid. 232 auto newKey = std::make_tuple(newDialect, value, type); 233 234 // If an existing operation in the new dialect already exists, delete the 235 // materialized operation in favor of the existing one. 236 if (auto *existingOp = uniquedConstants.lookup(newKey)) { 237 constInst->erase(); 238 referencedDialects[existingOp].push_back(dialect); 239 return constInst = existingOp; 240 } 241 242 // Otherwise, update the new dialect to the materialized operation. 243 referencedDialects[constInst].assign({dialect, newDialect}); 244 auto newIt = uniquedConstants.insert({newKey, constInst}); 245 return newIt.first->second; 246 } 247