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/IR/Builders.h" 17 #include "mlir/IR/Matchers.h" 18 #include "mlir/IR/Operation.h" 19 20 using namespace mlir; 21 22 /// Given an operation, find the parent region that folded constants should be 23 /// inserted into. 24 static Region * 25 getInsertionRegion(DialectInterfaceCollection<DialectFoldInterface> &interfaces, 26 Block *insertionBlock) { 27 while (Region *region = insertionBlock->getParent()) { 28 // Insert in this region for any of the following scenarios: 29 // * The parent is unregistered, or is known to be isolated from above. 30 // * The parent is a top-level operation. 31 auto *parentOp = region->getParentOp(); 32 if (parentOp->mightHaveTrait<OpTrait::IsIsolatedFromAbove>() || 33 !parentOp->getBlock()) 34 return region; 35 36 // Otherwise, check if this region is a desired insertion region. 37 auto *interface = interfaces.getInterfaceFor(parentOp); 38 if (LLVM_UNLIKELY(interface && interface->shouldMaterializeInto(region))) 39 return region; 40 41 // Traverse up the parent looking for an insertion region. 42 insertionBlock = parentOp->getBlock(); 43 } 44 llvm_unreachable("expected valid insertion region"); 45 } 46 47 /// A utility function used to materialize a constant for a given attribute and 48 /// type. On success, a valid constant value is returned. Otherwise, null is 49 /// returned 50 static Operation *materializeConstant(Dialect *dialect, OpBuilder &builder, 51 Attribute value, Type type, 52 Location loc) { 53 auto insertPt = builder.getInsertionPoint(); 54 (void)insertPt; 55 56 // Ask the dialect to materialize a constant operation for this value. 57 if (auto *constOp = dialect->materializeConstant(builder, value, type, loc)) { 58 assert(insertPt == builder.getInsertionPoint()); 59 assert(matchPattern(constOp, m_Constant())); 60 return constOp; 61 } 62 63 return nullptr; 64 } 65 66 //===----------------------------------------------------------------------===// 67 // OperationFolder 68 //===----------------------------------------------------------------------===// 69 70 LogicalResult OperationFolder::tryToFold(Operation *op, bool *inPlaceUpdate) { 71 if (inPlaceUpdate) 72 *inPlaceUpdate = false; 73 74 // If this is a unique'd constant, return failure as we know that it has 75 // already been folded. 76 if (isFolderOwnedConstant(op)) { 77 // Check to see if we should rehoist, i.e. if a non-constant operation was 78 // inserted before this one. 79 Block *opBlock = op->getBlock(); 80 if (&opBlock->front() != op && !isFolderOwnedConstant(op->getPrevNode())) 81 op->moveBefore(&opBlock->front()); 82 return failure(); 83 } 84 85 // Try to fold the operation. 86 SmallVector<Value, 8> results; 87 if (failed(tryToFold(op, results))) 88 return failure(); 89 90 // Check to see if the operation was just updated in place. 91 if (results.empty()) { 92 if (inPlaceUpdate) 93 *inPlaceUpdate = true; 94 if (auto *rewriteListener = dyn_cast_if_present<RewriterBase::Listener>( 95 rewriter.getListener())) { 96 // Folding API does not notify listeners, so we have to notify manually. 97 rewriteListener->notifyOperationModified(op); 98 } 99 return success(); 100 } 101 102 // Constant folding succeeded. Replace all of the result values and erase the 103 // operation. 104 notifyRemoval(op); 105 rewriter.replaceOp(op, results); 106 return success(); 107 } 108 109 bool OperationFolder::insertKnownConstant(Operation *op, Attribute constValue) { 110 Block *opBlock = op->getBlock(); 111 112 // If this is a constant we unique'd, we don't need to insert, but we can 113 // check to see if we should rehoist it. 114 if (isFolderOwnedConstant(op)) { 115 if (&opBlock->front() != op && !isFolderOwnedConstant(op->getPrevNode())) 116 op->moveBefore(&opBlock->front()); 117 return true; 118 } 119 120 // Get the constant value of the op if necessary. 121 if (!constValue) { 122 matchPattern(op, m_Constant(&constValue)); 123 assert(constValue && "expected `op` to be a constant"); 124 } else { 125 // Ensure that the provided constant was actually correct. 126 #ifndef NDEBUG 127 Attribute expectedValue; 128 matchPattern(op, m_Constant(&expectedValue)); 129 assert( 130 expectedValue == constValue && 131 "provided constant value was not the expected value of the constant"); 132 #endif 133 } 134 135 // Check for an existing constant operation for the attribute value. 136 Region *insertRegion = getInsertionRegion(interfaces, opBlock); 137 auto &uniquedConstants = foldScopes[insertRegion]; 138 Operation *&folderConstOp = uniquedConstants[std::make_tuple( 139 op->getDialect(), constValue, *op->result_type_begin())]; 140 141 // If there is an existing constant, replace `op`. 142 if (folderConstOp) { 143 notifyRemoval(op); 144 rewriter.replaceOp(op, folderConstOp->getResults()); 145 return false; 146 } 147 148 // Otherwise, we insert `op`. If `op` is in the insertion block and is either 149 // already at the front of the block, or the previous operation is already a 150 // constant we unique'd (i.e. one we inserted), then we don't need to do 151 // anything. Otherwise, we move the constant to the insertion block. 152 Block *insertBlock = &insertRegion->front(); 153 if (opBlock != insertBlock || (&insertBlock->front() != op && 154 !isFolderOwnedConstant(op->getPrevNode()))) 155 op->moveBefore(&insertBlock->front()); 156 157 folderConstOp = op; 158 referencedDialects[op].push_back(op->getDialect()); 159 return true; 160 } 161 162 /// Notifies that the given constant `op` should be remove from this 163 /// OperationFolder's internal bookkeeping. 164 void OperationFolder::notifyRemoval(Operation *op) { 165 // Check to see if this operation is uniqued within the folder. 166 auto it = referencedDialects.find(op); 167 if (it == referencedDialects.end()) 168 return; 169 170 // Get the constant value for this operation, this is the value that was used 171 // to unique the operation internally. 172 Attribute constValue; 173 matchPattern(op, m_Constant(&constValue)); 174 assert(constValue); 175 176 // Get the constant map that this operation was uniqued in. 177 auto &uniquedConstants = 178 foldScopes[getInsertionRegion(interfaces, op->getBlock())]; 179 180 // Erase all of the references to this operation. 181 auto type = op->getResult(0).getType(); 182 for (auto *dialect : it->second) 183 uniquedConstants.erase(std::make_tuple(dialect, constValue, type)); 184 referencedDialects.erase(it); 185 } 186 187 /// Clear out any constants cached inside of the folder. 188 void OperationFolder::clear() { 189 foldScopes.clear(); 190 referencedDialects.clear(); 191 } 192 193 /// Get or create a constant using the given builder. On success this returns 194 /// the constant operation, nullptr otherwise. 195 Value OperationFolder::getOrCreateConstant(Block *block, Dialect *dialect, 196 Attribute value, Type type, 197 Location loc) { 198 // Find an insertion point for the constant. 199 auto *insertRegion = getInsertionRegion(interfaces, block); 200 auto &entry = insertRegion->front(); 201 rewriter.setInsertionPoint(&entry, entry.begin()); 202 203 // Get the constant map for the insertion region of this operation. 204 auto &uniquedConstants = foldScopes[insertRegion]; 205 Operation *constOp = 206 tryGetOrCreateConstant(uniquedConstants, dialect, value, type, loc); 207 return constOp ? constOp->getResult(0) : Value(); 208 } 209 210 bool OperationFolder::isFolderOwnedConstant(Operation *op) const { 211 return referencedDialects.count(op); 212 } 213 214 /// Tries to perform folding on the given `op`. If successful, populates 215 /// `results` with the results of the folding. 216 LogicalResult OperationFolder::tryToFold(Operation *op, 217 SmallVectorImpl<Value> &results) { 218 SmallVector<OpFoldResult, 8> foldResults; 219 if (failed(op->fold(foldResults)) || 220 failed(processFoldResults(op, results, foldResults))) 221 return failure(); 222 return success(); 223 } 224 225 LogicalResult 226 OperationFolder::processFoldResults(Operation *op, 227 SmallVectorImpl<Value> &results, 228 ArrayRef<OpFoldResult> foldResults) { 229 // Check to see if the operation was just updated in place. 230 if (foldResults.empty()) 231 return success(); 232 assert(foldResults.size() == op->getNumResults()); 233 234 // Create a builder to insert new operations into the entry block of the 235 // insertion region. 236 auto *insertRegion = getInsertionRegion(interfaces, op->getBlock()); 237 auto &entry = insertRegion->front(); 238 rewriter.setInsertionPoint(&entry, entry.begin()); 239 240 // Get the constant map for the insertion region of this operation. 241 auto &uniquedConstants = foldScopes[insertRegion]; 242 243 // Create the result constants and replace the results. 244 auto *dialect = op->getDialect(); 245 for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) { 246 assert(!foldResults[i].isNull() && "expected valid OpFoldResult"); 247 248 // Check if the result was an SSA value. 249 if (auto repl = llvm::dyn_cast_if_present<Value>(foldResults[i])) { 250 results.emplace_back(repl); 251 continue; 252 } 253 254 // Check to see if there is a canonicalized version of this constant. 255 auto res = op->getResult(i); 256 Attribute attrRepl = foldResults[i].get<Attribute>(); 257 if (auto *constOp = tryGetOrCreateConstant( 258 uniquedConstants, dialect, attrRepl, res.getType(), op->getLoc())) { 259 // Ensure that this constant dominates the operation we are replacing it 260 // with. This may not automatically happen if the operation being folded 261 // was inserted before the constant within the insertion block. 262 Block *opBlock = op->getBlock(); 263 if (opBlock == constOp->getBlock() && &opBlock->front() != constOp) 264 constOp->moveBefore(&opBlock->front()); 265 266 results.push_back(constOp->getResult(0)); 267 continue; 268 } 269 // If materialization fails, cleanup any operations generated for the 270 // previous results and return failure. 271 for (Operation &op : llvm::make_early_inc_range( 272 llvm::make_range(entry.begin(), rewriter.getInsertionPoint()))) { 273 notifyRemoval(&op); 274 rewriter.eraseOp(&op); 275 } 276 277 results.clear(); 278 return failure(); 279 } 280 281 return success(); 282 } 283 284 /// Try to get or create a new constant entry. On success this returns the 285 /// constant operation value, nullptr otherwise. 286 Operation * 287 OperationFolder::tryGetOrCreateConstant(ConstantMap &uniquedConstants, 288 Dialect *dialect, Attribute value, 289 Type type, Location loc) { 290 // Check if an existing mapping already exists. 291 auto constKey = std::make_tuple(dialect, value, type); 292 Operation *&constOp = uniquedConstants[constKey]; 293 if (constOp) 294 return constOp; 295 296 // If one doesn't exist, try to materialize one. 297 if (!(constOp = materializeConstant(dialect, rewriter, value, type, loc))) 298 return nullptr; 299 300 // Check to see if the generated constant is in the expected dialect. 301 auto *newDialect = constOp->getDialect(); 302 if (newDialect == dialect) { 303 referencedDialects[constOp].push_back(dialect); 304 return constOp; 305 } 306 307 // If it isn't, then we also need to make sure that the mapping for the new 308 // dialect is valid. 309 auto newKey = std::make_tuple(newDialect, value, type); 310 311 // If an existing operation in the new dialect already exists, delete the 312 // materialized operation in favor of the existing one. 313 if (auto *existingOp = uniquedConstants.lookup(newKey)) { 314 notifyRemoval(constOp); 315 rewriter.eraseOp(constOp); 316 referencedDialects[existingOp].push_back(dialect); 317 return constOp = existingOp; 318 } 319 320 // Otherwise, update the new dialect to the materialized operation. 321 referencedDialects[constOp].assign({dialect, newDialect}); 322 auto newIt = uniquedConstants.insert({newKey, constOp}); 323 return newIt.first->second; 324 } 325