1 //===- StraightLineStrengthReduce.cpp - -----------------------------------===// 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 implements straight-line strength reduction (SLSR). Unlike loop 10 // strength reduction, this algorithm is designed to reduce arithmetic 11 // redundancy in straight-line code instead of loops. It has proven to be 12 // effective in simplifying arithmetic statements derived from an unrolled loop. 13 // It can also simplify the logic of SeparateConstOffsetFromGEP. 14 // 15 // There are many optimizations we can perform in the domain of SLSR. This file 16 // for now contains only an initial step. Specifically, we look for strength 17 // reduction candidates in the following forms: 18 // 19 // Form 1: B + i * S 20 // Form 2: (B + i) * S 21 // Form 3: &B[i * S] 22 // 23 // where S is an integer variable, and i is a constant integer. If we found two 24 // candidates S1 and S2 in the same form and S1 dominates S2, we may rewrite S2 25 // in a simpler way with respect to S1. For example, 26 // 27 // S1: X = B + i * S 28 // S2: Y = B + i' * S => X + (i' - i) * S 29 // 30 // S1: X = (B + i) * S 31 // S2: Y = (B + i') * S => X + (i' - i) * S 32 // 33 // S1: X = &B[i * S] 34 // S2: Y = &B[i' * S] => &X[(i' - i) * S] 35 // 36 // Note: (i' - i) * S is folded to the extent possible. 37 // 38 // This rewriting is in general a good idea. The code patterns we focus on 39 // usually come from loop unrolling, so (i' - i) * S is likely the same 40 // across iterations and can be reused. When that happens, the optimized form 41 // takes only one add starting from the second iteration. 42 // 43 // When such rewriting is possible, we call S1 a "basis" of S2. When S2 has 44 // multiple bases, we choose to rewrite S2 with respect to its "immediate" 45 // basis, the basis that is the closest ancestor in the dominator tree. 46 // 47 // TODO: 48 // 49 // - Floating point arithmetics when fast math is enabled. 50 // 51 // - SLSR may decrease ILP at the architecture level. Targets that are very 52 // sensitive to ILP may want to disable it. Having SLSR to consider ILP is 53 // left as future work. 54 // 55 // - When (i' - i) is constant but i and i' are not, we could still perform 56 // SLSR. 57 58 #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h" 59 #include "llvm/ADT/APInt.h" 60 #include "llvm/ADT/DepthFirstIterator.h" 61 #include "llvm/ADT/SmallVector.h" 62 #include "llvm/Analysis/ScalarEvolution.h" 63 #include "llvm/Analysis/TargetTransformInfo.h" 64 #include "llvm/Analysis/ValueTracking.h" 65 #include "llvm/IR/Constants.h" 66 #include "llvm/IR/DataLayout.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Dominators.h" 69 #include "llvm/IR/GetElementPtrTypeIterator.h" 70 #include "llvm/IR/IRBuilder.h" 71 #include "llvm/IR/InstrTypes.h" 72 #include "llvm/IR/Instruction.h" 73 #include "llvm/IR/Instructions.h" 74 #include "llvm/IR/Module.h" 75 #include "llvm/IR/Operator.h" 76 #include "llvm/IR/PatternMatch.h" 77 #include "llvm/IR/Type.h" 78 #include "llvm/IR/Value.h" 79 #include "llvm/InitializePasses.h" 80 #include "llvm/Pass.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Transforms/Scalar.h" 84 #include "llvm/Transforms/Utils/Local.h" 85 #include <cassert> 86 #include <cstdint> 87 #include <limits> 88 #include <list> 89 #include <vector> 90 91 using namespace llvm; 92 using namespace PatternMatch; 93 94 static const unsigned UnknownAddressSpace = 95 std::numeric_limits<unsigned>::max(); 96 97 namespace { 98 99 class StraightLineStrengthReduceLegacyPass : public FunctionPass { 100 const DataLayout *DL = nullptr; 101 102 public: 103 static char ID; 104 105 StraightLineStrengthReduceLegacyPass() : FunctionPass(ID) { 106 initializeStraightLineStrengthReduceLegacyPassPass( 107 *PassRegistry::getPassRegistry()); 108 } 109 110 void getAnalysisUsage(AnalysisUsage &AU) const override { 111 AU.addRequired<DominatorTreeWrapperPass>(); 112 AU.addRequired<ScalarEvolutionWrapperPass>(); 113 AU.addRequired<TargetTransformInfoWrapperPass>(); 114 // We do not modify the shape of the CFG. 115 AU.setPreservesCFG(); 116 } 117 118 bool doInitialization(Module &M) override { 119 DL = &M.getDataLayout(); 120 return false; 121 } 122 123 bool runOnFunction(Function &F) override; 124 }; 125 126 class StraightLineStrengthReduce { 127 public: 128 StraightLineStrengthReduce(const DataLayout *DL, DominatorTree *DT, 129 ScalarEvolution *SE, TargetTransformInfo *TTI) 130 : DL(DL), DT(DT), SE(SE), TTI(TTI) {} 131 132 // SLSR candidate. Such a candidate must be in one of the forms described in 133 // the header comments. 134 struct Candidate { 135 enum Kind { 136 Invalid, // reserved for the default constructor 137 Add, // B + i * S 138 Mul, // (B + i) * S 139 GEP, // &B[..][i * S][..] 140 }; 141 142 Candidate() = default; 143 Candidate(Kind CT, const SCEV *B, ConstantInt *Idx, Value *S, 144 Instruction *I) 145 : CandidateKind(CT), Base(B), Index(Idx), Stride(S), Ins(I) {} 146 147 Kind CandidateKind = Invalid; 148 149 const SCEV *Base = nullptr; 150 151 // Note that Index and Stride of a GEP candidate do not necessarily have the 152 // same integer type. In that case, during rewriting, Stride will be 153 // sign-extended or truncated to Index's type. 154 ConstantInt *Index = nullptr; 155 156 Value *Stride = nullptr; 157 158 // The instruction this candidate corresponds to. It helps us to rewrite a 159 // candidate with respect to its immediate basis. Note that one instruction 160 // can correspond to multiple candidates depending on how you associate the 161 // expression. For instance, 162 // 163 // (a + 1) * (b + 2) 164 // 165 // can be treated as 166 // 167 // <Base: a, Index: 1, Stride: b + 2> 168 // 169 // or 170 // 171 // <Base: b, Index: 2, Stride: a + 1> 172 Instruction *Ins = nullptr; 173 174 // Points to the immediate basis of this candidate, or nullptr if we cannot 175 // find any basis for this candidate. 176 Candidate *Basis = nullptr; 177 }; 178 179 bool runOnFunction(Function &F); 180 181 private: 182 // Returns true if Basis is a basis for C, i.e., Basis dominates C and they 183 // share the same base and stride. 184 bool isBasisFor(const Candidate &Basis, const Candidate &C); 185 186 // Returns whether the candidate can be folded into an addressing mode. 187 bool isFoldable(const Candidate &C, TargetTransformInfo *TTI, 188 const DataLayout *DL); 189 190 // Returns true if C is already in a simplest form and not worth being 191 // rewritten. 192 bool isSimplestForm(const Candidate &C); 193 194 // Checks whether I is in a candidate form. If so, adds all the matching forms 195 // to Candidates, and tries to find the immediate basis for each of them. 196 void allocateCandidatesAndFindBasis(Instruction *I); 197 198 // Allocate candidates and find bases for Add instructions. 199 void allocateCandidatesAndFindBasisForAdd(Instruction *I); 200 201 // Given I = LHS + RHS, factors RHS into i * S and makes (LHS + i * S) a 202 // candidate. 203 void allocateCandidatesAndFindBasisForAdd(Value *LHS, Value *RHS, 204 Instruction *I); 205 // Allocate candidates and find bases for Mul instructions. 206 void allocateCandidatesAndFindBasisForMul(Instruction *I); 207 208 // Splits LHS into Base + Index and, if succeeds, calls 209 // allocateCandidatesAndFindBasis. 210 void allocateCandidatesAndFindBasisForMul(Value *LHS, Value *RHS, 211 Instruction *I); 212 213 // Allocate candidates and find bases for GetElementPtr instructions. 214 void allocateCandidatesAndFindBasisForGEP(GetElementPtrInst *GEP); 215 216 // A helper function that scales Idx with ElementSize before invoking 217 // allocateCandidatesAndFindBasis. 218 void allocateCandidatesAndFindBasisForGEP(const SCEV *B, ConstantInt *Idx, 219 Value *S, uint64_t ElementSize, 220 Instruction *I); 221 222 // Adds the given form <CT, B, Idx, S> to Candidates, and finds its immediate 223 // basis. 224 void allocateCandidatesAndFindBasis(Candidate::Kind CT, const SCEV *B, 225 ConstantInt *Idx, Value *S, 226 Instruction *I); 227 228 // Rewrites candidate C with respect to Basis. 229 void rewriteCandidateWithBasis(const Candidate &C, const Candidate &Basis); 230 231 // A helper function that factors ArrayIdx to a product of a stride and a 232 // constant index, and invokes allocateCandidatesAndFindBasis with the 233 // factorings. 234 void factorArrayIndex(Value *ArrayIdx, const SCEV *Base, uint64_t ElementSize, 235 GetElementPtrInst *GEP); 236 237 // Emit code that computes the "bump" from Basis to C. If the candidate is a 238 // GEP and the bump is not divisible by the element size of the GEP, this 239 // function sets the BumpWithUglyGEP flag to notify its caller to bump the 240 // basis using an ugly GEP. 241 static Value *emitBump(const Candidate &Basis, const Candidate &C, 242 IRBuilder<> &Builder, const DataLayout *DL, 243 bool &BumpWithUglyGEP); 244 245 const DataLayout *DL = nullptr; 246 DominatorTree *DT = nullptr; 247 ScalarEvolution *SE; 248 TargetTransformInfo *TTI = nullptr; 249 std::list<Candidate> Candidates; 250 251 // Temporarily holds all instructions that are unlinked (but not deleted) by 252 // rewriteCandidateWithBasis. These instructions will be actually removed 253 // after all rewriting finishes. 254 std::vector<Instruction *> UnlinkedInstructions; 255 }; 256 257 } // end anonymous namespace 258 259 char StraightLineStrengthReduceLegacyPass::ID = 0; 260 261 INITIALIZE_PASS_BEGIN(StraightLineStrengthReduceLegacyPass, "slsr", 262 "Straight line strength reduction", false, false) 263 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 264 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 265 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 266 INITIALIZE_PASS_END(StraightLineStrengthReduceLegacyPass, "slsr", 267 "Straight line strength reduction", false, false) 268 269 FunctionPass *llvm::createStraightLineStrengthReducePass() { 270 return new StraightLineStrengthReduceLegacyPass(); 271 } 272 273 bool StraightLineStrengthReduce::isBasisFor(const Candidate &Basis, 274 const Candidate &C) { 275 return (Basis.Ins != C.Ins && // skip the same instruction 276 // They must have the same type too. Basis.Base == C.Base doesn't 277 // guarantee their types are the same (PR23975). 278 Basis.Ins->getType() == C.Ins->getType() && 279 // Basis must dominate C in order to rewrite C with respect to Basis. 280 DT->dominates(Basis.Ins->getParent(), C.Ins->getParent()) && 281 // They share the same base, stride, and candidate kind. 282 Basis.Base == C.Base && Basis.Stride == C.Stride && 283 Basis.CandidateKind == C.CandidateKind); 284 } 285 286 static bool isGEPFoldable(GetElementPtrInst *GEP, 287 const TargetTransformInfo *TTI) { 288 SmallVector<const Value*, 4> Indices; 289 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) 290 Indices.push_back(*I); 291 return TTI->getGEPCost(GEP->getSourceElementType(), GEP->getPointerOperand(), 292 Indices) == TargetTransformInfo::TCC_Free; 293 } 294 295 // Returns whether (Base + Index * Stride) can be folded to an addressing mode. 296 static bool isAddFoldable(const SCEV *Base, ConstantInt *Index, Value *Stride, 297 TargetTransformInfo *TTI) { 298 // Index->getSExtValue() may crash if Index is wider than 64-bit. 299 return Index->getBitWidth() <= 64 && 300 TTI->isLegalAddressingMode(Base->getType(), nullptr, 0, true, 301 Index->getSExtValue(), UnknownAddressSpace); 302 } 303 304 bool StraightLineStrengthReduce::isFoldable(const Candidate &C, 305 TargetTransformInfo *TTI, 306 const DataLayout *DL) { 307 if (C.CandidateKind == Candidate::Add) 308 return isAddFoldable(C.Base, C.Index, C.Stride, TTI); 309 if (C.CandidateKind == Candidate::GEP) 310 return isGEPFoldable(cast<GetElementPtrInst>(C.Ins), TTI); 311 return false; 312 } 313 314 // Returns true if GEP has zero or one non-zero index. 315 static bool hasOnlyOneNonZeroIndex(GetElementPtrInst *GEP) { 316 unsigned NumNonZeroIndices = 0; 317 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) { 318 ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I); 319 if (ConstIdx == nullptr || !ConstIdx->isZero()) 320 ++NumNonZeroIndices; 321 } 322 return NumNonZeroIndices <= 1; 323 } 324 325 bool StraightLineStrengthReduce::isSimplestForm(const Candidate &C) { 326 if (C.CandidateKind == Candidate::Add) { 327 // B + 1 * S or B + (-1) * S 328 return C.Index->isOne() || C.Index->isMinusOne(); 329 } 330 if (C.CandidateKind == Candidate::Mul) { 331 // (B + 0) * S 332 return C.Index->isZero(); 333 } 334 if (C.CandidateKind == Candidate::GEP) { 335 // (char*)B + S or (char*)B - S 336 return ((C.Index->isOne() || C.Index->isMinusOne()) && 337 hasOnlyOneNonZeroIndex(cast<GetElementPtrInst>(C.Ins))); 338 } 339 return false; 340 } 341 342 // TODO: We currently implement an algorithm whose time complexity is linear in 343 // the number of existing candidates. However, we could do better by using 344 // ScopedHashTable. Specifically, while traversing the dominator tree, we could 345 // maintain all the candidates that dominate the basic block being traversed in 346 // a ScopedHashTable. This hash table is indexed by the base and the stride of 347 // a candidate. Therefore, finding the immediate basis of a candidate boils down 348 // to one hash-table look up. 349 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis( 350 Candidate::Kind CT, const SCEV *B, ConstantInt *Idx, Value *S, 351 Instruction *I) { 352 Candidate C(CT, B, Idx, S, I); 353 // SLSR can complicate an instruction in two cases: 354 // 355 // 1. If we can fold I into an addressing mode, computing I is likely free or 356 // takes only one instruction. 357 // 358 // 2. I is already in a simplest form. For example, when 359 // X = B + 8 * S 360 // Y = B + S, 361 // rewriting Y to X - 7 * S is probably a bad idea. 362 // 363 // In the above cases, we still add I to the candidate list so that I can be 364 // the basis of other candidates, but we leave I's basis blank so that I 365 // won't be rewritten. 366 if (!isFoldable(C, TTI, DL) && !isSimplestForm(C)) { 367 // Try to compute the immediate basis of C. 368 unsigned NumIterations = 0; 369 // Limit the scan radius to avoid running in quadratice time. 370 static const unsigned MaxNumIterations = 50; 371 for (auto Basis = Candidates.rbegin(); 372 Basis != Candidates.rend() && NumIterations < MaxNumIterations; 373 ++Basis, ++NumIterations) { 374 if (isBasisFor(*Basis, C)) { 375 C.Basis = &(*Basis); 376 break; 377 } 378 } 379 } 380 // Regardless of whether we find a basis for C, we need to push C to the 381 // candidate list so that it can be the basis of other candidates. 382 Candidates.push_back(C); 383 } 384 385 void StraightLineStrengthReduce::allocateCandidatesAndFindBasis( 386 Instruction *I) { 387 switch (I->getOpcode()) { 388 case Instruction::Add: 389 allocateCandidatesAndFindBasisForAdd(I); 390 break; 391 case Instruction::Mul: 392 allocateCandidatesAndFindBasisForMul(I); 393 break; 394 case Instruction::GetElementPtr: 395 allocateCandidatesAndFindBasisForGEP(cast<GetElementPtrInst>(I)); 396 break; 397 } 398 } 399 400 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd( 401 Instruction *I) { 402 // Try matching B + i * S. 403 if (!isa<IntegerType>(I->getType())) 404 return; 405 406 assert(I->getNumOperands() == 2 && "isn't I an add?"); 407 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); 408 allocateCandidatesAndFindBasisForAdd(LHS, RHS, I); 409 if (LHS != RHS) 410 allocateCandidatesAndFindBasisForAdd(RHS, LHS, I); 411 } 412 413 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForAdd( 414 Value *LHS, Value *RHS, Instruction *I) { 415 Value *S = nullptr; 416 ConstantInt *Idx = nullptr; 417 if (match(RHS, m_Mul(m_Value(S), m_ConstantInt(Idx)))) { 418 // I = LHS + RHS = LHS + Idx * S 419 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I); 420 } else if (match(RHS, m_Shl(m_Value(S), m_ConstantInt(Idx)))) { 421 // I = LHS + RHS = LHS + (S << Idx) = LHS + S * (1 << Idx) 422 APInt One(Idx->getBitWidth(), 1); 423 Idx = ConstantInt::get(Idx->getContext(), One << Idx->getValue()); 424 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), Idx, S, I); 425 } else { 426 // At least, I = LHS + 1 * RHS 427 ConstantInt *One = ConstantInt::get(cast<IntegerType>(I->getType()), 1); 428 allocateCandidatesAndFindBasis(Candidate::Add, SE->getSCEV(LHS), One, RHS, 429 I); 430 } 431 } 432 433 // Returns true if A matches B + C where C is constant. 434 static bool matchesAdd(Value *A, Value *&B, ConstantInt *&C) { 435 return (match(A, m_Add(m_Value(B), m_ConstantInt(C))) || 436 match(A, m_Add(m_ConstantInt(C), m_Value(B)))); 437 } 438 439 // Returns true if A matches B | C where C is constant. 440 static bool matchesOr(Value *A, Value *&B, ConstantInt *&C) { 441 return (match(A, m_Or(m_Value(B), m_ConstantInt(C))) || 442 match(A, m_Or(m_ConstantInt(C), m_Value(B)))); 443 } 444 445 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul( 446 Value *LHS, Value *RHS, Instruction *I) { 447 Value *B = nullptr; 448 ConstantInt *Idx = nullptr; 449 if (matchesAdd(LHS, B, Idx)) { 450 // If LHS is in the form of "Base + Index", then I is in the form of 451 // "(Base + Index) * RHS". 452 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I); 453 } else if (matchesOr(LHS, B, Idx) && haveNoCommonBitsSet(B, Idx, *DL)) { 454 // If LHS is in the form of "Base | Index" and Base and Index have no common 455 // bits set, then 456 // Base | Index = Base + Index 457 // and I is thus in the form of "(Base + Index) * RHS". 458 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(B), Idx, RHS, I); 459 } else { 460 // Otherwise, at least try the form (LHS + 0) * RHS. 461 ConstantInt *Zero = ConstantInt::get(cast<IntegerType>(I->getType()), 0); 462 allocateCandidatesAndFindBasis(Candidate::Mul, SE->getSCEV(LHS), Zero, RHS, 463 I); 464 } 465 } 466 467 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForMul( 468 Instruction *I) { 469 // Try matching (B + i) * S. 470 // TODO: we could extend SLSR to float and vector types. 471 if (!isa<IntegerType>(I->getType())) 472 return; 473 474 assert(I->getNumOperands() == 2 && "isn't I a mul?"); 475 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); 476 allocateCandidatesAndFindBasisForMul(LHS, RHS, I); 477 if (LHS != RHS) { 478 // Symmetrically, try to split RHS to Base + Index. 479 allocateCandidatesAndFindBasisForMul(RHS, LHS, I); 480 } 481 } 482 483 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP( 484 const SCEV *B, ConstantInt *Idx, Value *S, uint64_t ElementSize, 485 Instruction *I) { 486 // I = B + sext(Idx *nsw S) * ElementSize 487 // = B + (sext(Idx) * sext(S)) * ElementSize 488 // = B + (sext(Idx) * ElementSize) * sext(S) 489 // Casting to IntegerType is safe because we skipped vector GEPs. 490 IntegerType *IntPtrTy = cast<IntegerType>(DL->getIntPtrType(I->getType())); 491 ConstantInt *ScaledIdx = ConstantInt::get( 492 IntPtrTy, Idx->getSExtValue() * (int64_t)ElementSize, true); 493 allocateCandidatesAndFindBasis(Candidate::GEP, B, ScaledIdx, S, I); 494 } 495 496 void StraightLineStrengthReduce::factorArrayIndex(Value *ArrayIdx, 497 const SCEV *Base, 498 uint64_t ElementSize, 499 GetElementPtrInst *GEP) { 500 // At least, ArrayIdx = ArrayIdx *nsw 1. 501 allocateCandidatesAndFindBasisForGEP( 502 Base, ConstantInt::get(cast<IntegerType>(ArrayIdx->getType()), 1), 503 ArrayIdx, ElementSize, GEP); 504 Value *LHS = nullptr; 505 ConstantInt *RHS = nullptr; 506 // One alternative is matching the SCEV of ArrayIdx instead of ArrayIdx 507 // itself. This would allow us to handle the shl case for free. However, 508 // matching SCEVs has two issues: 509 // 510 // 1. this would complicate rewriting because the rewriting procedure 511 // would have to translate SCEVs back to IR instructions. This translation 512 // is difficult when LHS is further evaluated to a composite SCEV. 513 // 514 // 2. ScalarEvolution is designed to be control-flow oblivious. It tends 515 // to strip nsw/nuw flags which are critical for SLSR to trace into 516 // sext'ed multiplication. 517 if (match(ArrayIdx, m_NSWMul(m_Value(LHS), m_ConstantInt(RHS)))) { 518 // SLSR is currently unsafe if i * S may overflow. 519 // GEP = Base + sext(LHS *nsw RHS) * ElementSize 520 allocateCandidatesAndFindBasisForGEP(Base, RHS, LHS, ElementSize, GEP); 521 } else if (match(ArrayIdx, m_NSWShl(m_Value(LHS), m_ConstantInt(RHS)))) { 522 // GEP = Base + sext(LHS <<nsw RHS) * ElementSize 523 // = Base + sext(LHS *nsw (1 << RHS)) * ElementSize 524 APInt One(RHS->getBitWidth(), 1); 525 ConstantInt *PowerOf2 = 526 ConstantInt::get(RHS->getContext(), One << RHS->getValue()); 527 allocateCandidatesAndFindBasisForGEP(Base, PowerOf2, LHS, ElementSize, GEP); 528 } 529 } 530 531 void StraightLineStrengthReduce::allocateCandidatesAndFindBasisForGEP( 532 GetElementPtrInst *GEP) { 533 // TODO: handle vector GEPs 534 if (GEP->getType()->isVectorTy()) 535 return; 536 537 SmallVector<const SCEV *, 4> IndexExprs; 538 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) 539 IndexExprs.push_back(SE->getSCEV(*I)); 540 541 gep_type_iterator GTI = gep_type_begin(GEP); 542 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I, ++GTI) { 543 if (GTI.isStruct()) 544 continue; 545 546 const SCEV *OrigIndexExpr = IndexExprs[I - 1]; 547 IndexExprs[I - 1] = SE->getZero(OrigIndexExpr->getType()); 548 549 // The base of this candidate is GEP's base plus the offsets of all 550 // indices except this current one. 551 const SCEV *BaseExpr = SE->getGEPExpr(cast<GEPOperator>(GEP), IndexExprs); 552 Value *ArrayIdx = GEP->getOperand(I); 553 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 554 if (ArrayIdx->getType()->getIntegerBitWidth() <= 555 DL->getPointerSizeInBits(GEP->getAddressSpace())) { 556 // Skip factoring if ArrayIdx is wider than the pointer size, because 557 // ArrayIdx is implicitly truncated to the pointer size. 558 factorArrayIndex(ArrayIdx, BaseExpr, ElementSize, GEP); 559 } 560 // When ArrayIdx is the sext of a value, we try to factor that value as 561 // well. Handling this case is important because array indices are 562 // typically sign-extended to the pointer size. 563 Value *TruncatedArrayIdx = nullptr; 564 if (match(ArrayIdx, m_SExt(m_Value(TruncatedArrayIdx))) && 565 TruncatedArrayIdx->getType()->getIntegerBitWidth() <= 566 DL->getPointerSizeInBits(GEP->getAddressSpace())) { 567 // Skip factoring if TruncatedArrayIdx is wider than the pointer size, 568 // because TruncatedArrayIdx is implicitly truncated to the pointer size. 569 factorArrayIndex(TruncatedArrayIdx, BaseExpr, ElementSize, GEP); 570 } 571 572 IndexExprs[I - 1] = OrigIndexExpr; 573 } 574 } 575 576 // A helper function that unifies the bitwidth of A and B. 577 static void unifyBitWidth(APInt &A, APInt &B) { 578 if (A.getBitWidth() < B.getBitWidth()) 579 A = A.sext(B.getBitWidth()); 580 else if (A.getBitWidth() > B.getBitWidth()) 581 B = B.sext(A.getBitWidth()); 582 } 583 584 Value *StraightLineStrengthReduce::emitBump(const Candidate &Basis, 585 const Candidate &C, 586 IRBuilder<> &Builder, 587 const DataLayout *DL, 588 bool &BumpWithUglyGEP) { 589 APInt Idx = C.Index->getValue(), BasisIdx = Basis.Index->getValue(); 590 unifyBitWidth(Idx, BasisIdx); 591 APInt IndexOffset = Idx - BasisIdx; 592 593 BumpWithUglyGEP = false; 594 if (Basis.CandidateKind == Candidate::GEP) { 595 APInt ElementSize( 596 IndexOffset.getBitWidth(), 597 DL->getTypeAllocSize( 598 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType())); 599 APInt Q, R; 600 APInt::sdivrem(IndexOffset, ElementSize, Q, R); 601 if (R == 0) 602 IndexOffset = Q; 603 else 604 BumpWithUglyGEP = true; 605 } 606 607 // Compute Bump = C - Basis = (i' - i) * S. 608 // Common case 1: if (i' - i) is 1, Bump = S. 609 if (IndexOffset == 1) 610 return C.Stride; 611 // Common case 2: if (i' - i) is -1, Bump = -S. 612 if (IndexOffset.isAllOnesValue()) 613 return Builder.CreateNeg(C.Stride); 614 615 // Otherwise, Bump = (i' - i) * sext/trunc(S). Note that (i' - i) and S may 616 // have different bit widths. 617 IntegerType *DeltaType = 618 IntegerType::get(Basis.Ins->getContext(), IndexOffset.getBitWidth()); 619 Value *ExtendedStride = Builder.CreateSExtOrTrunc(C.Stride, DeltaType); 620 if (IndexOffset.isPowerOf2()) { 621 // If (i' - i) is a power of 2, Bump = sext/trunc(S) << log(i' - i). 622 ConstantInt *Exponent = ConstantInt::get(DeltaType, IndexOffset.logBase2()); 623 return Builder.CreateShl(ExtendedStride, Exponent); 624 } 625 if ((-IndexOffset).isPowerOf2()) { 626 // If (i - i') is a power of 2, Bump = -sext/trunc(S) << log(i' - i). 627 ConstantInt *Exponent = 628 ConstantInt::get(DeltaType, (-IndexOffset).logBase2()); 629 return Builder.CreateNeg(Builder.CreateShl(ExtendedStride, Exponent)); 630 } 631 Constant *Delta = ConstantInt::get(DeltaType, IndexOffset); 632 return Builder.CreateMul(ExtendedStride, Delta); 633 } 634 635 void StraightLineStrengthReduce::rewriteCandidateWithBasis( 636 const Candidate &C, const Candidate &Basis) { 637 assert(C.CandidateKind == Basis.CandidateKind && C.Base == Basis.Base && 638 C.Stride == Basis.Stride); 639 // We run rewriteCandidateWithBasis on all candidates in a post-order, so the 640 // basis of a candidate cannot be unlinked before the candidate. 641 assert(Basis.Ins->getParent() != nullptr && "the basis is unlinked"); 642 643 // An instruction can correspond to multiple candidates. Therefore, instead of 644 // simply deleting an instruction when we rewrite it, we mark its parent as 645 // nullptr (i.e. unlink it) so that we can skip the candidates whose 646 // instruction is already rewritten. 647 if (!C.Ins->getParent()) 648 return; 649 650 IRBuilder<> Builder(C.Ins); 651 bool BumpWithUglyGEP; 652 Value *Bump = emitBump(Basis, C, Builder, DL, BumpWithUglyGEP); 653 Value *Reduced = nullptr; // equivalent to but weaker than C.Ins 654 switch (C.CandidateKind) { 655 case Candidate::Add: 656 case Candidate::Mul: { 657 // C = Basis + Bump 658 Value *NegBump; 659 if (match(Bump, m_Neg(m_Value(NegBump)))) { 660 // If Bump is a neg instruction, emit C = Basis - (-Bump). 661 Reduced = Builder.CreateSub(Basis.Ins, NegBump); 662 // We only use the negative argument of Bump, and Bump itself may be 663 // trivially dead. 664 RecursivelyDeleteTriviallyDeadInstructions(Bump); 665 } else { 666 // It's tempting to preserve nsw on Bump and/or Reduced. However, it's 667 // usually unsound, e.g., 668 // 669 // X = (-2 +nsw 1) *nsw INT_MAX 670 // Y = (-2 +nsw 3) *nsw INT_MAX 671 // => 672 // Y = X + 2 * INT_MAX 673 // 674 // Neither + and * in the resultant expression are nsw. 675 Reduced = Builder.CreateAdd(Basis.Ins, Bump); 676 } 677 break; 678 } 679 case Candidate::GEP: 680 { 681 Type *IntPtrTy = DL->getIntPtrType(C.Ins->getType()); 682 bool InBounds = cast<GetElementPtrInst>(C.Ins)->isInBounds(); 683 if (BumpWithUglyGEP) { 684 // C = (char *)Basis + Bump 685 unsigned AS = Basis.Ins->getType()->getPointerAddressSpace(); 686 Type *CharTy = Type::getInt8PtrTy(Basis.Ins->getContext(), AS); 687 Reduced = Builder.CreateBitCast(Basis.Ins, CharTy); 688 if (InBounds) 689 Reduced = 690 Builder.CreateInBoundsGEP(Builder.getInt8Ty(), Reduced, Bump); 691 else 692 Reduced = Builder.CreateGEP(Builder.getInt8Ty(), Reduced, Bump); 693 Reduced = Builder.CreateBitCast(Reduced, C.Ins->getType()); 694 } else { 695 // C = gep Basis, Bump 696 // Canonicalize bump to pointer size. 697 Bump = Builder.CreateSExtOrTrunc(Bump, IntPtrTy); 698 if (InBounds) 699 Reduced = Builder.CreateInBoundsGEP( 700 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType(), 701 Basis.Ins, Bump); 702 else 703 Reduced = Builder.CreateGEP( 704 cast<GetElementPtrInst>(Basis.Ins)->getResultElementType(), 705 Basis.Ins, Bump); 706 } 707 break; 708 } 709 default: 710 llvm_unreachable("C.CandidateKind is invalid"); 711 }; 712 Reduced->takeName(C.Ins); 713 C.Ins->replaceAllUsesWith(Reduced); 714 // Unlink C.Ins so that we can skip other candidates also corresponding to 715 // C.Ins. The actual deletion is postponed to the end of runOnFunction. 716 C.Ins->removeFromParent(); 717 UnlinkedInstructions.push_back(C.Ins); 718 } 719 720 bool StraightLineStrengthReduceLegacyPass::runOnFunction(Function &F) { 721 if (skipFunction(F)) 722 return false; 723 724 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 725 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 726 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 727 return StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F); 728 } 729 730 bool StraightLineStrengthReduce::runOnFunction(Function &F) { 731 // Traverse the dominator tree in the depth-first order. This order makes sure 732 // all bases of a candidate are in Candidates when we process it. 733 for (const auto Node : depth_first(DT)) 734 for (auto &I : *(Node->getBlock())) 735 allocateCandidatesAndFindBasis(&I); 736 737 // Rewrite candidates in the reverse depth-first order. This order makes sure 738 // a candidate being rewritten is not a basis for any other candidate. 739 while (!Candidates.empty()) { 740 const Candidate &C = Candidates.back(); 741 if (C.Basis != nullptr) { 742 rewriteCandidateWithBasis(C, *C.Basis); 743 } 744 Candidates.pop_back(); 745 } 746 747 // Delete all unlink instructions. 748 for (auto *UnlinkedInst : UnlinkedInstructions) { 749 for (unsigned I = 0, E = UnlinkedInst->getNumOperands(); I != E; ++I) { 750 Value *Op = UnlinkedInst->getOperand(I); 751 UnlinkedInst->setOperand(I, nullptr); 752 RecursivelyDeleteTriviallyDeadInstructions(Op); 753 } 754 UnlinkedInst->deleteValue(); 755 } 756 bool Ret = !UnlinkedInstructions.empty(); 757 UnlinkedInstructions.clear(); 758 return Ret; 759 } 760 761 namespace llvm { 762 763 PreservedAnalyses 764 StraightLineStrengthReducePass::run(Function &F, FunctionAnalysisManager &AM) { 765 const DataLayout *DL = &F.getParent()->getDataLayout(); 766 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 767 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 768 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 769 770 if (!StraightLineStrengthReduce(DL, DT, SE, TTI).runOnFunction(F)) 771 return PreservedAnalyses::all(); 772 773 PreservedAnalyses PA; 774 PA.preserveSet<CFGAnalyses>(); 775 PA.preserve<DominatorTreeAnalysis>(); 776 PA.preserve<ScalarEvolutionAnalysis>(); 777 PA.preserve<TargetIRAnalysis>(); 778 return PA; 779 } 780 781 } // namespace llvm 782