1 //===- CSE.cpp - Common Sub-expression Elimination ------------------------===// 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 transformation pass performs a simple common sub-expression elimination 10 // algorithm on operations within a region. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PassDetail.h" 15 #include "mlir/IR/Dominance.h" 16 #include "mlir/Pass/Pass.h" 17 #include "mlir/Transforms/Passes.h" 18 #include "mlir/Transforms/Utils.h" 19 #include "llvm/ADT/DenseMapInfo.h" 20 #include "llvm/ADT/Hashing.h" 21 #include "llvm/ADT/ScopedHashTable.h" 22 #include "llvm/Support/Allocator.h" 23 #include "llvm/Support/RecyclingAllocator.h" 24 #include <deque> 25 26 using namespace mlir; 27 28 namespace { 29 struct SimpleOperationInfo : public llvm::DenseMapInfo<Operation *> { 30 static unsigned getHashValue(const Operation *opC) { 31 return OperationEquivalence::computeHash(const_cast<Operation *>(opC)); 32 } 33 static bool isEqual(const Operation *lhsC, const Operation *rhsC) { 34 auto *lhs = const_cast<Operation *>(lhsC); 35 auto *rhs = const_cast<Operation *>(rhsC); 36 if (lhs == rhs) 37 return true; 38 if (lhs == getTombstoneKey() || lhs == getEmptyKey() || 39 rhs == getTombstoneKey() || rhs == getEmptyKey()) 40 return false; 41 return OperationEquivalence::isEquivalentTo(const_cast<Operation *>(lhsC), 42 const_cast<Operation *>(rhsC)); 43 } 44 }; 45 } // end anonymous namespace 46 47 namespace { 48 /// Simple common sub-expression elimination. 49 struct CSE : public CSEBase<CSE> { 50 /// Shared implementation of operation elimination and scoped map definitions. 51 using AllocatorTy = llvm::RecyclingAllocator< 52 llvm::BumpPtrAllocator, 53 llvm::ScopedHashTableVal<Operation *, Operation *>>; 54 using ScopedMapTy = llvm::ScopedHashTable<Operation *, Operation *, 55 SimpleOperationInfo, AllocatorTy>; 56 57 /// Represents a single entry in the depth first traversal of a CFG. 58 struct CFGStackNode { 59 CFGStackNode(ScopedMapTy &knownValues, DominanceInfoNode *node) 60 : scope(knownValues), node(node), childIterator(node->begin()), 61 processed(false) {} 62 63 /// Scope for the known values. 64 ScopedMapTy::ScopeTy scope; 65 66 DominanceInfoNode *node; 67 DominanceInfoNode::const_iterator childIterator; 68 69 /// If this node has been fully processed yet or not. 70 bool processed; 71 }; 72 73 /// Attempt to eliminate a redundant operation. Returns success if the 74 /// operation was marked for removal, failure otherwise. 75 LogicalResult simplifyOperation(ScopedMapTy &knownValues, Operation *op, 76 bool hasSSADominance); 77 void simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo, 78 Block *bb, bool hasSSADominance); 79 void simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo, 80 Region ®ion); 81 82 void runOnOperation() override; 83 84 private: 85 /// Operations marked as dead and to be erased. 86 std::vector<Operation *> opsToErase; 87 }; 88 } // end anonymous namespace 89 90 /// Attempt to eliminate a redundant operation. 91 LogicalResult CSE::simplifyOperation(ScopedMapTy &knownValues, Operation *op, 92 bool hasSSADominance) { 93 // Don't simplify terminator operations. 94 if (op->hasTrait<OpTrait::IsTerminator>()) 95 return failure(); 96 97 // If the operation is already trivially dead just add it to the erase list. 98 if (isOpTriviallyDead(op)) { 99 opsToErase.push_back(op); 100 ++numDCE; 101 return success(); 102 } 103 104 // Don't simplify operations with nested blocks. We don't currently model 105 // equality comparisons correctly among other things. It is also unclear 106 // whether we would want to CSE such operations. 107 if (op->getNumRegions() != 0) 108 return failure(); 109 110 // TODO: We currently only eliminate non side-effecting 111 // operations. 112 if (!MemoryEffectOpInterface::hasNoEffect(op)) 113 return failure(); 114 115 // Look for an existing definition for the operation. 116 if (auto *existing = knownValues.lookup(op)) { 117 118 // If we find one then replace all uses of the current operation with the 119 // existing one and mark it for deletion. We can only replace an operand in 120 // an operation if it has not been visited yet. 121 if (hasSSADominance) { 122 // If the region has SSA dominance, then we are guaranteed to have not 123 // visited any use of the current operation. 124 op->replaceAllUsesWith(existing); 125 opsToErase.push_back(op); 126 } else { 127 // When the region does not have SSA dominance, we need to check if we 128 // have visited a use before replacing any use. 129 for (auto it : llvm::zip(op->getResults(), existing->getResults())) { 130 std::get<0>(it).replaceUsesWithIf( 131 std::get<1>(it), [&](OpOperand &operand) { 132 return !knownValues.count(operand.getOwner()); 133 }); 134 } 135 136 // There may be some remaining uses of the operation. 137 if (op->use_empty()) 138 opsToErase.push_back(op); 139 } 140 141 // If the existing operation has an unknown location and the current 142 // operation doesn't, then set the existing op's location to that of the 143 // current op. 144 if (existing->getLoc().isa<UnknownLoc>() && 145 !op->getLoc().isa<UnknownLoc>()) { 146 existing->setLoc(op->getLoc()); 147 } 148 149 ++numCSE; 150 return success(); 151 } 152 153 // Otherwise, we add this operation to the known values map. 154 knownValues.insert(op, op); 155 return failure(); 156 } 157 158 void CSE::simplifyBlock(ScopedMapTy &knownValues, DominanceInfo &domInfo, 159 Block *bb, bool hasSSADominance) { 160 for (auto &inst : *bb) { 161 // If the operation is simplified, we don't process any held regions. 162 if (succeeded(simplifyOperation(knownValues, &inst, hasSSADominance))) 163 continue; 164 165 // If this operation is isolated above, we can't process nested regions with 166 // the given 'knownValues' map. This would cause the insertion of implicit 167 // captures in explicit capture only regions. 168 if (inst.mightHaveTrait<OpTrait::IsIsolatedFromAbove>()) { 169 ScopedMapTy nestedKnownValues; 170 for (auto ®ion : inst.getRegions()) 171 simplifyRegion(nestedKnownValues, domInfo, region); 172 continue; 173 } 174 175 // Otherwise, process nested regions normally. 176 for (auto ®ion : inst.getRegions()) 177 simplifyRegion(knownValues, domInfo, region); 178 } 179 } 180 181 void CSE::simplifyRegion(ScopedMapTy &knownValues, DominanceInfo &domInfo, 182 Region ®ion) { 183 // If the region is empty there is nothing to do. 184 if (region.empty()) 185 return; 186 187 bool hasSSADominance = domInfo.hasDominanceInfo(®ion); 188 189 // If the region only contains one block, then simplify it directly. 190 if (std::next(region.begin()) == region.end()) { 191 ScopedMapTy::ScopeTy scope(knownValues); 192 simplifyBlock(knownValues, domInfo, ®ion.front(), hasSSADominance); 193 return; 194 } 195 196 // If the region does not have dominanceInfo, then skip it. 197 // TODO: Regions without SSA dominance should define a different 198 // traversal order which is appropriate and can be used here. 199 if (!hasSSADominance) 200 return; 201 202 // Note, deque is being used here because there was significant performance 203 // gains over vector when the container becomes very large due to the 204 // specific access patterns. If/when these performance issues are no 205 // longer a problem we can change this to vector. For more information see 206 // the llvm mailing list discussion on this: 207 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html 208 std::deque<std::unique_ptr<CFGStackNode>> stack; 209 210 // Process the nodes of the dom tree for this region. 211 stack.emplace_back(std::make_unique<CFGStackNode>( 212 knownValues, domInfo.getRootNode(®ion))); 213 214 while (!stack.empty()) { 215 auto ¤tNode = stack.back(); 216 217 // Check to see if we need to process this node. 218 if (!currentNode->processed) { 219 currentNode->processed = true; 220 simplifyBlock(knownValues, domInfo, currentNode->node->getBlock(), 221 hasSSADominance); 222 } 223 224 // Otherwise, check to see if we need to process a child node. 225 if (currentNode->childIterator != currentNode->node->end()) { 226 auto *childNode = *(currentNode->childIterator++); 227 stack.emplace_back( 228 std::make_unique<CFGStackNode>(knownValues, childNode)); 229 } else { 230 // Finally, if the node and all of its children have been processed 231 // then we delete the node. 232 stack.pop_back(); 233 } 234 } 235 } 236 237 void CSE::runOnOperation() { 238 /// A scoped hash table of defining operations within a region. 239 ScopedMapTy knownValues; 240 241 DominanceInfo &domInfo = getAnalysis<DominanceInfo>(); 242 for (Region ®ion : getOperation()->getRegions()) 243 simplifyRegion(knownValues, domInfo, region); 244 245 // If no operations were erased, then we mark all analyses as preserved. 246 if (opsToErase.empty()) 247 return markAllAnalysesPreserved(); 248 249 /// Erase any operations that were marked as dead during simplification. 250 for (auto *op : opsToErase) 251 op->erase(); 252 opsToErase.clear(); 253 254 // We currently don't remove region operations, so mark dominance as 255 // preserved. 256 markAnalysesPreserved<DominanceInfo, PostDominanceInfo>(); 257 } 258 259 std::unique_ptr<Pass> mlir::createCSEPass() { return std::make_unique<CSE>(); } 260