Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 1 | //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass reassociates n-ary add expressions and eliminates the redundancy |
| 11 | // exposed by the reassociation. |
| 12 | // |
| 13 | // A motivating example: |
| 14 | // |
| 15 | // void foo(int a, int b) { |
| 16 | // bar(a + b); |
| 17 | // bar((a + 2) + b); |
| 18 | // } |
| 19 | // |
| 20 | // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify |
| 21 | // the above code to |
| 22 | // |
| 23 | // int t = a + b; |
| 24 | // bar(t); |
| 25 | // bar(t + 2); |
| 26 | // |
| 27 | // However, the Reassociate pass is unable to do that because it processes each |
| 28 | // instruction individually and believes (a + 2) + b is the best form according |
| 29 | // to its rank system. |
| 30 | // |
| 31 | // To address this limitation, NaryReassociate reassociates an expression in a |
| 32 | // form that reuses existing instructions. As a result, NaryReassociate can |
| 33 | // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that |
| 34 | // (a + b) is computed before. |
| 35 | // |
| 36 | // NaryReassociate works as follows. For every instruction in the form of (a + |
| 37 | // b) + c, it checks whether a + c or b + c is already computed by a dominating |
| 38 | // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b + |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 39 | // c) + a and removes the redundancy accordingly. To efficiently look up whether |
| 40 | // an expression is computed before, we store each instruction seen and its SCEV |
| 41 | // into an SCEV-to-instruction map. |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 42 | // |
| 43 | // Although the algorithm pattern-matches only ternary additions, it |
| 44 | // automatically handles many >3-ary expressions by walking through the function |
| 45 | // in the depth-first order. For example, given |
| 46 | // |
| 47 | // (a + c) + d |
| 48 | // ((a + b) + c) + d |
| 49 | // |
| 50 | // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites |
| 51 | // ((a + c) + b) + d into ((a + c) + d) + b. |
| 52 | // |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 53 | // Finally, the above dominator-based algorithm may need to be run multiple |
| 54 | // iterations before emitting optimal code. One source of this need is that we |
| 55 | // only split an operand when it is used only once. The above algorithm can |
| 56 | // eliminate an instruction and decrease the usage count of its operands. As a |
| 57 | // result, an instruction that previously had multiple uses may become a |
| 58 | // single-use instruction and thus eligible for split consideration. For |
| 59 | // example, |
| 60 | // |
| 61 | // ac = a + c |
| 62 | // ab = a + b |
| 63 | // abc = ab + c |
| 64 | // ab2 = ab + b |
| 65 | // ab2c = ab2 + c |
| 66 | // |
| 67 | // In the first iteration, we cannot reassociate abc to ac+b because ab is used |
| 68 | // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a |
| 69 | // result, ab2 becomes dead and ab will be used only once in the second |
| 70 | // iteration. |
| 71 | // |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 72 | // Limitations and TODO items: |
| 73 | // |
| 74 | // 1) We only considers n-ary adds for now. This should be extended and |
| 75 | // generalized. |
| 76 | // |
| 77 | // 2) Besides arithmetic operations, similar reassociation can be applied to |
| 78 | // GEPs. For example, if |
| 79 | // X = &arr[a] |
| 80 | // dominates |
| 81 | // Y = &arr[a + b] |
| 82 | // we may rewrite Y into X + b. |
| 83 | // |
| 84 | //===----------------------------------------------------------------------===// |
| 85 | |
| 86 | #include "llvm/Analysis/ScalarEvolution.h" |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 87 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 88 | #include "llvm/Analysis/TargetTransformInfo.h" |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 89 | #include "llvm/IR/Dominators.h" |
| 90 | #include "llvm/IR/Module.h" |
| 91 | #include "llvm/IR/PatternMatch.h" |
| 92 | #include "llvm/Transforms/Scalar.h" |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 93 | #include "llvm/Transforms/Utils/Local.h" |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 94 | using namespace llvm; |
| 95 | using namespace PatternMatch; |
| 96 | |
| 97 | #define DEBUG_TYPE "nary-reassociate" |
| 98 | |
| 99 | namespace { |
| 100 | class NaryReassociate : public FunctionPass { |
| 101 | public: |
| 102 | static char ID; |
| 103 | |
| 104 | NaryReassociate(): FunctionPass(ID) { |
| 105 | initializeNaryReassociatePass(*PassRegistry::getPassRegistry()); |
| 106 | } |
| 107 | |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 108 | bool doInitialization(Module &M) override { |
| 109 | DL = &M.getDataLayout(); |
| 110 | return false; |
| 111 | } |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 112 | bool runOnFunction(Function &F) override; |
| 113 | |
| 114 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 115 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 116 | AU.addPreserved<ScalarEvolution>(); |
| 117 | AU.addPreserved<TargetLibraryInfoWrapperPass>(); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 118 | AU.addRequired<DominatorTreeWrapperPass>(); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 119 | AU.addRequired<ScalarEvolution>(); |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 120 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 121 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 122 | AU.setPreservesCFG(); |
| 123 | } |
| 124 | |
| 125 | private: |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 126 | // Runs only one iteration of the dominator-based algorithm. See the header |
| 127 | // comments for why we need multiple iterations. |
| 128 | bool doOneIteration(Function &F); |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 129 | |
| 130 | // Reassociates I for better CSE. |
| 131 | Instruction *tryReassociate(Instruction *I); |
| 132 | |
| 133 | // Reassociate GEP for better CSE. |
| 134 | Instruction *tryReassociateGEP(GetElementPtrInst *GEP); |
| 135 | // Try splitting GEP at the I-th index and see whether either part can be |
| 136 | // CSE'ed. This is a helper function for tryReassociateGEP. |
| 137 | // |
| 138 | // \p IndexedType The element type indexed by GEP's I-th index. This is |
| 139 | // equivalent to |
| 140 | // GEP->getIndexedType(GEP->getPointerOperand(), 0-th index, |
| 141 | // ..., i-th index). |
| 142 | GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP, |
| 143 | unsigned I, Type *IndexedType); |
| 144 | // Given GEP's I-th index = LHS + RHS, see whether &Base[..][LHS][..] or |
| 145 | // &Base[..][RHS][..] can be CSE'ed and rewrite GEP accordingly. |
| 146 | GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP, |
| 147 | unsigned I, Value *LHS, |
| 148 | Value *RHS, Type *IndexedType); |
| 149 | |
| 150 | // Reassociate Add for better CSE. |
| 151 | Instruction *tryReassociateAdd(BinaryOperator *I); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 152 | // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed. |
| 153 | Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I); |
| 154 | // Rewrites I to LHS + RHS if LHS is computed already. |
| 155 | Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I); |
| 156 | |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 157 | // Returns the closest dominator of \c Dominatee that computes |
| 158 | // \c CandidateExpr. Returns null if not found. |
| 159 | Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr, |
| 160 | Instruction *Dominatee); |
| 161 | // GetElementPtrInst implicitly sign-extends an index if the index is shorter |
| 162 | // than the pointer size. This function returns whether Index is shorter than |
| 163 | // GEP's pointer size, i.e., whether Index needs to be sign-extended in order |
| 164 | // to be an index of GEP. |
| 165 | bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP); |
| 166 | |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 167 | DominatorTree *DT; |
| 168 | ScalarEvolution *SE; |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 169 | TargetLibraryInfo *TLI; |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 170 | TargetTransformInfo *TTI; |
| 171 | const DataLayout *DL; |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 172 | // A lookup table quickly telling which instructions compute the given SCEV. |
| 173 | // Note that there can be multiple instructions at different locations |
Jingyue Wu | 771dfe9 | 2015-04-16 18:42:31 +0000 | [diff] [blame] | 174 | // computing to the same SCEV, so we map a SCEV to an instruction list. For |
| 175 | // example, |
| 176 | // |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 177 | // if (p1) |
| 178 | // foo(a + b); |
| 179 | // if (p2) |
| 180 | // bar(a + b); |
| 181 | DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs; |
| 182 | }; |
| 183 | } // anonymous namespace |
| 184 | |
| 185 | char NaryReassociate::ID = 0; |
| 186 | INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation", |
| 187 | false, false) |
| 188 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 189 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 190 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 191 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 192 | INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation", |
| 193 | false, false) |
| 194 | |
| 195 | FunctionPass *llvm::createNaryReassociatePass() { |
| 196 | return new NaryReassociate(); |
| 197 | } |
| 198 | |
| 199 | bool NaryReassociate::runOnFunction(Function &F) { |
| 200 | if (skipOptnoneFunction(F)) |
| 201 | return false; |
| 202 | |
| 203 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 204 | SE = &getAnalysis<ScalarEvolution>(); |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 205 | TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 206 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 207 | |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 208 | bool Changed = false, ChangedInThisIteration; |
| 209 | do { |
| 210 | ChangedInThisIteration = doOneIteration(F); |
| 211 | Changed |= ChangedInThisIteration; |
| 212 | } while (ChangedInThisIteration); |
| 213 | return Changed; |
| 214 | } |
| 215 | |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 216 | // Whitelist the instruction types NaryReassociate handles for now. |
| 217 | static bool isPotentiallyNaryReassociable(Instruction *I) { |
| 218 | switch (I->getOpcode()) { |
| 219 | case Instruction::Add: |
| 220 | case Instruction::GetElementPtr: |
| 221 | return true; |
| 222 | default: |
| 223 | return false; |
| 224 | } |
| 225 | } |
| 226 | |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 227 | bool NaryReassociate::doOneIteration(Function &F) { |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 228 | bool Changed = false; |
| 229 | SeenExprs.clear(); |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 230 | // Process the basic blocks in pre-order of the dominator tree. This order |
| 231 | // ensures that all bases of a candidate are in Candidates when we process it. |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 232 | for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT); |
| 233 | Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) { |
| 234 | BasicBlock *BB = Node->getBlock(); |
| 235 | for (auto I = BB->begin(); I != BB->end(); ++I) { |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 236 | if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(I)) { |
| 237 | if (Instruction *NewI = tryReassociate(I)) { |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 238 | Changed = true; |
| 239 | SE->forgetValue(I); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 240 | I->replaceAllUsesWith(NewI); |
Jingyue Wu | 8579b81 | 2015-04-17 00:25:10 +0000 | [diff] [blame] | 241 | RecursivelyDeleteTriviallyDeadInstructions(I, TLI); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 242 | I = NewI; |
| 243 | } |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 244 | // Add the rewritten instruction to SeenExprs; the original instruction |
| 245 | // is deleted. |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 246 | SeenExprs[SE->getSCEV(I)].push_back(I); |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | return Changed; |
| 251 | } |
| 252 | |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 253 | Instruction *NaryReassociate::tryReassociate(Instruction *I) { |
| 254 | switch (I->getOpcode()) { |
| 255 | case Instruction::Add: |
| 256 | return tryReassociateAdd(cast<BinaryOperator>(I)); |
| 257 | case Instruction::GetElementPtr: |
| 258 | return tryReassociateGEP(cast<GetElementPtrInst>(I)); |
| 259 | default: |
| 260 | llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable"); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // FIXME: extract this method into TTI->getGEPCost. |
| 265 | static bool isGEPFoldable(GetElementPtrInst *GEP, |
| 266 | const TargetTransformInfo *TTI, |
| 267 | const DataLayout *DL) { |
| 268 | GlobalVariable *BaseGV = nullptr; |
| 269 | int64_t BaseOffset = 0; |
| 270 | bool HasBaseReg = false; |
| 271 | int64_t Scale = 0; |
| 272 | |
| 273 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand())) |
| 274 | BaseGV = GV; |
| 275 | else |
| 276 | HasBaseReg = true; |
| 277 | |
| 278 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 279 | for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) { |
| 280 | if (isa<SequentialType>(*GTI)) { |
| 281 | int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); |
| 282 | if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) { |
| 283 | BaseOffset += ConstIdx->getSExtValue() * ElementSize; |
| 284 | } else { |
| 285 | // Needs scale register. |
| 286 | if (Scale != 0) { |
| 287 | // No addressing mode takes two scale registers. |
| 288 | return false; |
| 289 | } |
| 290 | Scale = ElementSize; |
| 291 | } |
| 292 | } else { |
| 293 | StructType *STy = cast<StructType>(*GTI); |
| 294 | uint64_t Field = cast<ConstantInt>(*I)->getZExtValue(); |
| 295 | BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field); |
| 296 | } |
| 297 | } |
| 298 | return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV, |
| 299 | BaseOffset, HasBaseReg, Scale); |
| 300 | } |
| 301 | |
| 302 | Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) { |
| 303 | // Not worth reassociating GEP if it is foldable. |
| 304 | if (isGEPFoldable(GEP, TTI, DL)) |
| 305 | return nullptr; |
| 306 | |
| 307 | gep_type_iterator GTI = gep_type_begin(*GEP); |
| 308 | for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) { |
| 309 | if (isa<SequentialType>(*GTI++)) { |
| 310 | if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) { |
| 311 | return NewGEP; |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | return nullptr; |
| 316 | } |
| 317 | |
| 318 | bool NaryReassociate::requiresSignExtension(Value *Index, |
| 319 | GetElementPtrInst *GEP) { |
| 320 | unsigned PointerSizeInBits = |
| 321 | DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace()); |
| 322 | return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits; |
| 323 | } |
| 324 | |
| 325 | GetElementPtrInst * |
| 326 | NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I, |
| 327 | Type *IndexedType) { |
| 328 | Value *IndexToSplit = GEP->getOperand(I + 1); |
| 329 | if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) |
| 330 | IndexToSplit = SExt->getOperand(0); |
| 331 | |
| 332 | if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) { |
| 333 | // If the I-th index needs sext and the underlying add is not equipped with |
| 334 | // nsw, we cannot split the add because |
| 335 | // sext(LHS + RHS) != sext(LHS) + sext(RHS). |
| 336 | if (requiresSignExtension(IndexToSplit, GEP) && !AO->hasNoSignedWrap()) |
| 337 | return nullptr; |
| 338 | Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1); |
| 339 | // IndexToSplit = LHS + RHS. |
| 340 | if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType)) |
| 341 | return NewGEP; |
| 342 | // Symmetrically, try IndexToSplit = RHS + LHS. |
| 343 | if (LHS != RHS) { |
| 344 | if (auto *NewGEP = |
| 345 | tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType)) |
| 346 | return NewGEP; |
| 347 | } |
| 348 | } |
| 349 | return nullptr; |
| 350 | } |
| 351 | |
| 352 | GetElementPtrInst * |
| 353 | NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I, |
| 354 | Value *LHS, Value *RHS, |
| 355 | Type *IndexedType) { |
| 356 | // Look for GEP's closest dominator that has the same SCEV as GEP except that |
| 357 | // the I-th index is replaced with LHS. |
| 358 | SmallVector<const SCEV *, 4> IndexExprs; |
| 359 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 360 | IndexExprs.push_back(SE->getSCEV(*Index)); |
| 361 | // Replace the I-th index with LHS. |
| 362 | IndexExprs[I] = SE->getSCEV(LHS); |
| 363 | const SCEV *CandidateExpr = SE->getGEPExpr( |
| 364 | GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()), |
| 365 | IndexExprs, GEP->isInBounds()); |
| 366 | |
| 367 | auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP); |
| 368 | if (Candidate == nullptr) |
| 369 | return nullptr; |
| 370 | |
| 371 | PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType()); |
| 372 | // Pretty rare but theoretically possible when a numeric value happens to |
| 373 | // share CandidateExpr. |
| 374 | if (TypeOfCandidate == nullptr) |
| 375 | return nullptr; |
| 376 | |
| 377 | // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType) |
| 378 | uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType); |
| 379 | Type *ElementType = TypeOfCandidate->getElementType(); |
| 380 | uint64_t ElementSize = DL->getTypeAllocSize(ElementType); |
| 381 | // Another less rare case: because I is not necessarily the last index of the |
| 382 | // GEP, the size of the type at the I-th index (IndexedSize) is not |
| 383 | // necessarily divisible by ElementSize. For example, |
| 384 | // |
| 385 | // #pragma pack(1) |
| 386 | // struct S { |
| 387 | // int a[3]; |
| 388 | // int64 b[8]; |
| 389 | // }; |
| 390 | // #pragma pack() |
| 391 | // |
| 392 | // sizeof(S) = 100 is indivisible by sizeof(int64) = 8. |
| 393 | // |
| 394 | // TODO: bail out on this case for now. We could emit uglygep. |
| 395 | if (IndexedSize % ElementSize != 0) |
| 396 | return nullptr; |
| 397 | |
| 398 | // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0]))); |
| 399 | IRBuilder<> Builder(GEP); |
| 400 | Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate); |
| 401 | if (RHS->getType() != IntPtrTy) |
| 402 | RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy); |
| 403 | if (IndexedSize != ElementSize) { |
| 404 | RHS = Builder.CreateMul( |
| 405 | RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize)); |
| 406 | } |
| 407 | GetElementPtrInst *NewGEP = |
| 408 | cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS)); |
| 409 | NewGEP->setIsInBounds(GEP->isInBounds()); |
| 410 | NewGEP->takeName(GEP); |
| 411 | return NewGEP; |
| 412 | } |
| 413 | |
| 414 | Instruction *NaryReassociate::tryReassociateAdd(BinaryOperator *I) { |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 415 | Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); |
| 416 | if (auto *NewI = tryReassociateAdd(LHS, RHS, I)) |
| 417 | return NewI; |
| 418 | if (auto *NewI = tryReassociateAdd(RHS, LHS, I)) |
| 419 | return NewI; |
| 420 | return nullptr; |
| 421 | } |
| 422 | |
| 423 | Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS, |
| 424 | Instruction *I) { |
| 425 | Value *A = nullptr, *B = nullptr; |
| 426 | // To be conservative, we reassociate I only when it is the only user of A+B. |
| 427 | if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) { |
| 428 | // I = (A + B) + RHS |
| 429 | // = (A + RHS) + B or (B + RHS) + A |
| 430 | const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B); |
| 431 | const SCEV *RHSExpr = SE->getSCEV(RHS); |
Jingyue Wu | c74e33b | 2015-05-13 18:12:24 +0000 | [diff] [blame] | 432 | if (BExpr != RHSExpr) { |
| 433 | if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I)) |
| 434 | return NewI; |
| 435 | } |
| 436 | if (AExpr != RHSExpr) { |
| 437 | if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I)) |
| 438 | return NewI; |
| 439 | } |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 440 | } |
| 441 | return nullptr; |
| 442 | } |
| 443 | |
| 444 | Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr, |
| 445 | Value *RHS, Instruction *I) { |
| 446 | auto Pos = SeenExprs.find(LHSExpr); |
| 447 | // Bail out if LHSExpr is not previously seen. |
| 448 | if (Pos == SeenExprs.end()) |
| 449 | return nullptr; |
| 450 | |
Jingyue Wu | 771dfe9 | 2015-04-16 18:42:31 +0000 | [diff] [blame] | 451 | // Look for the closest dominator LHS of I that computes LHSExpr, and replace |
| 452 | // I with LHS + RHS. |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 453 | auto *LHS = findClosestMatchingDominator(LHSExpr, I); |
| 454 | if (LHS == nullptr) |
| 455 | return nullptr; |
| 456 | |
| 457 | Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I); |
| 458 | NewI->takeName(I); |
| 459 | return NewI; |
| 460 | } |
| 461 | |
| 462 | Instruction * |
| 463 | NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr, |
| 464 | Instruction *Dominatee) { |
| 465 | auto Pos = SeenExprs.find(CandidateExpr); |
| 466 | if (Pos == SeenExprs.end()) |
| 467 | return nullptr; |
| 468 | |
| 469 | auto &Candidates = Pos->second; |
| 470 | // Because we process the basic blocks in pre-order of the dominator tree, a |
Jingyue Wu | 771dfe9 | 2015-04-16 18:42:31 +0000 | [diff] [blame] | 471 | // candidate that doesn't dominate the current instruction won't dominate any |
| 472 | // future instruction either. Therefore, we pop it out of the stack. This |
| 473 | // optimization makes the algorithm O(n). |
Jingyue Wu | 4fc97f6d | 2015-05-21 23:17:30 +0000 | [diff] [blame^] | 474 | while (!Candidates.empty()) { |
| 475 | Instruction *Candidate = Candidates.back(); |
| 476 | if (DT->dominates(Candidate, Dominatee)) |
| 477 | return Candidate; |
| 478 | Candidates.pop_back(); |
Jingyue Wu | 8cb6b2a | 2015-04-14 04:59:22 +0000 | [diff] [blame] | 479 | } |
| 480 | return nullptr; |
| 481 | } |