1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===// 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 transformation analyzes and transforms the induction variables (and 11 // computations derived from them) into forms suitable for efficient execution 12 // on the target. 13 // 14 // This pass performs a strength reduction on array references inside loops that 15 // have as one or more of their components the loop induction variable, it 16 // rewrites expressions to take advantage of scaled-index addressing modes 17 // available on the target, and it performs a variety of other optimizations 18 // related to loop induction variables. 19 // 20 // Terminology note: this code has a lot of handling for "post-increment" or 21 // "post-inc" users. This is not talking about post-increment addressing modes; 22 // it is instead talking about code like this: 23 // 24 // %i = phi [ 0, %entry ], [ %i.next, %latch ] 25 // ... 26 // %i.next = add %i, 1 27 // %c = icmp eq %i.next, %n 28 // 29 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however 30 // it's useful to think about these as the same register, with some uses using 31 // the value of the register before the add and some using it after. In this 32 // example, the icmp is a post-increment user, since it uses %i.next, which is 33 // the value of the induction variable after the increment. The other common 34 // case of post-increment users is users outside the loop. 35 // 36 // TODO: More sophistication in the way Formulae are generated and filtered. 37 // 38 // TODO: Handle multiple loops at a time. 39 // 40 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead 41 // of a GlobalValue? 42 // 43 // TODO: When truncation is free, truncate ICmp users' operands to make it a 44 // smaller encoding (on x86 at least). 45 // 46 // TODO: When a negated register is used by an add (such as in a list of 47 // multiple base registers, or as the increment expression in an addrec), 48 // we may not actually need both reg and (-1 * reg) in registers; the 49 // negation can be implemented by using a sub instead of an add. The 50 // lack of support for taking this into consideration when making 51 // register pressure decisions is partly worked around by the "Special" 52 // use kind. 53 // 54 //===----------------------------------------------------------------------===// 55 56 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 57 #include "llvm/ADT/APInt.h" 58 #include "llvm/ADT/DenseMap.h" 59 #include "llvm/ADT/DenseSet.h" 60 #include "llvm/ADT/Hashing.h" 61 #include "llvm/ADT/PointerIntPair.h" 62 #include "llvm/ADT/STLExtras.h" 63 #include "llvm/ADT/SetVector.h" 64 #include "llvm/ADT/SmallBitVector.h" 65 #include "llvm/ADT/SmallPtrSet.h" 66 #include "llvm/ADT/SmallSet.h" 67 #include "llvm/ADT/SmallVector.h" 68 #include "llvm/ADT/iterator_range.h" 69 #include "llvm/Analysis/IVUsers.h" 70 #include "llvm/Analysis/LoopAnalysisManager.h" 71 #include "llvm/Analysis/LoopInfo.h" 72 #include "llvm/Analysis/LoopPass.h" 73 #include "llvm/Analysis/ScalarEvolution.h" 74 #include "llvm/Analysis/ScalarEvolutionExpander.h" 75 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 76 #include "llvm/Analysis/ScalarEvolutionNormalization.h" 77 #include "llvm/Analysis/TargetTransformInfo.h" 78 #include "llvm/Transforms/Utils/Local.h" 79 #include "llvm/Config/llvm-config.h" 80 #include "llvm/IR/BasicBlock.h" 81 #include "llvm/IR/Constant.h" 82 #include "llvm/IR/Constants.h" 83 #include "llvm/IR/DerivedTypes.h" 84 #include "llvm/IR/Dominators.h" 85 #include "llvm/IR/GlobalValue.h" 86 #include "llvm/IR/IRBuilder.h" 87 #include "llvm/IR/InstrTypes.h" 88 #include "llvm/IR/Instruction.h" 89 #include "llvm/IR/Instructions.h" 90 #include "llvm/IR/IntrinsicInst.h" 91 #include "llvm/IR/Intrinsics.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/OperandTraits.h" 94 #include "llvm/IR/Operator.h" 95 #include "llvm/IR/PassManager.h" 96 #include "llvm/IR/Type.h" 97 #include "llvm/IR/Use.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/IR/ValueHandle.h" 101 #include "llvm/Pass.h" 102 #include "llvm/Support/Casting.h" 103 #include "llvm/Support/CommandLine.h" 104 #include "llvm/Support/Compiler.h" 105 #include "llvm/Support/Debug.h" 106 #include "llvm/Support/ErrorHandling.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Transforms/Scalar.h" 110 #include "llvm/Transforms/Utils.h" 111 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 112 #include <algorithm> 113 #include <cassert> 114 #include <cstddef> 115 #include <cstdint> 116 #include <cstdlib> 117 #include <iterator> 118 #include <limits> 119 #include <map> 120 #include <utility> 121 122 using namespace llvm; 123 124 #define DEBUG_TYPE "loop-reduce" 125 126 /// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for 127 /// bail out. This threshold is far beyond the number of users that LSR can 128 /// conceivably solve, so it should not affect generated code, but catches the 129 /// worst cases before LSR burns too much compile time and stack space. 130 static const unsigned MaxIVUsers = 200; 131 132 // Temporary flag to cleanup congruent phis after LSR phi expansion. 133 // It's currently disabled until we can determine whether it's truly useful or 134 // not. The flag should be removed after the v3.0 release. 135 // This is now needed for ivchains. 136 static cl::opt<bool> EnablePhiElim( 137 "enable-lsr-phielim", cl::Hidden, cl::init(true), 138 cl::desc("Enable LSR phi elimination")); 139 140 // The flag adds instruction count to solutions cost comparision. 141 static cl::opt<bool> InsnsCost( 142 "lsr-insns-cost", cl::Hidden, cl::init(true), 143 cl::desc("Add instruction count to a LSR cost model")); 144 145 // Flag to choose how to narrow complex lsr solution 146 static cl::opt<bool> LSRExpNarrow( 147 "lsr-exp-narrow", cl::Hidden, cl::init(false), 148 cl::desc("Narrow LSR complex solution using" 149 " expectation of registers number")); 150 151 // Flag to narrow search space by filtering non-optimal formulae with 152 // the same ScaledReg and Scale. 153 static cl::opt<bool> FilterSameScaledReg( 154 "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true), 155 cl::desc("Narrow LSR search space by filtering non-optimal formulae" 156 " with the same ScaledReg and Scale")); 157 158 #ifndef NDEBUG 159 // Stress test IV chain generation. 160 static cl::opt<bool> StressIVChain( 161 "stress-ivchain", cl::Hidden, cl::init(false), 162 cl::desc("Stress test LSR IV chains")); 163 #else 164 static bool StressIVChain = false; 165 #endif 166 167 namespace { 168 169 struct MemAccessTy { 170 /// Used in situations where the accessed memory type is unknown. 171 static const unsigned UnknownAddressSpace = 172 std::numeric_limits<unsigned>::max(); 173 174 Type *MemTy = nullptr; 175 unsigned AddrSpace = UnknownAddressSpace; 176 177 MemAccessTy() = default; 178 MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {} 179 180 bool operator==(MemAccessTy Other) const { 181 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace; 182 } 183 184 bool operator!=(MemAccessTy Other) const { return !(*this == Other); } 185 186 static MemAccessTy getUnknown(LLVMContext &Ctx, 187 unsigned AS = UnknownAddressSpace) { 188 return MemAccessTy(Type::getVoidTy(Ctx), AS); 189 } 190 191 Type *getType() { return MemTy; } 192 }; 193 194 /// This class holds data which is used to order reuse candidates. 195 class RegSortData { 196 public: 197 /// This represents the set of LSRUse indices which reference 198 /// a particular register. 199 SmallBitVector UsedByIndices; 200 201 void print(raw_ostream &OS) const; 202 void dump() const; 203 }; 204 205 } // end anonymous namespace 206 207 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 208 void RegSortData::print(raw_ostream &OS) const { 209 OS << "[NumUses=" << UsedByIndices.count() << ']'; 210 } 211 212 LLVM_DUMP_METHOD void RegSortData::dump() const { 213 print(errs()); errs() << '\n'; 214 } 215 #endif 216 217 namespace { 218 219 /// Map register candidates to information about how they are used. 220 class RegUseTracker { 221 using RegUsesTy = DenseMap<const SCEV *, RegSortData>; 222 223 RegUsesTy RegUsesMap; 224 SmallVector<const SCEV *, 16> RegSequence; 225 226 public: 227 void countRegister(const SCEV *Reg, size_t LUIdx); 228 void dropRegister(const SCEV *Reg, size_t LUIdx); 229 void swapAndDropUse(size_t LUIdx, size_t LastLUIdx); 230 231 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const; 232 233 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const; 234 235 void clear(); 236 237 using iterator = SmallVectorImpl<const SCEV *>::iterator; 238 using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator; 239 240 iterator begin() { return RegSequence.begin(); } 241 iterator end() { return RegSequence.end(); } 242 const_iterator begin() const { return RegSequence.begin(); } 243 const_iterator end() const { return RegSequence.end(); } 244 }; 245 246 } // end anonymous namespace 247 248 void 249 RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) { 250 std::pair<RegUsesTy::iterator, bool> Pair = 251 RegUsesMap.insert(std::make_pair(Reg, RegSortData())); 252 RegSortData &RSD = Pair.first->second; 253 if (Pair.second) 254 RegSequence.push_back(Reg); 255 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1)); 256 RSD.UsedByIndices.set(LUIdx); 257 } 258 259 void 260 RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) { 261 RegUsesTy::iterator It = RegUsesMap.find(Reg); 262 assert(It != RegUsesMap.end()); 263 RegSortData &RSD = It->second; 264 assert(RSD.UsedByIndices.size() > LUIdx); 265 RSD.UsedByIndices.reset(LUIdx); 266 } 267 268 void 269 RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) { 270 assert(LUIdx <= LastLUIdx); 271 272 // Update RegUses. The data structure is not optimized for this purpose; 273 // we must iterate through it and update each of the bit vectors. 274 for (auto &Pair : RegUsesMap) { 275 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices; 276 if (LUIdx < UsedByIndices.size()) 277 UsedByIndices[LUIdx] = 278 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false; 279 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx)); 280 } 281 } 282 283 bool 284 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const { 285 RegUsesTy::const_iterator I = RegUsesMap.find(Reg); 286 if (I == RegUsesMap.end()) 287 return false; 288 const SmallBitVector &UsedByIndices = I->second.UsedByIndices; 289 int i = UsedByIndices.find_first(); 290 if (i == -1) return false; 291 if ((size_t)i != LUIdx) return true; 292 return UsedByIndices.find_next(i) != -1; 293 } 294 295 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const { 296 RegUsesTy::const_iterator I = RegUsesMap.find(Reg); 297 assert(I != RegUsesMap.end() && "Unknown register!"); 298 return I->second.UsedByIndices; 299 } 300 301 void RegUseTracker::clear() { 302 RegUsesMap.clear(); 303 RegSequence.clear(); 304 } 305 306 namespace { 307 308 /// This class holds information that describes a formula for computing 309 /// satisfying a use. It may include broken-out immediates and scaled registers. 310 struct Formula { 311 /// Global base address used for complex addressing. 312 GlobalValue *BaseGV = nullptr; 313 314 /// Base offset for complex addressing. 315 int64_t BaseOffset = 0; 316 317 /// Whether any complex addressing has a base register. 318 bool HasBaseReg = false; 319 320 /// The scale of any complex addressing. 321 int64_t Scale = 0; 322 323 /// The list of "base" registers for this use. When this is non-empty. The 324 /// canonical representation of a formula is 325 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and 326 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty(). 327 /// 3. The reg containing recurrent expr related with currect loop in the 328 /// formula should be put in the ScaledReg. 329 /// #1 enforces that the scaled register is always used when at least two 330 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2. 331 /// #2 enforces that 1 * reg is reg. 332 /// #3 ensures invariant regs with respect to current loop can be combined 333 /// together in LSR codegen. 334 /// This invariant can be temporarly broken while building a formula. 335 /// However, every formula inserted into the LSRInstance must be in canonical 336 /// form. 337 SmallVector<const SCEV *, 4> BaseRegs; 338 339 /// The 'scaled' register for this use. This should be non-null when Scale is 340 /// not zero. 341 const SCEV *ScaledReg = nullptr; 342 343 /// An additional constant offset which added near the use. This requires a 344 /// temporary register, but the offset itself can live in an add immediate 345 /// field rather than a register. 346 int64_t UnfoldedOffset = 0; 347 348 Formula() = default; 349 350 void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE); 351 352 bool isCanonical(const Loop &L) const; 353 354 void canonicalize(const Loop &L); 355 356 bool unscale(); 357 358 bool hasZeroEnd() const; 359 360 size_t getNumRegs() const; 361 Type *getType() const; 362 363 void deleteBaseReg(const SCEV *&S); 364 365 bool referencesReg(const SCEV *S) const; 366 bool hasRegsUsedByUsesOtherThan(size_t LUIdx, 367 const RegUseTracker &RegUses) const; 368 369 void print(raw_ostream &OS) const; 370 void dump() const; 371 }; 372 373 } // end anonymous namespace 374 375 /// Recursion helper for initialMatch. 376 static void DoInitialMatch(const SCEV *S, Loop *L, 377 SmallVectorImpl<const SCEV *> &Good, 378 SmallVectorImpl<const SCEV *> &Bad, 379 ScalarEvolution &SE) { 380 // Collect expressions which properly dominate the loop header. 381 if (SE.properlyDominates(S, L->getHeader())) { 382 Good.push_back(S); 383 return; 384 } 385 386 // Look at add operands. 387 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 388 for (const SCEV *S : Add->operands()) 389 DoInitialMatch(S, L, Good, Bad, SE); 390 return; 391 } 392 393 // Look at addrec operands. 394 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 395 if (!AR->getStart()->isZero() && AR->isAffine()) { 396 DoInitialMatch(AR->getStart(), L, Good, Bad, SE); 397 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0), 398 AR->getStepRecurrence(SE), 399 // FIXME: AR->getNoWrapFlags() 400 AR->getLoop(), SCEV::FlagAnyWrap), 401 L, Good, Bad, SE); 402 return; 403 } 404 405 // Handle a multiplication by -1 (negation) if it didn't fold. 406 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) 407 if (Mul->getOperand(0)->isAllOnesValue()) { 408 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end()); 409 const SCEV *NewMul = SE.getMulExpr(Ops); 410 411 SmallVector<const SCEV *, 4> MyGood; 412 SmallVector<const SCEV *, 4> MyBad; 413 DoInitialMatch(NewMul, L, MyGood, MyBad, SE); 414 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue( 415 SE.getEffectiveSCEVType(NewMul->getType()))); 416 for (const SCEV *S : MyGood) 417 Good.push_back(SE.getMulExpr(NegOne, S)); 418 for (const SCEV *S : MyBad) 419 Bad.push_back(SE.getMulExpr(NegOne, S)); 420 return; 421 } 422 423 // Ok, we can't do anything interesting. Just stuff the whole thing into a 424 // register and hope for the best. 425 Bad.push_back(S); 426 } 427 428 /// Incorporate loop-variant parts of S into this Formula, attempting to keep 429 /// all loop-invariant and loop-computable values in a single base register. 430 void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) { 431 SmallVector<const SCEV *, 4> Good; 432 SmallVector<const SCEV *, 4> Bad; 433 DoInitialMatch(S, L, Good, Bad, SE); 434 if (!Good.empty()) { 435 const SCEV *Sum = SE.getAddExpr(Good); 436 if (!Sum->isZero()) 437 BaseRegs.push_back(Sum); 438 HasBaseReg = true; 439 } 440 if (!Bad.empty()) { 441 const SCEV *Sum = SE.getAddExpr(Bad); 442 if (!Sum->isZero()) 443 BaseRegs.push_back(Sum); 444 HasBaseReg = true; 445 } 446 canonicalize(*L); 447 } 448 449 /// Check whether or not this formula satisfies the canonical 450 /// representation. 451 /// \see Formula::BaseRegs. 452 bool Formula::isCanonical(const Loop &L) const { 453 if (!ScaledReg) 454 return BaseRegs.size() <= 1; 455 456 if (Scale != 1) 457 return true; 458 459 if (Scale == 1 && BaseRegs.empty()) 460 return false; 461 462 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg); 463 if (SAR && SAR->getLoop() == &L) 464 return true; 465 466 // If ScaledReg is not a recurrent expr, or it is but its loop is not current 467 // loop, meanwhile BaseRegs contains a recurrent expr reg related with current 468 // loop, we want to swap the reg in BaseRegs with ScaledReg. 469 auto I = 470 find_if(make_range(BaseRegs.begin(), BaseRegs.end()), [&](const SCEV *S) { 471 return isa<const SCEVAddRecExpr>(S) && 472 (cast<SCEVAddRecExpr>(S)->getLoop() == &L); 473 }); 474 return I == BaseRegs.end(); 475 } 476 477 /// Helper method to morph a formula into its canonical representation. 478 /// \see Formula::BaseRegs. 479 /// Every formula having more than one base register, must use the ScaledReg 480 /// field. Otherwise, we would have to do special cases everywhere in LSR 481 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ... 482 /// On the other hand, 1*reg should be canonicalized into reg. 483 void Formula::canonicalize(const Loop &L) { 484 if (isCanonical(L)) 485 return; 486 // So far we did not need this case. This is easy to implement but it is 487 // useless to maintain dead code. Beside it could hurt compile time. 488 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed."); 489 490 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg. 491 if (!ScaledReg) { 492 ScaledReg = BaseRegs.back(); 493 BaseRegs.pop_back(); 494 Scale = 1; 495 } 496 497 // If ScaledReg is an invariant with respect to L, find the reg from 498 // BaseRegs containing the recurrent expr related with Loop L. Swap the 499 // reg with ScaledReg. 500 const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg); 501 if (!SAR || SAR->getLoop() != &L) { 502 auto I = find_if(make_range(BaseRegs.begin(), BaseRegs.end()), 503 [&](const SCEV *S) { 504 return isa<const SCEVAddRecExpr>(S) && 505 (cast<SCEVAddRecExpr>(S)->getLoop() == &L); 506 }); 507 if (I != BaseRegs.end()) 508 std::swap(ScaledReg, *I); 509 } 510 } 511 512 /// Get rid of the scale in the formula. 513 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2. 514 /// \return true if it was possible to get rid of the scale, false otherwise. 515 /// \note After this operation the formula may not be in the canonical form. 516 bool Formula::unscale() { 517 if (Scale != 1) 518 return false; 519 Scale = 0; 520 BaseRegs.push_back(ScaledReg); 521 ScaledReg = nullptr; 522 return true; 523 } 524 525 bool Formula::hasZeroEnd() const { 526 if (UnfoldedOffset || BaseOffset) 527 return false; 528 if (BaseRegs.size() != 1 || ScaledReg) 529 return false; 530 return true; 531 } 532 533 /// Return the total number of register operands used by this formula. This does 534 /// not include register uses implied by non-constant addrec strides. 535 size_t Formula::getNumRegs() const { 536 return !!ScaledReg + BaseRegs.size(); 537 } 538 539 /// Return the type of this formula, if it has one, or null otherwise. This type 540 /// is meaningless except for the bit size. 541 Type *Formula::getType() const { 542 return !BaseRegs.empty() ? BaseRegs.front()->getType() : 543 ScaledReg ? ScaledReg->getType() : 544 BaseGV ? BaseGV->getType() : 545 nullptr; 546 } 547 548 /// Delete the given base reg from the BaseRegs list. 549 void Formula::deleteBaseReg(const SCEV *&S) { 550 if (&S != &BaseRegs.back()) 551 std::swap(S, BaseRegs.back()); 552 BaseRegs.pop_back(); 553 } 554 555 /// Test if this formula references the given register. 556 bool Formula::referencesReg(const SCEV *S) const { 557 return S == ScaledReg || is_contained(BaseRegs, S); 558 } 559 560 /// Test whether this formula uses registers which are used by uses other than 561 /// the use with the given index. 562 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx, 563 const RegUseTracker &RegUses) const { 564 if (ScaledReg) 565 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx)) 566 return true; 567 for (const SCEV *BaseReg : BaseRegs) 568 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx)) 569 return true; 570 return false; 571 } 572 573 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 574 void Formula::print(raw_ostream &OS) const { 575 bool First = true; 576 if (BaseGV) { 577 if (!First) OS << " + "; else First = false; 578 BaseGV->printAsOperand(OS, /*PrintType=*/false); 579 } 580 if (BaseOffset != 0) { 581 if (!First) OS << " + "; else First = false; 582 OS << BaseOffset; 583 } 584 for (const SCEV *BaseReg : BaseRegs) { 585 if (!First) OS << " + "; else First = false; 586 OS << "reg(" << *BaseReg << ')'; 587 } 588 if (HasBaseReg && BaseRegs.empty()) { 589 if (!First) OS << " + "; else First = false; 590 OS << "**error: HasBaseReg**"; 591 } else if (!HasBaseReg && !BaseRegs.empty()) { 592 if (!First) OS << " + "; else First = false; 593 OS << "**error: !HasBaseReg**"; 594 } 595 if (Scale != 0) { 596 if (!First) OS << " + "; else First = false; 597 OS << Scale << "*reg("; 598 if (ScaledReg) 599 OS << *ScaledReg; 600 else 601 OS << "<unknown>"; 602 OS << ')'; 603 } 604 if (UnfoldedOffset != 0) { 605 if (!First) OS << " + "; 606 OS << "imm(" << UnfoldedOffset << ')'; 607 } 608 } 609 610 LLVM_DUMP_METHOD void Formula::dump() const { 611 print(errs()); errs() << '\n'; 612 } 613 #endif 614 615 /// Return true if the given addrec can be sign-extended without changing its 616 /// value. 617 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { 618 Type *WideTy = 619 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1); 620 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); 621 } 622 623 /// Return true if the given add can be sign-extended without changing its 624 /// value. 625 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) { 626 Type *WideTy = 627 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1); 628 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy)); 629 } 630 631 /// Return true if the given mul can be sign-extended without changing its 632 /// value. 633 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) { 634 Type *WideTy = 635 IntegerType::get(SE.getContext(), 636 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands()); 637 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy)); 638 } 639 640 /// Return an expression for LHS /s RHS, if it can be determined and if the 641 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits 642 /// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that 643 /// the multiplication may overflow, which is useful when the result will be 644 /// used in a context where the most significant bits are ignored. 645 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS, 646 ScalarEvolution &SE, 647 bool IgnoreSignificantBits = false) { 648 // Handle the trivial case, which works for any SCEV type. 649 if (LHS == RHS) 650 return SE.getConstant(LHS->getType(), 1); 651 652 // Handle a few RHS special cases. 653 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS); 654 if (RC) { 655 const APInt &RA = RC->getAPInt(); 656 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do 657 // some folding. 658 if (RA.isAllOnesValue()) 659 return SE.getMulExpr(LHS, RC); 660 // Handle x /s 1 as x. 661 if (RA == 1) 662 return LHS; 663 } 664 665 // Check for a division of a constant by a constant. 666 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) { 667 if (!RC) 668 return nullptr; 669 const APInt &LA = C->getAPInt(); 670 const APInt &RA = RC->getAPInt(); 671 if (LA.srem(RA) != 0) 672 return nullptr; 673 return SE.getConstant(LA.sdiv(RA)); 674 } 675 676 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow. 677 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) { 678 if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) { 679 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE, 680 IgnoreSignificantBits); 681 if (!Step) return nullptr; 682 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE, 683 IgnoreSignificantBits); 684 if (!Start) return nullptr; 685 // FlagNW is independent of the start value, step direction, and is 686 // preserved with smaller magnitude steps. 687 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 688 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap); 689 } 690 return nullptr; 691 } 692 693 // Distribute the sdiv over add operands, if the add doesn't overflow. 694 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) { 695 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) { 696 SmallVector<const SCEV *, 8> Ops; 697 for (const SCEV *S : Add->operands()) { 698 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits); 699 if (!Op) return nullptr; 700 Ops.push_back(Op); 701 } 702 return SE.getAddExpr(Ops); 703 } 704 return nullptr; 705 } 706 707 // Check for a multiply operand that we can pull RHS out of. 708 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) { 709 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) { 710 SmallVector<const SCEV *, 4> Ops; 711 bool Found = false; 712 for (const SCEV *S : Mul->operands()) { 713 if (!Found) 714 if (const SCEV *Q = getExactSDiv(S, RHS, SE, 715 IgnoreSignificantBits)) { 716 S = Q; 717 Found = true; 718 } 719 Ops.push_back(S); 720 } 721 return Found ? SE.getMulExpr(Ops) : nullptr; 722 } 723 return nullptr; 724 } 725 726 // Otherwise we don't know. 727 return nullptr; 728 } 729 730 /// If S involves the addition of a constant integer value, return that integer 731 /// value, and mutate S to point to a new SCEV with that value excluded. 732 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) { 733 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 734 if (C->getAPInt().getMinSignedBits() <= 64) { 735 S = SE.getConstant(C->getType(), 0); 736 return C->getValue()->getSExtValue(); 737 } 738 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 739 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end()); 740 int64_t Result = ExtractImmediate(NewOps.front(), SE); 741 if (Result != 0) 742 S = SE.getAddExpr(NewOps); 743 return Result; 744 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 745 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end()); 746 int64_t Result = ExtractImmediate(NewOps.front(), SE); 747 if (Result != 0) 748 S = SE.getAddRecExpr(NewOps, AR->getLoop(), 749 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 750 SCEV::FlagAnyWrap); 751 return Result; 752 } 753 return 0; 754 } 755 756 /// If S involves the addition of a GlobalValue address, return that symbol, and 757 /// mutate S to point to a new SCEV with that value excluded. 758 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) { 759 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 760 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) { 761 S = SE.getConstant(GV->getType(), 0); 762 return GV; 763 } 764 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 765 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end()); 766 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE); 767 if (Result) 768 S = SE.getAddExpr(NewOps); 769 return Result; 770 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 771 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end()); 772 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE); 773 if (Result) 774 S = SE.getAddRecExpr(NewOps, AR->getLoop(), 775 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 776 SCEV::FlagAnyWrap); 777 return Result; 778 } 779 return nullptr; 780 } 781 782 /// Returns true if the specified instruction is using the specified value as an 783 /// address. 784 static bool isAddressUse(const TargetTransformInfo &TTI, 785 Instruction *Inst, Value *OperandVal) { 786 bool isAddress = isa<LoadInst>(Inst); 787 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 788 if (SI->getPointerOperand() == OperandVal) 789 isAddress = true; 790 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 791 // Addressing modes can also be folded into prefetches and a variety 792 // of intrinsics. 793 switch (II->getIntrinsicID()) { 794 case Intrinsic::memset: 795 case Intrinsic::prefetch: 796 if (II->getArgOperand(0) == OperandVal) 797 isAddress = true; 798 break; 799 case Intrinsic::memmove: 800 case Intrinsic::memcpy: 801 if (II->getArgOperand(0) == OperandVal || 802 II->getArgOperand(1) == OperandVal) 803 isAddress = true; 804 break; 805 default: { 806 MemIntrinsicInfo IntrInfo; 807 if (TTI.getTgtMemIntrinsic(II, IntrInfo)) { 808 if (IntrInfo.PtrVal == OperandVal) 809 isAddress = true; 810 } 811 } 812 } 813 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { 814 if (RMW->getPointerOperand() == OperandVal) 815 isAddress = true; 816 } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 817 if (CmpX->getPointerOperand() == OperandVal) 818 isAddress = true; 819 } 820 return isAddress; 821 } 822 823 /// Return the type of the memory being accessed. 824 static MemAccessTy getAccessType(const TargetTransformInfo &TTI, 825 Instruction *Inst, Value *OperandVal) { 826 MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace); 827 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 828 AccessTy.MemTy = SI->getOperand(0)->getType(); 829 AccessTy.AddrSpace = SI->getPointerAddressSpace(); 830 } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 831 AccessTy.AddrSpace = LI->getPointerAddressSpace(); 832 } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { 833 AccessTy.AddrSpace = RMW->getPointerAddressSpace(); 834 } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { 835 AccessTy.AddrSpace = CmpX->getPointerAddressSpace(); 836 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 837 switch (II->getIntrinsicID()) { 838 case Intrinsic::prefetch: 839 case Intrinsic::memset: 840 AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace(); 841 AccessTy.MemTy = OperandVal->getType(); 842 break; 843 case Intrinsic::memmove: 844 case Intrinsic::memcpy: 845 AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace(); 846 AccessTy.MemTy = OperandVal->getType(); 847 break; 848 default: { 849 MemIntrinsicInfo IntrInfo; 850 if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) { 851 AccessTy.AddrSpace 852 = IntrInfo.PtrVal->getType()->getPointerAddressSpace(); 853 } 854 855 break; 856 } 857 } 858 } 859 860 // All pointers have the same requirements, so canonicalize them to an 861 // arbitrary pointer type to minimize variation. 862 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy)) 863 AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1), 864 PTy->getAddressSpace()); 865 866 return AccessTy; 867 } 868 869 /// Return true if this AddRec is already a phi in its loop. 870 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { 871 for (PHINode &PN : AR->getLoop()->getHeader()->phis()) { 872 if (SE.isSCEVable(PN.getType()) && 873 (SE.getEffectiveSCEVType(PN.getType()) == 874 SE.getEffectiveSCEVType(AR->getType())) && 875 SE.getSCEV(&PN) == AR) 876 return true; 877 } 878 return false; 879 } 880 881 /// Check if expanding this expression is likely to incur significant cost. This 882 /// is tricky because SCEV doesn't track which expressions are actually computed 883 /// by the current IR. 884 /// 885 /// We currently allow expansion of IV increments that involve adds, 886 /// multiplication by constants, and AddRecs from existing phis. 887 /// 888 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an 889 /// obvious multiple of the UDivExpr. 890 static bool isHighCostExpansion(const SCEV *S, 891 SmallPtrSetImpl<const SCEV*> &Processed, 892 ScalarEvolution &SE) { 893 // Zero/One operand expressions 894 switch (S->getSCEVType()) { 895 case scUnknown: 896 case scConstant: 897 return false; 898 case scTruncate: 899 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(), 900 Processed, SE); 901 case scZeroExtend: 902 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(), 903 Processed, SE); 904 case scSignExtend: 905 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(), 906 Processed, SE); 907 } 908 909 if (!Processed.insert(S).second) 910 return false; 911 912 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 913 for (const SCEV *S : Add->operands()) { 914 if (isHighCostExpansion(S, Processed, SE)) 915 return true; 916 } 917 return false; 918 } 919 920 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 921 if (Mul->getNumOperands() == 2) { 922 // Multiplication by a constant is ok 923 if (isa<SCEVConstant>(Mul->getOperand(0))) 924 return isHighCostExpansion(Mul->getOperand(1), Processed, SE); 925 926 // If we have the value of one operand, check if an existing 927 // multiplication already generates this expression. 928 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) { 929 Value *UVal = U->getValue(); 930 for (User *UR : UVal->users()) { 931 // If U is a constant, it may be used by a ConstantExpr. 932 Instruction *UI = dyn_cast<Instruction>(UR); 933 if (UI && UI->getOpcode() == Instruction::Mul && 934 SE.isSCEVable(UI->getType())) { 935 return SE.getSCEV(UI) == Mul; 936 } 937 } 938 } 939 } 940 } 941 942 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 943 if (isExistingPhi(AR, SE)) 944 return false; 945 } 946 947 // Fow now, consider any other type of expression (div/mul/min/max) high cost. 948 return true; 949 } 950 951 /// If any of the instructions in the specified set are trivially dead, delete 952 /// them and see if this makes any of their operands subsequently dead. 953 static bool 954 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakTrackingVH> &DeadInsts) { 955 bool Changed = false; 956 957 while (!DeadInsts.empty()) { 958 Value *V = DeadInsts.pop_back_val(); 959 Instruction *I = dyn_cast_or_null<Instruction>(V); 960 961 if (!I || !isInstructionTriviallyDead(I)) 962 continue; 963 964 for (Use &O : I->operands()) 965 if (Instruction *U = dyn_cast<Instruction>(O)) { 966 O = nullptr; 967 if (U->use_empty()) 968 DeadInsts.emplace_back(U); 969 } 970 971 I->eraseFromParent(); 972 Changed = true; 973 } 974 975 return Changed; 976 } 977 978 namespace { 979 980 class LSRUse; 981 982 } // end anonymous namespace 983 984 /// Check if the addressing mode defined by \p F is completely 985 /// folded in \p LU at isel time. 986 /// This includes address-mode folding and special icmp tricks. 987 /// This function returns true if \p LU can accommodate what \p F 988 /// defines and up to 1 base + 1 scaled + offset. 989 /// In other words, if \p F has several base registers, this function may 990 /// still return true. Therefore, users still need to account for 991 /// additional base registers and/or unfolded offsets to derive an 992 /// accurate cost model. 993 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 994 const LSRUse &LU, const Formula &F); 995 996 // Get the cost of the scaling factor used in F for LU. 997 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI, 998 const LSRUse &LU, const Formula &F, 999 const Loop &L); 1000 1001 namespace { 1002 1003 /// This class is used to measure and compare candidate formulae. 1004 class Cost { 1005 TargetTransformInfo::LSRCost C; 1006 1007 public: 1008 Cost() { 1009 C.Insns = 0; 1010 C.NumRegs = 0; 1011 C.AddRecCost = 0; 1012 C.NumIVMuls = 0; 1013 C.NumBaseAdds = 0; 1014 C.ImmCost = 0; 1015 C.SetupCost = 0; 1016 C.ScaleCost = 0; 1017 } 1018 1019 bool isLess(Cost &Other, const TargetTransformInfo &TTI); 1020 1021 void Lose(); 1022 1023 #ifndef NDEBUG 1024 // Once any of the metrics loses, they must all remain losers. 1025 bool isValid() { 1026 return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds 1027 | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u) 1028 || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds 1029 & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u); 1030 } 1031 #endif 1032 1033 bool isLoser() { 1034 assert(isValid() && "invalid cost"); 1035 return C.NumRegs == ~0u; 1036 } 1037 1038 void RateFormula(const TargetTransformInfo &TTI, 1039 const Formula &F, 1040 SmallPtrSetImpl<const SCEV *> &Regs, 1041 const DenseSet<const SCEV *> &VisitedRegs, 1042 const Loop *L, 1043 ScalarEvolution &SE, DominatorTree &DT, 1044 const LSRUse &LU, 1045 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr); 1046 1047 void print(raw_ostream &OS) const; 1048 void dump() const; 1049 1050 private: 1051 void RateRegister(const SCEV *Reg, 1052 SmallPtrSetImpl<const SCEV *> &Regs, 1053 const Loop *L, 1054 ScalarEvolution &SE, DominatorTree &DT, 1055 const TargetTransformInfo &TTI); 1056 void RatePrimaryRegister(const SCEV *Reg, 1057 SmallPtrSetImpl<const SCEV *> &Regs, 1058 const Loop *L, 1059 ScalarEvolution &SE, DominatorTree &DT, 1060 SmallPtrSetImpl<const SCEV *> *LoserRegs, 1061 const TargetTransformInfo &TTI); 1062 }; 1063 1064 /// An operand value in an instruction which is to be replaced with some 1065 /// equivalent, possibly strength-reduced, replacement. 1066 struct LSRFixup { 1067 /// The instruction which will be updated. 1068 Instruction *UserInst = nullptr; 1069 1070 /// The operand of the instruction which will be replaced. The operand may be 1071 /// used more than once; every instance will be replaced. 1072 Value *OperandValToReplace = nullptr; 1073 1074 /// If this user is to use the post-incremented value of an induction 1075 /// variable, this set is non-empty and holds the loops associated with the 1076 /// induction variable. 1077 PostIncLoopSet PostIncLoops; 1078 1079 /// A constant offset to be added to the LSRUse expression. This allows 1080 /// multiple fixups to share the same LSRUse with different offsets, for 1081 /// example in an unrolled loop. 1082 int64_t Offset = 0; 1083 1084 LSRFixup() = default; 1085 1086 bool isUseFullyOutsideLoop(const Loop *L) const; 1087 1088 void print(raw_ostream &OS) const; 1089 void dump() const; 1090 }; 1091 1092 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted 1093 /// SmallVectors of const SCEV*. 1094 struct UniquifierDenseMapInfo { 1095 static SmallVector<const SCEV *, 4> getEmptyKey() { 1096 SmallVector<const SCEV *, 4> V; 1097 V.push_back(reinterpret_cast<const SCEV *>(-1)); 1098 return V; 1099 } 1100 1101 static SmallVector<const SCEV *, 4> getTombstoneKey() { 1102 SmallVector<const SCEV *, 4> V; 1103 V.push_back(reinterpret_cast<const SCEV *>(-2)); 1104 return V; 1105 } 1106 1107 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) { 1108 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 1109 } 1110 1111 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS, 1112 const SmallVector<const SCEV *, 4> &RHS) { 1113 return LHS == RHS; 1114 } 1115 }; 1116 1117 /// This class holds the state that LSR keeps for each use in IVUsers, as well 1118 /// as uses invented by LSR itself. It includes information about what kinds of 1119 /// things can be folded into the user, information about the user itself, and 1120 /// information about how the use may be satisfied. TODO: Represent multiple 1121 /// users of the same expression in common? 1122 class LSRUse { 1123 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier; 1124 1125 public: 1126 /// An enum for a kind of use, indicating what types of scaled and immediate 1127 /// operands it might support. 1128 enum KindType { 1129 Basic, ///< A normal use, with no folding. 1130 Special, ///< A special case of basic, allowing -1 scales. 1131 Address, ///< An address use; folding according to TargetLowering 1132 ICmpZero ///< An equality icmp with both operands folded into one. 1133 // TODO: Add a generic icmp too? 1134 }; 1135 1136 using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>; 1137 1138 KindType Kind; 1139 MemAccessTy AccessTy; 1140 1141 /// The list of operands which are to be replaced. 1142 SmallVector<LSRFixup, 8> Fixups; 1143 1144 /// Keep track of the min and max offsets of the fixups. 1145 int64_t MinOffset = std::numeric_limits<int64_t>::max(); 1146 int64_t MaxOffset = std::numeric_limits<int64_t>::min(); 1147 1148 /// This records whether all of the fixups using this LSRUse are outside of 1149 /// the loop, in which case some special-case heuristics may be used. 1150 bool AllFixupsOutsideLoop = true; 1151 1152 /// RigidFormula is set to true to guarantee that this use will be associated 1153 /// with a single formula--the one that initially matched. Some SCEV 1154 /// expressions cannot be expanded. This allows LSR to consider the registers 1155 /// used by those expressions without the need to expand them later after 1156 /// changing the formula. 1157 bool RigidFormula = false; 1158 1159 /// This records the widest use type for any fixup using this 1160 /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max 1161 /// fixup widths to be equivalent, because the narrower one may be relying on 1162 /// the implicit truncation to truncate away bogus bits. 1163 Type *WidestFixupType = nullptr; 1164 1165 /// A list of ways to build a value that can satisfy this user. After the 1166 /// list is populated, one of these is selected heuristically and used to 1167 /// formulate a replacement for OperandValToReplace in UserInst. 1168 SmallVector<Formula, 12> Formulae; 1169 1170 /// The set of register candidates used by all formulae in this LSRUse. 1171 SmallPtrSet<const SCEV *, 4> Regs; 1172 1173 LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {} 1174 1175 LSRFixup &getNewFixup() { 1176 Fixups.push_back(LSRFixup()); 1177 return Fixups.back(); 1178 } 1179 1180 void pushFixup(LSRFixup &f) { 1181 Fixups.push_back(f); 1182 if (f.Offset > MaxOffset) 1183 MaxOffset = f.Offset; 1184 if (f.Offset < MinOffset) 1185 MinOffset = f.Offset; 1186 } 1187 1188 bool HasFormulaWithSameRegs(const Formula &F) const; 1189 float getNotSelectedProbability(const SCEV *Reg) const; 1190 bool InsertFormula(const Formula &F, const Loop &L); 1191 void DeleteFormula(Formula &F); 1192 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses); 1193 1194 void print(raw_ostream &OS) const; 1195 void dump() const; 1196 }; 1197 1198 } // end anonymous namespace 1199 1200 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1201 LSRUse::KindType Kind, MemAccessTy AccessTy, 1202 GlobalValue *BaseGV, int64_t BaseOffset, 1203 bool HasBaseReg, int64_t Scale, 1204 Instruction *Fixup = nullptr); 1205 1206 /// Tally up interesting quantities from the given register. 1207 void Cost::RateRegister(const SCEV *Reg, 1208 SmallPtrSetImpl<const SCEV *> &Regs, 1209 const Loop *L, 1210 ScalarEvolution &SE, DominatorTree &DT, 1211 const TargetTransformInfo &TTI) { 1212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) { 1213 // If this is an addrec for another loop, it should be an invariant 1214 // with respect to L since L is the innermost loop (at least 1215 // for now LSR only handles innermost loops). 1216 if (AR->getLoop() != L) { 1217 // If the AddRec exists, consider it's register free and leave it alone. 1218 if (isExistingPhi(AR, SE)) 1219 return; 1220 1221 // It is bad to allow LSR for current loop to add induction variables 1222 // for its sibling loops. 1223 if (!AR->getLoop()->contains(L)) { 1224 Lose(); 1225 return; 1226 } 1227 1228 // Otherwise, it will be an invariant with respect to Loop L. 1229 ++C.NumRegs; 1230 return; 1231 } 1232 1233 unsigned LoopCost = 1; 1234 if (TTI.shouldFavorPostInc()) { 1235 const SCEV *LoopStep = AR->getStepRecurrence(SE); 1236 if (isa<SCEVConstant>(LoopStep)) { 1237 // Check if a post-indexed load/store can be used. 1238 if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) || 1239 TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) { 1240 const SCEV *LoopStart = AR->getStart(); 1241 if (!isa<SCEVConstant>(LoopStart) && 1242 SE.isLoopInvariant(LoopStart, L)) 1243 LoopCost = 0; 1244 } 1245 } 1246 } 1247 C.AddRecCost += LoopCost; 1248 1249 // Add the step value register, if it needs one. 1250 // TODO: The non-affine case isn't precisely modeled here. 1251 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) { 1252 if (!Regs.count(AR->getOperand(1))) { 1253 RateRegister(AR->getOperand(1), Regs, L, SE, DT, TTI); 1254 if (isLoser()) 1255 return; 1256 } 1257 } 1258 } 1259 ++C.NumRegs; 1260 1261 // Rough heuristic; favor registers which don't require extra setup 1262 // instructions in the preheader. 1263 if (!isa<SCEVUnknown>(Reg) && 1264 !isa<SCEVConstant>(Reg) && 1265 !(isa<SCEVAddRecExpr>(Reg) && 1266 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) || 1267 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart())))) 1268 ++C.SetupCost; 1269 1270 C.NumIVMuls += isa<SCEVMulExpr>(Reg) && 1271 SE.hasComputableLoopEvolution(Reg, L); 1272 } 1273 1274 /// Record this register in the set. If we haven't seen it before, rate 1275 /// it. Optional LoserRegs provides a way to declare any formula that refers to 1276 /// one of those regs an instant loser. 1277 void Cost::RatePrimaryRegister(const SCEV *Reg, 1278 SmallPtrSetImpl<const SCEV *> &Regs, 1279 const Loop *L, 1280 ScalarEvolution &SE, DominatorTree &DT, 1281 SmallPtrSetImpl<const SCEV *> *LoserRegs, 1282 const TargetTransformInfo &TTI) { 1283 if (LoserRegs && LoserRegs->count(Reg)) { 1284 Lose(); 1285 return; 1286 } 1287 if (Regs.insert(Reg).second) { 1288 RateRegister(Reg, Regs, L, SE, DT, TTI); 1289 if (LoserRegs && isLoser()) 1290 LoserRegs->insert(Reg); 1291 } 1292 } 1293 1294 void Cost::RateFormula(const TargetTransformInfo &TTI, 1295 const Formula &F, 1296 SmallPtrSetImpl<const SCEV *> &Regs, 1297 const DenseSet<const SCEV *> &VisitedRegs, 1298 const Loop *L, 1299 ScalarEvolution &SE, DominatorTree &DT, 1300 const LSRUse &LU, 1301 SmallPtrSetImpl<const SCEV *> *LoserRegs) { 1302 assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula"); 1303 // Tally up the registers. 1304 unsigned PrevAddRecCost = C.AddRecCost; 1305 unsigned PrevNumRegs = C.NumRegs; 1306 unsigned PrevNumBaseAdds = C.NumBaseAdds; 1307 if (const SCEV *ScaledReg = F.ScaledReg) { 1308 if (VisitedRegs.count(ScaledReg)) { 1309 Lose(); 1310 return; 1311 } 1312 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs, TTI); 1313 if (isLoser()) 1314 return; 1315 } 1316 for (const SCEV *BaseReg : F.BaseRegs) { 1317 if (VisitedRegs.count(BaseReg)) { 1318 Lose(); 1319 return; 1320 } 1321 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs, TTI); 1322 if (isLoser()) 1323 return; 1324 } 1325 1326 // Determine how many (unfolded) adds we'll need inside the loop. 1327 size_t NumBaseParts = F.getNumRegs(); 1328 if (NumBaseParts > 1) 1329 // Do not count the base and a possible second register if the target 1330 // allows to fold 2 registers. 1331 C.NumBaseAdds += 1332 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F))); 1333 C.NumBaseAdds += (F.UnfoldedOffset != 0); 1334 1335 // Accumulate non-free scaling amounts. 1336 C.ScaleCost += getScalingFactorCost(TTI, LU, F, *L); 1337 1338 // Tally up the non-zero immediates. 1339 for (const LSRFixup &Fixup : LU.Fixups) { 1340 int64_t O = Fixup.Offset; 1341 int64_t Offset = (uint64_t)O + F.BaseOffset; 1342 if (F.BaseGV) 1343 C.ImmCost += 64; // Handle symbolic values conservatively. 1344 // TODO: This should probably be the pointer size. 1345 else if (Offset != 0) 1346 C.ImmCost += APInt(64, Offset, true).getMinSignedBits(); 1347 1348 // Check with target if this offset with this instruction is 1349 // specifically not supported. 1350 if (LU.Kind == LSRUse::Address && Offset != 0 && 1351 !isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV, 1352 Offset, F.HasBaseReg, F.Scale, Fixup.UserInst)) 1353 C.NumBaseAdds++; 1354 } 1355 1356 // If we don't count instruction cost exit here. 1357 if (!InsnsCost) { 1358 assert(isValid() && "invalid cost"); 1359 return; 1360 } 1361 1362 // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as 1363 // additional instruction (at least fill). 1364 unsigned TTIRegNum = TTI.getNumberOfRegisters(false) - 1; 1365 if (C.NumRegs > TTIRegNum) { 1366 // Cost already exceeded TTIRegNum, then only newly added register can add 1367 // new instructions. 1368 if (PrevNumRegs > TTIRegNum) 1369 C.Insns += (C.NumRegs - PrevNumRegs); 1370 else 1371 C.Insns += (C.NumRegs - TTIRegNum); 1372 } 1373 1374 // If ICmpZero formula ends with not 0, it could not be replaced by 1375 // just add or sub. We'll need to compare final result of AddRec. 1376 // That means we'll need an additional instruction. But if the target can 1377 // macro-fuse a compare with a branch, don't count this extra instruction. 1378 // For -10 + {0, +, 1}: 1379 // i = i + 1; 1380 // cmp i, 10 1381 // 1382 // For {-10, +, 1}: 1383 // i = i + 1; 1384 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() && !TTI.canMacroFuseCmp()) 1385 C.Insns++; 1386 // Each new AddRec adds 1 instruction to calculation. 1387 C.Insns += (C.AddRecCost - PrevAddRecCost); 1388 1389 // BaseAdds adds instructions for unfolded registers. 1390 if (LU.Kind != LSRUse::ICmpZero) 1391 C.Insns += C.NumBaseAdds - PrevNumBaseAdds; 1392 assert(isValid() && "invalid cost"); 1393 } 1394 1395 /// Set this cost to a losing value. 1396 void Cost::Lose() { 1397 C.Insns = std::numeric_limits<unsigned>::max(); 1398 C.NumRegs = std::numeric_limits<unsigned>::max(); 1399 C.AddRecCost = std::numeric_limits<unsigned>::max(); 1400 C.NumIVMuls = std::numeric_limits<unsigned>::max(); 1401 C.NumBaseAdds = std::numeric_limits<unsigned>::max(); 1402 C.ImmCost = std::numeric_limits<unsigned>::max(); 1403 C.SetupCost = std::numeric_limits<unsigned>::max(); 1404 C.ScaleCost = std::numeric_limits<unsigned>::max(); 1405 } 1406 1407 /// Choose the lower cost. 1408 bool Cost::isLess(Cost &Other, const TargetTransformInfo &TTI) { 1409 if (InsnsCost.getNumOccurrences() > 0 && InsnsCost && 1410 C.Insns != Other.C.Insns) 1411 return C.Insns < Other.C.Insns; 1412 return TTI.isLSRCostLess(C, Other.C); 1413 } 1414 1415 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1416 void Cost::print(raw_ostream &OS) const { 1417 if (InsnsCost) 1418 OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s "); 1419 OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s"); 1420 if (C.AddRecCost != 0) 1421 OS << ", with addrec cost " << C.AddRecCost; 1422 if (C.NumIVMuls != 0) 1423 OS << ", plus " << C.NumIVMuls << " IV mul" 1424 << (C.NumIVMuls == 1 ? "" : "s"); 1425 if (C.NumBaseAdds != 0) 1426 OS << ", plus " << C.NumBaseAdds << " base add" 1427 << (C.NumBaseAdds == 1 ? "" : "s"); 1428 if (C.ScaleCost != 0) 1429 OS << ", plus " << C.ScaleCost << " scale cost"; 1430 if (C.ImmCost != 0) 1431 OS << ", plus " << C.ImmCost << " imm cost"; 1432 if (C.SetupCost != 0) 1433 OS << ", plus " << C.SetupCost << " setup cost"; 1434 } 1435 1436 LLVM_DUMP_METHOD void Cost::dump() const { 1437 print(errs()); errs() << '\n'; 1438 } 1439 #endif 1440 1441 /// Test whether this fixup always uses its value outside of the given loop. 1442 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const { 1443 // PHI nodes use their value in their incoming blocks. 1444 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) { 1445 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 1446 if (PN->getIncomingValue(i) == OperandValToReplace && 1447 L->contains(PN->getIncomingBlock(i))) 1448 return false; 1449 return true; 1450 } 1451 1452 return !L->contains(UserInst); 1453 } 1454 1455 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1456 void LSRFixup::print(raw_ostream &OS) const { 1457 OS << "UserInst="; 1458 // Store is common and interesting enough to be worth special-casing. 1459 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) { 1460 OS << "store "; 1461 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false); 1462 } else if (UserInst->getType()->isVoidTy()) 1463 OS << UserInst->getOpcodeName(); 1464 else 1465 UserInst->printAsOperand(OS, /*PrintType=*/false); 1466 1467 OS << ", OperandValToReplace="; 1468 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false); 1469 1470 for (const Loop *PIL : PostIncLoops) { 1471 OS << ", PostIncLoop="; 1472 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 1473 } 1474 1475 if (Offset != 0) 1476 OS << ", Offset=" << Offset; 1477 } 1478 1479 LLVM_DUMP_METHOD void LSRFixup::dump() const { 1480 print(errs()); errs() << '\n'; 1481 } 1482 #endif 1483 1484 /// Test whether this use as a formula which has the same registers as the given 1485 /// formula. 1486 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const { 1487 SmallVector<const SCEV *, 4> Key = F.BaseRegs; 1488 if (F.ScaledReg) Key.push_back(F.ScaledReg); 1489 // Unstable sort by host order ok, because this is only used for uniquifying. 1490 llvm::sort(Key.begin(), Key.end()); 1491 return Uniquifier.count(Key); 1492 } 1493 1494 /// The function returns a probability of selecting formula without Reg. 1495 float LSRUse::getNotSelectedProbability(const SCEV *Reg) const { 1496 unsigned FNum = 0; 1497 for (const Formula &F : Formulae) 1498 if (F.referencesReg(Reg)) 1499 FNum++; 1500 return ((float)(Formulae.size() - FNum)) / Formulae.size(); 1501 } 1502 1503 /// If the given formula has not yet been inserted, add it to the list, and 1504 /// return true. Return false otherwise. The formula must be in canonical form. 1505 bool LSRUse::InsertFormula(const Formula &F, const Loop &L) { 1506 assert(F.isCanonical(L) && "Invalid canonical representation"); 1507 1508 if (!Formulae.empty() && RigidFormula) 1509 return false; 1510 1511 SmallVector<const SCEV *, 4> Key = F.BaseRegs; 1512 if (F.ScaledReg) Key.push_back(F.ScaledReg); 1513 // Unstable sort by host order ok, because this is only used for uniquifying. 1514 llvm::sort(Key.begin(), Key.end()); 1515 1516 if (!Uniquifier.insert(Key).second) 1517 return false; 1518 1519 // Using a register to hold the value of 0 is not profitable. 1520 assert((!F.ScaledReg || !F.ScaledReg->isZero()) && 1521 "Zero allocated in a scaled register!"); 1522 #ifndef NDEBUG 1523 for (const SCEV *BaseReg : F.BaseRegs) 1524 assert(!BaseReg->isZero() && "Zero allocated in a base register!"); 1525 #endif 1526 1527 // Add the formula to the list. 1528 Formulae.push_back(F); 1529 1530 // Record registers now being used by this use. 1531 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 1532 if (F.ScaledReg) 1533 Regs.insert(F.ScaledReg); 1534 1535 return true; 1536 } 1537 1538 /// Remove the given formula from this use's list. 1539 void LSRUse::DeleteFormula(Formula &F) { 1540 if (&F != &Formulae.back()) 1541 std::swap(F, Formulae.back()); 1542 Formulae.pop_back(); 1543 } 1544 1545 /// Recompute the Regs field, and update RegUses. 1546 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) { 1547 // Now that we've filtered out some formulae, recompute the Regs set. 1548 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs); 1549 Regs.clear(); 1550 for (const Formula &F : Formulae) { 1551 if (F.ScaledReg) Regs.insert(F.ScaledReg); 1552 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 1553 } 1554 1555 // Update the RegTracker. 1556 for (const SCEV *S : OldRegs) 1557 if (!Regs.count(S)) 1558 RegUses.dropRegister(S, LUIdx); 1559 } 1560 1561 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1562 void LSRUse::print(raw_ostream &OS) const { 1563 OS << "LSR Use: Kind="; 1564 switch (Kind) { 1565 case Basic: OS << "Basic"; break; 1566 case Special: OS << "Special"; break; 1567 case ICmpZero: OS << "ICmpZero"; break; 1568 case Address: 1569 OS << "Address of "; 1570 if (AccessTy.MemTy->isPointerTy()) 1571 OS << "pointer"; // the full pointer type could be really verbose 1572 else { 1573 OS << *AccessTy.MemTy; 1574 } 1575 1576 OS << " in addrspace(" << AccessTy.AddrSpace << ')'; 1577 } 1578 1579 OS << ", Offsets={"; 1580 bool NeedComma = false; 1581 for (const LSRFixup &Fixup : Fixups) { 1582 if (NeedComma) OS << ','; 1583 OS << Fixup.Offset; 1584 NeedComma = true; 1585 } 1586 OS << '}'; 1587 1588 if (AllFixupsOutsideLoop) 1589 OS << ", all-fixups-outside-loop"; 1590 1591 if (WidestFixupType) 1592 OS << ", widest fixup type: " << *WidestFixupType; 1593 } 1594 1595 LLVM_DUMP_METHOD void LSRUse::dump() const { 1596 print(errs()); errs() << '\n'; 1597 } 1598 #endif 1599 1600 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1601 LSRUse::KindType Kind, MemAccessTy AccessTy, 1602 GlobalValue *BaseGV, int64_t BaseOffset, 1603 bool HasBaseReg, int64_t Scale, 1604 Instruction *Fixup/*= nullptr*/) { 1605 switch (Kind) { 1606 case LSRUse::Address: 1607 return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset, 1608 HasBaseReg, Scale, AccessTy.AddrSpace, Fixup); 1609 1610 case LSRUse::ICmpZero: 1611 // There's not even a target hook for querying whether it would be legal to 1612 // fold a GV into an ICmp. 1613 if (BaseGV) 1614 return false; 1615 1616 // ICmp only has two operands; don't allow more than two non-trivial parts. 1617 if (Scale != 0 && HasBaseReg && BaseOffset != 0) 1618 return false; 1619 1620 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by 1621 // putting the scaled register in the other operand of the icmp. 1622 if (Scale != 0 && Scale != -1) 1623 return false; 1624 1625 // If we have low-level target information, ask the target if it can fold an 1626 // integer immediate on an icmp. 1627 if (BaseOffset != 0) { 1628 // We have one of: 1629 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset 1630 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset 1631 // Offs is the ICmp immediate. 1632 if (Scale == 0) 1633 // The cast does the right thing with 1634 // std::numeric_limits<int64_t>::min(). 1635 BaseOffset = -(uint64_t)BaseOffset; 1636 return TTI.isLegalICmpImmediate(BaseOffset); 1637 } 1638 1639 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg 1640 return true; 1641 1642 case LSRUse::Basic: 1643 // Only handle single-register values. 1644 return !BaseGV && Scale == 0 && BaseOffset == 0; 1645 1646 case LSRUse::Special: 1647 // Special case Basic to handle -1 scales. 1648 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0; 1649 } 1650 1651 llvm_unreachable("Invalid LSRUse Kind!"); 1652 } 1653 1654 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1655 int64_t MinOffset, int64_t MaxOffset, 1656 LSRUse::KindType Kind, MemAccessTy AccessTy, 1657 GlobalValue *BaseGV, int64_t BaseOffset, 1658 bool HasBaseReg, int64_t Scale) { 1659 // Check for overflow. 1660 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) != 1661 (MinOffset > 0)) 1662 return false; 1663 MinOffset = (uint64_t)BaseOffset + MinOffset; 1664 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) != 1665 (MaxOffset > 0)) 1666 return false; 1667 MaxOffset = (uint64_t)BaseOffset + MaxOffset; 1668 1669 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset, 1670 HasBaseReg, Scale) && 1671 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset, 1672 HasBaseReg, Scale); 1673 } 1674 1675 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1676 int64_t MinOffset, int64_t MaxOffset, 1677 LSRUse::KindType Kind, MemAccessTy AccessTy, 1678 const Formula &F, const Loop &L) { 1679 // For the purpose of isAMCompletelyFolded either having a canonical formula 1680 // or a scale not equal to zero is correct. 1681 // Problems may arise from non canonical formulae having a scale == 0. 1682 // Strictly speaking it would best to just rely on canonical formulae. 1683 // However, when we generate the scaled formulae, we first check that the 1684 // scaling factor is profitable before computing the actual ScaledReg for 1685 // compile time sake. 1686 assert((F.isCanonical(L) || F.Scale != 0)); 1687 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, 1688 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale); 1689 } 1690 1691 /// Test whether we know how to expand the current formula. 1692 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, 1693 int64_t MaxOffset, LSRUse::KindType Kind, 1694 MemAccessTy AccessTy, GlobalValue *BaseGV, 1695 int64_t BaseOffset, bool HasBaseReg, int64_t Scale) { 1696 // We know how to expand completely foldable formulae. 1697 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, 1698 BaseOffset, HasBaseReg, Scale) || 1699 // Or formulae that use a base register produced by a sum of base 1700 // registers. 1701 (Scale == 1 && 1702 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, 1703 BaseGV, BaseOffset, true, 0)); 1704 } 1705 1706 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, 1707 int64_t MaxOffset, LSRUse::KindType Kind, 1708 MemAccessTy AccessTy, const Formula &F) { 1709 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV, 1710 F.BaseOffset, F.HasBaseReg, F.Scale); 1711 } 1712 1713 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, 1714 const LSRUse &LU, const Formula &F) { 1715 // Target may want to look at the user instructions. 1716 if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) { 1717 for (const LSRFixup &Fixup : LU.Fixups) 1718 if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV, 1719 (F.BaseOffset + Fixup.Offset), F.HasBaseReg, 1720 F.Scale, Fixup.UserInst)) 1721 return false; 1722 return true; 1723 } 1724 1725 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, 1726 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg, 1727 F.Scale); 1728 } 1729 1730 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI, 1731 const LSRUse &LU, const Formula &F, 1732 const Loop &L) { 1733 if (!F.Scale) 1734 return 0; 1735 1736 // If the use is not completely folded in that instruction, we will have to 1737 // pay an extra cost only for scale != 1. 1738 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, 1739 LU.AccessTy, F, L)) 1740 return F.Scale != 1; 1741 1742 switch (LU.Kind) { 1743 case LSRUse::Address: { 1744 // Check the scaling factor cost with both the min and max offsets. 1745 int ScaleCostMinOffset = TTI.getScalingFactorCost( 1746 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg, 1747 F.Scale, LU.AccessTy.AddrSpace); 1748 int ScaleCostMaxOffset = TTI.getScalingFactorCost( 1749 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg, 1750 F.Scale, LU.AccessTy.AddrSpace); 1751 1752 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 && 1753 "Legal addressing mode has an illegal cost!"); 1754 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset); 1755 } 1756 case LSRUse::ICmpZero: 1757 case LSRUse::Basic: 1758 case LSRUse::Special: 1759 // The use is completely folded, i.e., everything is folded into the 1760 // instruction. 1761 return 0; 1762 } 1763 1764 llvm_unreachable("Invalid LSRUse Kind!"); 1765 } 1766 1767 static bool isAlwaysFoldable(const TargetTransformInfo &TTI, 1768 LSRUse::KindType Kind, MemAccessTy AccessTy, 1769 GlobalValue *BaseGV, int64_t BaseOffset, 1770 bool HasBaseReg) { 1771 // Fast-path: zero is always foldable. 1772 if (BaseOffset == 0 && !BaseGV) return true; 1773 1774 // Conservatively, create an address with an immediate and a 1775 // base and a scale. 1776 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; 1777 1778 // Canonicalize a scale of 1 to a base register if the formula doesn't 1779 // already have a base register. 1780 if (!HasBaseReg && Scale == 1) { 1781 Scale = 0; 1782 HasBaseReg = true; 1783 } 1784 1785 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset, 1786 HasBaseReg, Scale); 1787 } 1788 1789 static bool isAlwaysFoldable(const TargetTransformInfo &TTI, 1790 ScalarEvolution &SE, int64_t MinOffset, 1791 int64_t MaxOffset, LSRUse::KindType Kind, 1792 MemAccessTy AccessTy, const SCEV *S, 1793 bool HasBaseReg) { 1794 // Fast-path: zero is always foldable. 1795 if (S->isZero()) return true; 1796 1797 // Conservatively, create an address with an immediate and a 1798 // base and a scale. 1799 int64_t BaseOffset = ExtractImmediate(S, SE); 1800 GlobalValue *BaseGV = ExtractSymbol(S, SE); 1801 1802 // If there's anything else involved, it's not foldable. 1803 if (!S->isZero()) return false; 1804 1805 // Fast-path: zero is always foldable. 1806 if (BaseOffset == 0 && !BaseGV) return true; 1807 1808 // Conservatively, create an address with an immediate and a 1809 // base and a scale. 1810 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; 1811 1812 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, 1813 BaseOffset, HasBaseReg, Scale); 1814 } 1815 1816 namespace { 1817 1818 /// An individual increment in a Chain of IV increments. Relate an IV user to 1819 /// an expression that computes the IV it uses from the IV used by the previous 1820 /// link in the Chain. 1821 /// 1822 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the 1823 /// original IVOperand. The head of the chain's IVOperand is only valid during 1824 /// chain collection, before LSR replaces IV users. During chain generation, 1825 /// IncExpr can be used to find the new IVOperand that computes the same 1826 /// expression. 1827 struct IVInc { 1828 Instruction *UserInst; 1829 Value* IVOperand; 1830 const SCEV *IncExpr; 1831 1832 IVInc(Instruction *U, Value *O, const SCEV *E) 1833 : UserInst(U), IVOperand(O), IncExpr(E) {} 1834 }; 1835 1836 // The list of IV increments in program order. We typically add the head of a 1837 // chain without finding subsequent links. 1838 struct IVChain { 1839 SmallVector<IVInc, 1> Incs; 1840 const SCEV *ExprBase = nullptr; 1841 1842 IVChain() = default; 1843 IVChain(const IVInc &Head, const SCEV *Base) 1844 : Incs(1, Head), ExprBase(Base) {} 1845 1846 using const_iterator = SmallVectorImpl<IVInc>::const_iterator; 1847 1848 // Return the first increment in the chain. 1849 const_iterator begin() const { 1850 assert(!Incs.empty()); 1851 return std::next(Incs.begin()); 1852 } 1853 const_iterator end() const { 1854 return Incs.end(); 1855 } 1856 1857 // Returns true if this chain contains any increments. 1858 bool hasIncs() const { return Incs.size() >= 2; } 1859 1860 // Add an IVInc to the end of this chain. 1861 void add(const IVInc &X) { Incs.push_back(X); } 1862 1863 // Returns the last UserInst in the chain. 1864 Instruction *tailUserInst() const { return Incs.back().UserInst; } 1865 1866 // Returns true if IncExpr can be profitably added to this chain. 1867 bool isProfitableIncrement(const SCEV *OperExpr, 1868 const SCEV *IncExpr, 1869 ScalarEvolution&); 1870 }; 1871 1872 /// Helper for CollectChains to track multiple IV increment uses. Distinguish 1873 /// between FarUsers that definitely cross IV increments and NearUsers that may 1874 /// be used between IV increments. 1875 struct ChainUsers { 1876 SmallPtrSet<Instruction*, 4> FarUsers; 1877 SmallPtrSet<Instruction*, 4> NearUsers; 1878 }; 1879 1880 /// This class holds state for the main loop strength reduction logic. 1881 class LSRInstance { 1882 IVUsers &IU; 1883 ScalarEvolution &SE; 1884 DominatorTree &DT; 1885 LoopInfo &LI; 1886 const TargetTransformInfo &TTI; 1887 Loop *const L; 1888 bool Changed = false; 1889 1890 /// This is the insert position that the current loop's induction variable 1891 /// increment should be placed. In simple loops, this is the latch block's 1892 /// terminator. But in more complicated cases, this is a position which will 1893 /// dominate all the in-loop post-increment users. 1894 Instruction *IVIncInsertPos = nullptr; 1895 1896 /// Interesting factors between use strides. 1897 /// 1898 /// We explicitly use a SetVector which contains a SmallSet, instead of the 1899 /// default, a SmallDenseSet, because we need to use the full range of 1900 /// int64_ts, and there's currently no good way of doing that with 1901 /// SmallDenseSet. 1902 SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors; 1903 1904 /// Interesting use types, to facilitate truncation reuse. 1905 SmallSetVector<Type *, 4> Types; 1906 1907 /// The list of interesting uses. 1908 SmallVector<LSRUse, 16> Uses; 1909 1910 /// Track which uses use which register candidates. 1911 RegUseTracker RegUses; 1912 1913 // Limit the number of chains to avoid quadratic behavior. We don't expect to 1914 // have more than a few IV increment chains in a loop. Missing a Chain falls 1915 // back to normal LSR behavior for those uses. 1916 static const unsigned MaxChains = 8; 1917 1918 /// IV users can form a chain of IV increments. 1919 SmallVector<IVChain, MaxChains> IVChainVec; 1920 1921 /// IV users that belong to profitable IVChains. 1922 SmallPtrSet<Use*, MaxChains> IVIncSet; 1923 1924 void OptimizeShadowIV(); 1925 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse); 1926 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse); 1927 void OptimizeLoopTermCond(); 1928 1929 void ChainInstruction(Instruction *UserInst, Instruction *IVOper, 1930 SmallVectorImpl<ChainUsers> &ChainUsersVec); 1931 void FinalizeChain(IVChain &Chain); 1932 void CollectChains(); 1933 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter, 1934 SmallVectorImpl<WeakTrackingVH> &DeadInsts); 1935 1936 void CollectInterestingTypesAndFactors(); 1937 void CollectFixupsAndInitialFormulae(); 1938 1939 // Support for sharing of LSRUses between LSRFixups. 1940 using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>; 1941 UseMapTy UseMap; 1942 1943 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg, 1944 LSRUse::KindType Kind, MemAccessTy AccessTy); 1945 1946 std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind, 1947 MemAccessTy AccessTy); 1948 1949 void DeleteUse(LSRUse &LU, size_t LUIdx); 1950 1951 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU); 1952 1953 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); 1954 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); 1955 void CountRegisters(const Formula &F, size_t LUIdx); 1956 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F); 1957 1958 void CollectLoopInvariantFixupsAndFormulae(); 1959 1960 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base, 1961 unsigned Depth = 0); 1962 1963 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, 1964 const Formula &Base, unsigned Depth, 1965 size_t Idx, bool IsScaledReg = false); 1966 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base); 1967 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, 1968 const Formula &Base, size_t Idx, 1969 bool IsScaledReg = false); 1970 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); 1971 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx, 1972 const Formula &Base, 1973 const SmallVectorImpl<int64_t> &Worklist, 1974 size_t Idx, bool IsScaledReg = false); 1975 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); 1976 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base); 1977 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base); 1978 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base); 1979 void GenerateCrossUseConstantOffsets(); 1980 void GenerateAllReuseFormulae(); 1981 1982 void FilterOutUndesirableDedicatedRegisters(); 1983 1984 size_t EstimateSearchSpaceComplexity() const; 1985 void NarrowSearchSpaceByDetectingSupersets(); 1986 void NarrowSearchSpaceByCollapsingUnrolledCode(); 1987 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); 1988 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg(); 1989 void NarrowSearchSpaceByDeletingCostlyFormulas(); 1990 void NarrowSearchSpaceByPickingWinnerRegs(); 1991 void NarrowSearchSpaceUsingHeuristics(); 1992 1993 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution, 1994 Cost &SolutionCost, 1995 SmallVectorImpl<const Formula *> &Workspace, 1996 const Cost &CurCost, 1997 const SmallPtrSet<const SCEV *, 16> &CurRegs, 1998 DenseSet<const SCEV *> &VisitedRegs) const; 1999 void Solve(SmallVectorImpl<const Formula *> &Solution) const; 2000 2001 BasicBlock::iterator 2002 HoistInsertPosition(BasicBlock::iterator IP, 2003 const SmallVectorImpl<Instruction *> &Inputs) const; 2004 BasicBlock::iterator 2005 AdjustInsertPositionForExpand(BasicBlock::iterator IP, 2006 const LSRFixup &LF, 2007 const LSRUse &LU, 2008 SCEVExpander &Rewriter) const; 2009 2010 Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F, 2011 BasicBlock::iterator IP, SCEVExpander &Rewriter, 2012 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 2013 void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF, 2014 const Formula &F, SCEVExpander &Rewriter, 2015 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 2016 void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F, 2017 SCEVExpander &Rewriter, 2018 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; 2019 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution); 2020 2021 public: 2022 LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, 2023 LoopInfo &LI, const TargetTransformInfo &TTI); 2024 2025 bool getChanged() const { return Changed; } 2026 2027 void print_factors_and_types(raw_ostream &OS) const; 2028 void print_fixups(raw_ostream &OS) const; 2029 void print_uses(raw_ostream &OS) const; 2030 void print(raw_ostream &OS) const; 2031 void dump() const; 2032 }; 2033 2034 } // end anonymous namespace 2035 2036 /// If IV is used in a int-to-float cast inside the loop then try to eliminate 2037 /// the cast operation. 2038 void LSRInstance::OptimizeShadowIV() { 2039 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 2040 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2041 return; 2042 2043 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); 2044 UI != E; /* empty */) { 2045 IVUsers::const_iterator CandidateUI = UI; 2046 ++UI; 2047 Instruction *ShadowUse = CandidateUI->getUser(); 2048 Type *DestTy = nullptr; 2049 bool IsSigned = false; 2050 2051 /* If shadow use is a int->float cast then insert a second IV 2052 to eliminate this cast. 2053 2054 for (unsigned i = 0; i < n; ++i) 2055 foo((double)i); 2056 2057 is transformed into 2058 2059 double d = 0.0; 2060 for (unsigned i = 0; i < n; ++i, ++d) 2061 foo(d); 2062 */ 2063 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) { 2064 IsSigned = false; 2065 DestTy = UCast->getDestTy(); 2066 } 2067 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) { 2068 IsSigned = true; 2069 DestTy = SCast->getDestTy(); 2070 } 2071 if (!DestTy) continue; 2072 2073 // If target does not support DestTy natively then do not apply 2074 // this transformation. 2075 if (!TTI.isTypeLegal(DestTy)) continue; 2076 2077 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0)); 2078 if (!PH) continue; 2079 if (PH->getNumIncomingValues() != 2) continue; 2080 2081 // If the calculation in integers overflows, the result in FP type will 2082 // differ. So we only can do this transformation if we are guaranteed to not 2083 // deal with overflowing values 2084 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH)); 2085 if (!AR) continue; 2086 if (IsSigned && !AR->hasNoSignedWrap()) continue; 2087 if (!IsSigned && !AR->hasNoUnsignedWrap()) continue; 2088 2089 Type *SrcTy = PH->getType(); 2090 int Mantissa = DestTy->getFPMantissaWidth(); 2091 if (Mantissa == -1) continue; 2092 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa) 2093 continue; 2094 2095 unsigned Entry, Latch; 2096 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) { 2097 Entry = 0; 2098 Latch = 1; 2099 } else { 2100 Entry = 1; 2101 Latch = 0; 2102 } 2103 2104 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry)); 2105 if (!Init) continue; 2106 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ? 2107 (double)Init->getSExtValue() : 2108 (double)Init->getZExtValue()); 2109 2110 BinaryOperator *Incr = 2111 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch)); 2112 if (!Incr) continue; 2113 if (Incr->getOpcode() != Instruction::Add 2114 && Incr->getOpcode() != Instruction::Sub) 2115 continue; 2116 2117 /* Initialize new IV, double d = 0.0 in above example. */ 2118 ConstantInt *C = nullptr; 2119 if (Incr->getOperand(0) == PH) 2120 C = dyn_cast<ConstantInt>(Incr->getOperand(1)); 2121 else if (Incr->getOperand(1) == PH) 2122 C = dyn_cast<ConstantInt>(Incr->getOperand(0)); 2123 else 2124 continue; 2125 2126 if (!C) continue; 2127 2128 // Ignore negative constants, as the code below doesn't handle them 2129 // correctly. TODO: Remove this restriction. 2130 if (!C->getValue().isStrictlyPositive()) continue; 2131 2132 /* Add new PHINode. */ 2133 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH); 2134 2135 /* create new increment. '++d' in above example. */ 2136 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue()); 2137 BinaryOperator *NewIncr = 2138 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ? 2139 Instruction::FAdd : Instruction::FSub, 2140 NewPH, CFP, "IV.S.next.", Incr); 2141 2142 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry)); 2143 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch)); 2144 2145 /* Remove cast operation */ 2146 ShadowUse->replaceAllUsesWith(NewPH); 2147 ShadowUse->eraseFromParent(); 2148 Changed = true; 2149 break; 2150 } 2151 } 2152 2153 /// If Cond has an operand that is an expression of an IV, set the IV user and 2154 /// stride information and return true, otherwise return false. 2155 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) { 2156 for (IVStrideUse &U : IU) 2157 if (U.getUser() == Cond) { 2158 // NOTE: we could handle setcc instructions with multiple uses here, but 2159 // InstCombine does it as well for simple uses, it's not clear that it 2160 // occurs enough in real life to handle. 2161 CondUse = &U; 2162 return true; 2163 } 2164 return false; 2165 } 2166 2167 /// Rewrite the loop's terminating condition if it uses a max computation. 2168 /// 2169 /// This is a narrow solution to a specific, but acute, problem. For loops 2170 /// like this: 2171 /// 2172 /// i = 0; 2173 /// do { 2174 /// p[i] = 0.0; 2175 /// } while (++i < n); 2176 /// 2177 /// the trip count isn't just 'n', because 'n' might not be positive. And 2178 /// unfortunately this can come up even for loops where the user didn't use 2179 /// a C do-while loop. For example, seemingly well-behaved top-test loops 2180 /// will commonly be lowered like this: 2181 /// 2182 /// if (n > 0) { 2183 /// i = 0; 2184 /// do { 2185 /// p[i] = 0.0; 2186 /// } while (++i < n); 2187 /// } 2188 /// 2189 /// and then it's possible for subsequent optimization to obscure the if 2190 /// test in such a way that indvars can't find it. 2191 /// 2192 /// When indvars can't find the if test in loops like this, it creates a 2193 /// max expression, which allows it to give the loop a canonical 2194 /// induction variable: 2195 /// 2196 /// i = 0; 2197 /// max = n < 1 ? 1 : n; 2198 /// do { 2199 /// p[i] = 0.0; 2200 /// } while (++i != max); 2201 /// 2202 /// Canonical induction variables are necessary because the loop passes 2203 /// are designed around them. The most obvious example of this is the 2204 /// LoopInfo analysis, which doesn't remember trip count values. It 2205 /// expects to be able to rediscover the trip count each time it is 2206 /// needed, and it does this using a simple analysis that only succeeds if 2207 /// the loop has a canonical induction variable. 2208 /// 2209 /// However, when it comes time to generate code, the maximum operation 2210 /// can be quite costly, especially if it's inside of an outer loop. 2211 /// 2212 /// This function solves this problem by detecting this type of loop and 2213 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting 2214 /// the instructions for the maximum computation. 2215 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) { 2216 // Check that the loop matches the pattern we're looking for. 2217 if (Cond->getPredicate() != CmpInst::ICMP_EQ && 2218 Cond->getPredicate() != CmpInst::ICMP_NE) 2219 return Cond; 2220 2221 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1)); 2222 if (!Sel || !Sel->hasOneUse()) return Cond; 2223 2224 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 2225 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) 2226 return Cond; 2227 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1); 2228 2229 // Add one to the backedge-taken count to get the trip count. 2230 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount); 2231 if (IterationCount != SE.getSCEV(Sel)) return Cond; 2232 2233 // Check for a max calculation that matches the pattern. There's no check 2234 // for ICMP_ULE here because the comparison would be with zero, which 2235 // isn't interesting. 2236 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 2237 const SCEVNAryExpr *Max = nullptr; 2238 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) { 2239 Pred = ICmpInst::ICMP_SLE; 2240 Max = S; 2241 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) { 2242 Pred = ICmpInst::ICMP_SLT; 2243 Max = S; 2244 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) { 2245 Pred = ICmpInst::ICMP_ULT; 2246 Max = U; 2247 } else { 2248 // No match; bail. 2249 return Cond; 2250 } 2251 2252 // To handle a max with more than two operands, this optimization would 2253 // require additional checking and setup. 2254 if (Max->getNumOperands() != 2) 2255 return Cond; 2256 2257 const SCEV *MaxLHS = Max->getOperand(0); 2258 const SCEV *MaxRHS = Max->getOperand(1); 2259 2260 // ScalarEvolution canonicalizes constants to the left. For < and >, look 2261 // for a comparison with 1. For <= and >=, a comparison with zero. 2262 if (!MaxLHS || 2263 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One))) 2264 return Cond; 2265 2266 // Check the relevant induction variable for conformance to 2267 // the pattern. 2268 const SCEV *IV = SE.getSCEV(Cond->getOperand(0)); 2269 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV); 2270 if (!AR || !AR->isAffine() || 2271 AR->getStart() != One || 2272 AR->getStepRecurrence(SE) != One) 2273 return Cond; 2274 2275 assert(AR->getLoop() == L && 2276 "Loop condition operand is an addrec in a different loop!"); 2277 2278 // Check the right operand of the select, and remember it, as it will 2279 // be used in the new comparison instruction. 2280 Value *NewRHS = nullptr; 2281 if (ICmpInst::isTrueWhenEqual(Pred)) { 2282 // Look for n+1, and grab n. 2283 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1))) 2284 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) 2285 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) 2286 NewRHS = BO->getOperand(0); 2287 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2))) 2288 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) 2289 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) 2290 NewRHS = BO->getOperand(0); 2291 if (!NewRHS) 2292 return Cond; 2293 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS) 2294 NewRHS = Sel->getOperand(1); 2295 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS) 2296 NewRHS = Sel->getOperand(2); 2297 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS)) 2298 NewRHS = SU->getValue(); 2299 else 2300 // Max doesn't match expected pattern. 2301 return Cond; 2302 2303 // Determine the new comparison opcode. It may be signed or unsigned, 2304 // and the original comparison may be either equality or inequality. 2305 if (Cond->getPredicate() == CmpInst::ICMP_EQ) 2306 Pred = CmpInst::getInversePredicate(Pred); 2307 2308 // Ok, everything looks ok to change the condition into an SLT or SGE and 2309 // delete the max calculation. 2310 ICmpInst *NewCond = 2311 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp"); 2312 2313 // Delete the max calculation instructions. 2314 Cond->replaceAllUsesWith(NewCond); 2315 CondUse->setUser(NewCond); 2316 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0)); 2317 Cond->eraseFromParent(); 2318 Sel->eraseFromParent(); 2319 if (Cmp->use_empty()) 2320 Cmp->eraseFromParent(); 2321 return NewCond; 2322 } 2323 2324 /// Change loop terminating condition to use the postinc iv when possible. 2325 void 2326 LSRInstance::OptimizeLoopTermCond() { 2327 SmallPtrSet<Instruction *, 4> PostIncs; 2328 2329 // We need a different set of heuristics for rotated and non-rotated loops. 2330 // If a loop is rotated then the latch is also the backedge, so inserting 2331 // post-inc expressions just before the latch is ideal. To reduce live ranges 2332 // it also makes sense to rewrite terminating conditions to use post-inc 2333 // expressions. 2334 // 2335 // If the loop is not rotated then the latch is not a backedge; the latch 2336 // check is done in the loop head. Adding post-inc expressions before the 2337 // latch will cause overlapping live-ranges of pre-inc and post-inc expressions 2338 // in the loop body. In this case we do *not* want to use post-inc expressions 2339 // in the latch check, and we want to insert post-inc expressions before 2340 // the backedge. 2341 BasicBlock *LatchBlock = L->getLoopLatch(); 2342 SmallVector<BasicBlock*, 8> ExitingBlocks; 2343 L->getExitingBlocks(ExitingBlocks); 2344 if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) { 2345 return LatchBlock != BB; 2346 })) { 2347 // The backedge doesn't exit the loop; treat this as a head-tested loop. 2348 IVIncInsertPos = LatchBlock->getTerminator(); 2349 return; 2350 } 2351 2352 // Otherwise treat this as a rotated loop. 2353 for (BasicBlock *ExitingBlock : ExitingBlocks) { 2354 // Get the terminating condition for the loop if possible. If we 2355 // can, we want to change it to use a post-incremented version of its 2356 // induction variable, to allow coalescing the live ranges for the IV into 2357 // one register value. 2358 2359 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 2360 if (!TermBr) 2361 continue; 2362 // FIXME: Overly conservative, termination condition could be an 'or' etc.. 2363 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition())) 2364 continue; 2365 2366 // Search IVUsesByStride to find Cond's IVUse if there is one. 2367 IVStrideUse *CondUse = nullptr; 2368 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition()); 2369 if (!FindIVUserForCond(Cond, CondUse)) 2370 continue; 2371 2372 // If the trip count is computed in terms of a max (due to ScalarEvolution 2373 // being unable to find a sufficient guard, for example), change the loop 2374 // comparison to use SLT or ULT instead of NE. 2375 // One consequence of doing this now is that it disrupts the count-down 2376 // optimization. That's not always a bad thing though, because in such 2377 // cases it may still be worthwhile to avoid a max. 2378 Cond = OptimizeMax(Cond, CondUse); 2379 2380 // If this exiting block dominates the latch block, it may also use 2381 // the post-inc value if it won't be shared with other uses. 2382 // Check for dominance. 2383 if (!DT.dominates(ExitingBlock, LatchBlock)) 2384 continue; 2385 2386 // Conservatively avoid trying to use the post-inc value in non-latch 2387 // exits if there may be pre-inc users in intervening blocks. 2388 if (LatchBlock != ExitingBlock) 2389 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) 2390 // Test if the use is reachable from the exiting block. This dominator 2391 // query is a conservative approximation of reachability. 2392 if (&*UI != CondUse && 2393 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) { 2394 // Conservatively assume there may be reuse if the quotient of their 2395 // strides could be a legal scale. 2396 const SCEV *A = IU.getStride(*CondUse, L); 2397 const SCEV *B = IU.getStride(*UI, L); 2398 if (!A || !B) continue; 2399 if (SE.getTypeSizeInBits(A->getType()) != 2400 SE.getTypeSizeInBits(B->getType())) { 2401 if (SE.getTypeSizeInBits(A->getType()) > 2402 SE.getTypeSizeInBits(B->getType())) 2403 B = SE.getSignExtendExpr(B, A->getType()); 2404 else 2405 A = SE.getSignExtendExpr(A, B->getType()); 2406 } 2407 if (const SCEVConstant *D = 2408 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) { 2409 const ConstantInt *C = D->getValue(); 2410 // Stride of one or negative one can have reuse with non-addresses. 2411 if (C->isOne() || C->isMinusOne()) 2412 goto decline_post_inc; 2413 // Avoid weird situations. 2414 if (C->getValue().getMinSignedBits() >= 64 || 2415 C->getValue().isMinSignedValue()) 2416 goto decline_post_inc; 2417 // Check for possible scaled-address reuse. 2418 MemAccessTy AccessTy = 2419 getAccessType(TTI, UI->getUser(), UI->getOperandValToReplace()); 2420 int64_t Scale = C->getSExtValue(); 2421 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, 2422 /*BaseOffset=*/0, 2423 /*HasBaseReg=*/false, Scale, 2424 AccessTy.AddrSpace)) 2425 goto decline_post_inc; 2426 Scale = -Scale; 2427 if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, 2428 /*BaseOffset=*/0, 2429 /*HasBaseReg=*/false, Scale, 2430 AccessTy.AddrSpace)) 2431 goto decline_post_inc; 2432 } 2433 } 2434 2435 LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: " 2436 << *Cond << '\n'); 2437 2438 // It's possible for the setcc instruction to be anywhere in the loop, and 2439 // possible for it to have multiple users. If it is not immediately before 2440 // the exiting block branch, move it. 2441 if (&*++BasicBlock::iterator(Cond) != TermBr) { 2442 if (Cond->hasOneUse()) { 2443 Cond->moveBefore(TermBr); 2444 } else { 2445 // Clone the terminating condition and insert into the loopend. 2446 ICmpInst *OldCond = Cond; 2447 Cond = cast<ICmpInst>(Cond->clone()); 2448 Cond->setName(L->getHeader()->getName() + ".termcond"); 2449 ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond); 2450 2451 // Clone the IVUse, as the old use still exists! 2452 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace()); 2453 TermBr->replaceUsesOfWith(OldCond, Cond); 2454 } 2455 } 2456 2457 // If we get to here, we know that we can transform the setcc instruction to 2458 // use the post-incremented version of the IV, allowing us to coalesce the 2459 // live ranges for the IV correctly. 2460 CondUse->transformToPostInc(L); 2461 Changed = true; 2462 2463 PostIncs.insert(Cond); 2464 decline_post_inc:; 2465 } 2466 2467 // Determine an insertion point for the loop induction variable increment. It 2468 // must dominate all the post-inc comparisons we just set up, and it must 2469 // dominate the loop latch edge. 2470 IVIncInsertPos = L->getLoopLatch()->getTerminator(); 2471 for (Instruction *Inst : PostIncs) { 2472 BasicBlock *BB = 2473 DT.findNearestCommonDominator(IVIncInsertPos->getParent(), 2474 Inst->getParent()); 2475 if (BB == Inst->getParent()) 2476 IVIncInsertPos = Inst; 2477 else if (BB != IVIncInsertPos->getParent()) 2478 IVIncInsertPos = BB->getTerminator(); 2479 } 2480 } 2481 2482 /// Determine if the given use can accommodate a fixup at the given offset and 2483 /// other details. If so, update the use and return true. 2484 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, 2485 bool HasBaseReg, LSRUse::KindType Kind, 2486 MemAccessTy AccessTy) { 2487 int64_t NewMinOffset = LU.MinOffset; 2488 int64_t NewMaxOffset = LU.MaxOffset; 2489 MemAccessTy NewAccessTy = AccessTy; 2490 2491 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to 2492 // something conservative, however this can pessimize in the case that one of 2493 // the uses will have all its uses outside the loop, for example. 2494 if (LU.Kind != Kind) 2495 return false; 2496 2497 // Check for a mismatched access type, and fall back conservatively as needed. 2498 // TODO: Be less conservative when the type is similar and can use the same 2499 // addressing modes. 2500 if (Kind == LSRUse::Address) { 2501 if (AccessTy.MemTy != LU.AccessTy.MemTy) { 2502 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(), 2503 AccessTy.AddrSpace); 2504 } 2505 } 2506 2507 // Conservatively assume HasBaseReg is true for now. 2508 if (NewOffset < LU.MinOffset) { 2509 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, 2510 LU.MaxOffset - NewOffset, HasBaseReg)) 2511 return false; 2512 NewMinOffset = NewOffset; 2513 } else if (NewOffset > LU.MaxOffset) { 2514 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, 2515 NewOffset - LU.MinOffset, HasBaseReg)) 2516 return false; 2517 NewMaxOffset = NewOffset; 2518 } 2519 2520 // Update the use. 2521 LU.MinOffset = NewMinOffset; 2522 LU.MaxOffset = NewMaxOffset; 2523 LU.AccessTy = NewAccessTy; 2524 return true; 2525 } 2526 2527 /// Return an LSRUse index and an offset value for a fixup which needs the given 2528 /// expression, with the given kind and optional access type. Either reuse an 2529 /// existing use or create a new one, as needed. 2530 std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr, 2531 LSRUse::KindType Kind, 2532 MemAccessTy AccessTy) { 2533 const SCEV *Copy = Expr; 2534 int64_t Offset = ExtractImmediate(Expr, SE); 2535 2536 // Basic uses can't accept any offset, for example. 2537 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr, 2538 Offset, /*HasBaseReg=*/ true)) { 2539 Expr = Copy; 2540 Offset = 0; 2541 } 2542 2543 std::pair<UseMapTy::iterator, bool> P = 2544 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0)); 2545 if (!P.second) { 2546 // A use already existed with this base. 2547 size_t LUIdx = P.first->second; 2548 LSRUse &LU = Uses[LUIdx]; 2549 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy)) 2550 // Reuse this use. 2551 return std::make_pair(LUIdx, Offset); 2552 } 2553 2554 // Create a new use. 2555 size_t LUIdx = Uses.size(); 2556 P.first->second = LUIdx; 2557 Uses.push_back(LSRUse(Kind, AccessTy)); 2558 LSRUse &LU = Uses[LUIdx]; 2559 2560 LU.MinOffset = Offset; 2561 LU.MaxOffset = Offset; 2562 return std::make_pair(LUIdx, Offset); 2563 } 2564 2565 /// Delete the given use from the Uses list. 2566 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) { 2567 if (&LU != &Uses.back()) 2568 std::swap(LU, Uses.back()); 2569 Uses.pop_back(); 2570 2571 // Update RegUses. 2572 RegUses.swapAndDropUse(LUIdx, Uses.size()); 2573 } 2574 2575 /// Look for a use distinct from OrigLU which is has a formula that has the same 2576 /// registers as the given formula. 2577 LSRUse * 2578 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF, 2579 const LSRUse &OrigLU) { 2580 // Search all uses for the formula. This could be more clever. 2581 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 2582 LSRUse &LU = Uses[LUIdx]; 2583 // Check whether this use is close enough to OrigLU, to see whether it's 2584 // worthwhile looking through its formulae. 2585 // Ignore ICmpZero uses because they may contain formulae generated by 2586 // GenerateICmpZeroScales, in which case adding fixup offsets may 2587 // be invalid. 2588 if (&LU != &OrigLU && 2589 LU.Kind != LSRUse::ICmpZero && 2590 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy && 2591 LU.WidestFixupType == OrigLU.WidestFixupType && 2592 LU.HasFormulaWithSameRegs(OrigF)) { 2593 // Scan through this use's formulae. 2594 for (const Formula &F : LU.Formulae) { 2595 // Check to see if this formula has the same registers and symbols 2596 // as OrigF. 2597 if (F.BaseRegs == OrigF.BaseRegs && 2598 F.ScaledReg == OrigF.ScaledReg && 2599 F.BaseGV == OrigF.BaseGV && 2600 F.Scale == OrigF.Scale && 2601 F.UnfoldedOffset == OrigF.UnfoldedOffset) { 2602 if (F.BaseOffset == 0) 2603 return &LU; 2604 // This is the formula where all the registers and symbols matched; 2605 // there aren't going to be any others. Since we declined it, we 2606 // can skip the rest of the formulae and proceed to the next LSRUse. 2607 break; 2608 } 2609 } 2610 } 2611 } 2612 2613 // Nothing looked good. 2614 return nullptr; 2615 } 2616 2617 void LSRInstance::CollectInterestingTypesAndFactors() { 2618 SmallSetVector<const SCEV *, 4> Strides; 2619 2620 // Collect interesting types and strides. 2621 SmallVector<const SCEV *, 4> Worklist; 2622 for (const IVStrideUse &U : IU) { 2623 const SCEV *Expr = IU.getExpr(U); 2624 2625 // Collect interesting types. 2626 Types.insert(SE.getEffectiveSCEVType(Expr->getType())); 2627 2628 // Add strides for mentioned loops. 2629 Worklist.push_back(Expr); 2630 do { 2631 const SCEV *S = Worklist.pop_back_val(); 2632 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 2633 if (AR->getLoop() == L) 2634 Strides.insert(AR->getStepRecurrence(SE)); 2635 Worklist.push_back(AR->getStart()); 2636 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 2637 Worklist.append(Add->op_begin(), Add->op_end()); 2638 } 2639 } while (!Worklist.empty()); 2640 } 2641 2642 // Compute interesting factors from the set of interesting strides. 2643 for (SmallSetVector<const SCEV *, 4>::const_iterator 2644 I = Strides.begin(), E = Strides.end(); I != E; ++I) 2645 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter = 2646 std::next(I); NewStrideIter != E; ++NewStrideIter) { 2647 const SCEV *OldStride = *I; 2648 const SCEV *NewStride = *NewStrideIter; 2649 2650 if (SE.getTypeSizeInBits(OldStride->getType()) != 2651 SE.getTypeSizeInBits(NewStride->getType())) { 2652 if (SE.getTypeSizeInBits(OldStride->getType()) > 2653 SE.getTypeSizeInBits(NewStride->getType())) 2654 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType()); 2655 else 2656 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType()); 2657 } 2658 if (const SCEVConstant *Factor = 2659 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride, 2660 SE, true))) { 2661 if (Factor->getAPInt().getMinSignedBits() <= 64) 2662 Factors.insert(Factor->getAPInt().getSExtValue()); 2663 } else if (const SCEVConstant *Factor = 2664 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride, 2665 NewStride, 2666 SE, true))) { 2667 if (Factor->getAPInt().getMinSignedBits() <= 64) 2668 Factors.insert(Factor->getAPInt().getSExtValue()); 2669 } 2670 } 2671 2672 // If all uses use the same type, don't bother looking for truncation-based 2673 // reuse. 2674 if (Types.size() == 1) 2675 Types.clear(); 2676 2677 LLVM_DEBUG(print_factors_and_types(dbgs())); 2678 } 2679 2680 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in 2681 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to 2682 /// IVStrideUses, we could partially skip this. 2683 static User::op_iterator 2684 findIVOperand(User::op_iterator OI, User::op_iterator OE, 2685 Loop *L, ScalarEvolution &SE) { 2686 for(; OI != OE; ++OI) { 2687 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) { 2688 if (!SE.isSCEVable(Oper->getType())) 2689 continue; 2690 2691 if (const SCEVAddRecExpr *AR = 2692 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) { 2693 if (AR->getLoop() == L) 2694 break; 2695 } 2696 } 2697 } 2698 return OI; 2699 } 2700 2701 /// IVChain logic must consistenctly peek base TruncInst operands, so wrap it in 2702 /// a convenient helper. 2703 static Value *getWideOperand(Value *Oper) { 2704 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper)) 2705 return Trunc->getOperand(0); 2706 return Oper; 2707 } 2708 2709 /// Return true if we allow an IV chain to include both types. 2710 static bool isCompatibleIVType(Value *LVal, Value *RVal) { 2711 Type *LType = LVal->getType(); 2712 Type *RType = RVal->getType(); 2713 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() && 2714 // Different address spaces means (possibly) 2715 // different types of the pointer implementation, 2716 // e.g. i16 vs i32 so disallow that. 2717 (LType->getPointerAddressSpace() == 2718 RType->getPointerAddressSpace())); 2719 } 2720 2721 /// Return an approximation of this SCEV expression's "base", or NULL for any 2722 /// constant. Returning the expression itself is conservative. Returning a 2723 /// deeper subexpression is more precise and valid as long as it isn't less 2724 /// complex than another subexpression. For expressions involving multiple 2725 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids 2726 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i], 2727 /// IVInc==b-a. 2728 /// 2729 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost 2730 /// SCEVUnknown, we simply return the rightmost SCEV operand. 2731 static const SCEV *getExprBase(const SCEV *S) { 2732 switch (S->getSCEVType()) { 2733 default: // uncluding scUnknown. 2734 return S; 2735 case scConstant: 2736 return nullptr; 2737 case scTruncate: 2738 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand()); 2739 case scZeroExtend: 2740 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand()); 2741 case scSignExtend: 2742 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand()); 2743 case scAddExpr: { 2744 // Skip over scaled operands (scMulExpr) to follow add operands as long as 2745 // there's nothing more complex. 2746 // FIXME: not sure if we want to recognize negation. 2747 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S); 2748 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()), 2749 E(Add->op_begin()); I != E; ++I) { 2750 const SCEV *SubExpr = *I; 2751 if (SubExpr->getSCEVType() == scAddExpr) 2752 return getExprBase(SubExpr); 2753 2754 if (SubExpr->getSCEVType() != scMulExpr) 2755 return SubExpr; 2756 } 2757 return S; // all operands are scaled, be conservative. 2758 } 2759 case scAddRecExpr: 2760 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart()); 2761 } 2762 } 2763 2764 /// Return true if the chain increment is profitable to expand into a loop 2765 /// invariant value, which may require its own register. A profitable chain 2766 /// increment will be an offset relative to the same base. We allow such offsets 2767 /// to potentially be used as chain increment as long as it's not obviously 2768 /// expensive to expand using real instructions. 2769 bool IVChain::isProfitableIncrement(const SCEV *OperExpr, 2770 const SCEV *IncExpr, 2771 ScalarEvolution &SE) { 2772 // Aggressively form chains when -stress-ivchain. 2773 if (StressIVChain) 2774 return true; 2775 2776 // Do not replace a constant offset from IV head with a nonconstant IV 2777 // increment. 2778 if (!isa<SCEVConstant>(IncExpr)) { 2779 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand)); 2780 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr))) 2781 return false; 2782 } 2783 2784 SmallPtrSet<const SCEV*, 8> Processed; 2785 return !isHighCostExpansion(IncExpr, Processed, SE); 2786 } 2787 2788 /// Return true if the number of registers needed for the chain is estimated to 2789 /// be less than the number required for the individual IV users. First prohibit 2790 /// any IV users that keep the IV live across increments (the Users set should 2791 /// be empty). Next count the number and type of increments in the chain. 2792 /// 2793 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't 2794 /// effectively use postinc addressing modes. Only consider it profitable it the 2795 /// increments can be computed in fewer registers when chained. 2796 /// 2797 /// TODO: Consider IVInc free if it's already used in another chains. 2798 static bool 2799 isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users, 2800 ScalarEvolution &SE, const TargetTransformInfo &TTI) { 2801 if (StressIVChain) 2802 return true; 2803 2804 if (!Chain.hasIncs()) 2805 return false; 2806 2807 if (!Users.empty()) { 2808 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n"; 2809 for (Instruction *Inst 2810 : Users) { dbgs() << " " << *Inst << "\n"; }); 2811 return false; 2812 } 2813 assert(!Chain.Incs.empty() && "empty IV chains are not allowed"); 2814 2815 // The chain itself may require a register, so intialize cost to 1. 2816 int cost = 1; 2817 2818 // A complete chain likely eliminates the need for keeping the original IV in 2819 // a register. LSR does not currently know how to form a complete chain unless 2820 // the header phi already exists. 2821 if (isa<PHINode>(Chain.tailUserInst()) 2822 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) { 2823 --cost; 2824 } 2825 const SCEV *LastIncExpr = nullptr; 2826 unsigned NumConstIncrements = 0; 2827 unsigned NumVarIncrements = 0; 2828 unsigned NumReusedIncrements = 0; 2829 for (const IVInc &Inc : Chain) { 2830 if (Inc.IncExpr->isZero()) 2831 continue; 2832 2833 // Incrementing by zero or some constant is neutral. We assume constants can 2834 // be folded into an addressing mode or an add's immediate operand. 2835 if (isa<SCEVConstant>(Inc.IncExpr)) { 2836 ++NumConstIncrements; 2837 continue; 2838 } 2839 2840 if (Inc.IncExpr == LastIncExpr) 2841 ++NumReusedIncrements; 2842 else 2843 ++NumVarIncrements; 2844 2845 LastIncExpr = Inc.IncExpr; 2846 } 2847 // An IV chain with a single increment is handled by LSR's postinc 2848 // uses. However, a chain with multiple increments requires keeping the IV's 2849 // value live longer than it needs to be if chained. 2850 if (NumConstIncrements > 1) 2851 --cost; 2852 2853 // Materializing increment expressions in the preheader that didn't exist in 2854 // the original code may cost a register. For example, sign-extended array 2855 // indices can produce ridiculous increments like this: 2856 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64))) 2857 cost += NumVarIncrements; 2858 2859 // Reusing variable increments likely saves a register to hold the multiple of 2860 // the stride. 2861 cost -= NumReusedIncrements; 2862 2863 LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost 2864 << "\n"); 2865 2866 return cost < 0; 2867 } 2868 2869 /// Add this IV user to an existing chain or make it the head of a new chain. 2870 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper, 2871 SmallVectorImpl<ChainUsers> &ChainUsersVec) { 2872 // When IVs are used as types of varying widths, they are generally converted 2873 // to a wider type with some uses remaining narrow under a (free) trunc. 2874 Value *const NextIV = getWideOperand(IVOper); 2875 const SCEV *const OperExpr = SE.getSCEV(NextIV); 2876 const SCEV *const OperExprBase = getExprBase(OperExpr); 2877 2878 // Visit all existing chains. Check if its IVOper can be computed as a 2879 // profitable loop invariant increment from the last link in the Chain. 2880 unsigned ChainIdx = 0, NChains = IVChainVec.size(); 2881 const SCEV *LastIncExpr = nullptr; 2882 for (; ChainIdx < NChains; ++ChainIdx) { 2883 IVChain &Chain = IVChainVec[ChainIdx]; 2884 2885 // Prune the solution space aggressively by checking that both IV operands 2886 // are expressions that operate on the same unscaled SCEVUnknown. This 2887 // "base" will be canceled by the subsequent getMinusSCEV call. Checking 2888 // first avoids creating extra SCEV expressions. 2889 if (!StressIVChain && Chain.ExprBase != OperExprBase) 2890 continue; 2891 2892 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand); 2893 if (!isCompatibleIVType(PrevIV, NextIV)) 2894 continue; 2895 2896 // A phi node terminates a chain. 2897 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst())) 2898 continue; 2899 2900 // The increment must be loop-invariant so it can be kept in a register. 2901 const SCEV *PrevExpr = SE.getSCEV(PrevIV); 2902 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr); 2903 if (!SE.isLoopInvariant(IncExpr, L)) 2904 continue; 2905 2906 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) { 2907 LastIncExpr = IncExpr; 2908 break; 2909 } 2910 } 2911 // If we haven't found a chain, create a new one, unless we hit the max. Don't 2912 // bother for phi nodes, because they must be last in the chain. 2913 if (ChainIdx == NChains) { 2914 if (isa<PHINode>(UserInst)) 2915 return; 2916 if (NChains >= MaxChains && !StressIVChain) { 2917 LLVM_DEBUG(dbgs() << "IV Chain Limit\n"); 2918 return; 2919 } 2920 LastIncExpr = OperExpr; 2921 // IVUsers may have skipped over sign/zero extensions. We don't currently 2922 // attempt to form chains involving extensions unless they can be hoisted 2923 // into this loop's AddRec. 2924 if (!isa<SCEVAddRecExpr>(LastIncExpr)) 2925 return; 2926 ++NChains; 2927 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr), 2928 OperExprBase)); 2929 ChainUsersVec.resize(NChains); 2930 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst 2931 << ") IV=" << *LastIncExpr << "\n"); 2932 } else { 2933 LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst 2934 << ") IV+" << *LastIncExpr << "\n"); 2935 // Add this IV user to the end of the chain. 2936 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr)); 2937 } 2938 IVChain &Chain = IVChainVec[ChainIdx]; 2939 2940 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers; 2941 // This chain's NearUsers become FarUsers. 2942 if (!LastIncExpr->isZero()) { 2943 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(), 2944 NearUsers.end()); 2945 NearUsers.clear(); 2946 } 2947 2948 // All other uses of IVOperand become near uses of the chain. 2949 // We currently ignore intermediate values within SCEV expressions, assuming 2950 // they will eventually be used be the current chain, or can be computed 2951 // from one of the chain increments. To be more precise we could 2952 // transitively follow its user and only add leaf IV users to the set. 2953 for (User *U : IVOper->users()) { 2954 Instruction *OtherUse = dyn_cast<Instruction>(U); 2955 if (!OtherUse) 2956 continue; 2957 // Uses in the chain will no longer be uses if the chain is formed. 2958 // Include the head of the chain in this iteration (not Chain.begin()). 2959 IVChain::const_iterator IncIter = Chain.Incs.begin(); 2960 IVChain::const_iterator IncEnd = Chain.Incs.end(); 2961 for( ; IncIter != IncEnd; ++IncIter) { 2962 if (IncIter->UserInst == OtherUse) 2963 break; 2964 } 2965 if (IncIter != IncEnd) 2966 continue; 2967 2968 if (SE.isSCEVable(OtherUse->getType()) 2969 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse)) 2970 && IU.isIVUserOrOperand(OtherUse)) { 2971 continue; 2972 } 2973 NearUsers.insert(OtherUse); 2974 } 2975 2976 // Since this user is part of the chain, it's no longer considered a use 2977 // of the chain. 2978 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst); 2979 } 2980 2981 /// Populate the vector of Chains. 2982 /// 2983 /// This decreases ILP at the architecture level. Targets with ample registers, 2984 /// multiple memory ports, and no register renaming probably don't want 2985 /// this. However, such targets should probably disable LSR altogether. 2986 /// 2987 /// The job of LSR is to make a reasonable choice of induction variables across 2988 /// the loop. Subsequent passes can easily "unchain" computation exposing more 2989 /// ILP *within the loop* if the target wants it. 2990 /// 2991 /// Finding the best IV chain is potentially a scheduling problem. Since LSR 2992 /// will not reorder memory operations, it will recognize this as a chain, but 2993 /// will generate redundant IV increments. Ideally this would be corrected later 2994 /// by a smart scheduler: 2995 /// = A[i] 2996 /// = A[i+x] 2997 /// A[i] = 2998 /// A[i+x] = 2999 /// 3000 /// TODO: Walk the entire domtree within this loop, not just the path to the 3001 /// loop latch. This will discover chains on side paths, but requires 3002 /// maintaining multiple copies of the Chains state. 3003 void LSRInstance::CollectChains() { 3004 LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n"); 3005 SmallVector<ChainUsers, 8> ChainUsersVec; 3006 3007 SmallVector<BasicBlock *,8> LatchPath; 3008 BasicBlock *LoopHeader = L->getHeader(); 3009 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch()); 3010 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) { 3011 LatchPath.push_back(Rung->getBlock()); 3012 } 3013 LatchPath.push_back(LoopHeader); 3014 3015 // Walk the instruction stream from the loop header to the loop latch. 3016 for (BasicBlock *BB : reverse(LatchPath)) { 3017 for (Instruction &I : *BB) { 3018 // Skip instructions that weren't seen by IVUsers analysis. 3019 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I)) 3020 continue; 3021 3022 // Ignore users that are part of a SCEV expression. This way we only 3023 // consider leaf IV Users. This effectively rediscovers a portion of 3024 // IVUsers analysis but in program order this time. 3025 if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I))) 3026 continue; 3027 3028 // Remove this instruction from any NearUsers set it may be in. 3029 for (unsigned ChainIdx = 0, NChains = IVChainVec.size(); 3030 ChainIdx < NChains; ++ChainIdx) { 3031 ChainUsersVec[ChainIdx].NearUsers.erase(&I); 3032 } 3033 // Search for operands that can be chained. 3034 SmallPtrSet<Instruction*, 4> UniqueOperands; 3035 User::op_iterator IVOpEnd = I.op_end(); 3036 User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE); 3037 while (IVOpIter != IVOpEnd) { 3038 Instruction *IVOpInst = cast<Instruction>(*IVOpIter); 3039 if (UniqueOperands.insert(IVOpInst).second) 3040 ChainInstruction(&I, IVOpInst, ChainUsersVec); 3041 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); 3042 } 3043 } // Continue walking down the instructions. 3044 } // Continue walking down the domtree. 3045 // Visit phi backedges to determine if the chain can generate the IV postinc. 3046 for (PHINode &PN : L->getHeader()->phis()) { 3047 if (!SE.isSCEVable(PN.getType())) 3048 continue; 3049 3050 Instruction *IncV = 3051 dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch())); 3052 if (IncV) 3053 ChainInstruction(&PN, IncV, ChainUsersVec); 3054 } 3055 // Remove any unprofitable chains. 3056 unsigned ChainIdx = 0; 3057 for (unsigned UsersIdx = 0, NChains = IVChainVec.size(); 3058 UsersIdx < NChains; ++UsersIdx) { 3059 if (!isProfitableChain(IVChainVec[UsersIdx], 3060 ChainUsersVec[UsersIdx].FarUsers, SE, TTI)) 3061 continue; 3062 // Preserve the chain at UsesIdx. 3063 if (ChainIdx != UsersIdx) 3064 IVChainVec[ChainIdx] = IVChainVec[UsersIdx]; 3065 FinalizeChain(IVChainVec[ChainIdx]); 3066 ++ChainIdx; 3067 } 3068 IVChainVec.resize(ChainIdx); 3069 } 3070 3071 void LSRInstance::FinalizeChain(IVChain &Chain) { 3072 assert(!Chain.Incs.empty() && "empty IV chains are not allowed"); 3073 LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n"); 3074 3075 for (const IVInc &Inc : Chain) { 3076 LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n"); 3077 auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand); 3078 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand"); 3079 IVIncSet.insert(UseI); 3080 } 3081 } 3082 3083 /// Return true if the IVInc can be folded into an addressing mode. 3084 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst, 3085 Value *Operand, const TargetTransformInfo &TTI) { 3086 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr); 3087 if (!IncConst || !isAddressUse(TTI, UserInst, Operand)) 3088 return false; 3089 3090 if (IncConst->getAPInt().getMinSignedBits() > 64) 3091 return false; 3092 3093 MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand); 3094 int64_t IncOffset = IncConst->getValue()->getSExtValue(); 3095 if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr, 3096 IncOffset, /*HaseBaseReg=*/false)) 3097 return false; 3098 3099 return true; 3100 } 3101 3102 /// Generate an add or subtract for each IVInc in a chain to materialize the IV 3103 /// user's operand from the previous IV user's operand. 3104 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter, 3105 SmallVectorImpl<WeakTrackingVH> &DeadInsts) { 3106 // Find the new IVOperand for the head of the chain. It may have been replaced 3107 // by LSR. 3108 const IVInc &Head = Chain.Incs[0]; 3109 User::op_iterator IVOpEnd = Head.UserInst->op_end(); 3110 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user. 3111 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(), 3112 IVOpEnd, L, SE); 3113 Value *IVSrc = nullptr; 3114 while (IVOpIter != IVOpEnd) { 3115 IVSrc = getWideOperand(*IVOpIter); 3116 3117 // If this operand computes the expression that the chain needs, we may use 3118 // it. (Check this after setting IVSrc which is used below.) 3119 // 3120 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too 3121 // narrow for the chain, so we can no longer use it. We do allow using a 3122 // wider phi, assuming the LSR checked for free truncation. In that case we 3123 // should already have a truncate on this operand such that 3124 // getSCEV(IVSrc) == IncExpr. 3125 if (SE.getSCEV(*IVOpIter) == Head.IncExpr 3126 || SE.getSCEV(IVSrc) == Head.IncExpr) { 3127 break; 3128 } 3129 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); 3130 } 3131 if (IVOpIter == IVOpEnd) { 3132 // Gracefully give up on this chain. 3133 LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n"); 3134 return; 3135 } 3136 3137 LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n"); 3138 Type *IVTy = IVSrc->getType(); 3139 Type *IntTy = SE.getEffectiveSCEVType(IVTy); 3140 const SCEV *LeftOverExpr = nullptr; 3141 for (const IVInc &Inc : Chain) { 3142 Instruction *InsertPt = Inc.UserInst; 3143 if (isa<PHINode>(InsertPt)) 3144 InsertPt = L->getLoopLatch()->getTerminator(); 3145 3146 // IVOper will replace the current IV User's operand. IVSrc is the IV 3147 // value currently held in a register. 3148 Value *IVOper = IVSrc; 3149 if (!Inc.IncExpr->isZero()) { 3150 // IncExpr was the result of subtraction of two narrow values, so must 3151 // be signed. 3152 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy); 3153 LeftOverExpr = LeftOverExpr ? 3154 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr; 3155 } 3156 if (LeftOverExpr && !LeftOverExpr->isZero()) { 3157 // Expand the IV increment. 3158 Rewriter.clearPostInc(); 3159 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt); 3160 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc), 3161 SE.getUnknown(IncV)); 3162 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt); 3163 3164 // If an IV increment can't be folded, use it as the next IV value. 3165 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) { 3166 assert(IVTy == IVOper->getType() && "inconsistent IV increment type"); 3167 IVSrc = IVOper; 3168 LeftOverExpr = nullptr; 3169 } 3170 } 3171 Type *OperTy = Inc.IVOperand->getType(); 3172 if (IVTy != OperTy) { 3173 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) && 3174 "cannot extend a chained IV"); 3175 IRBuilder<> Builder(InsertPt); 3176 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain"); 3177 } 3178 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper); 3179 DeadInsts.emplace_back(Inc.IVOperand); 3180 } 3181 // If LSR created a new, wider phi, we may also replace its postinc. We only 3182 // do this if we also found a wide value for the head of the chain. 3183 if (isa<PHINode>(Chain.tailUserInst())) { 3184 for (PHINode &Phi : L->getHeader()->phis()) { 3185 if (!isCompatibleIVType(&Phi, IVSrc)) 3186 continue; 3187 Instruction *PostIncV = dyn_cast<Instruction>( 3188 Phi.getIncomingValueForBlock(L->getLoopLatch())); 3189 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc))) 3190 continue; 3191 Value *IVOper = IVSrc; 3192 Type *PostIncTy = PostIncV->getType(); 3193 if (IVTy != PostIncTy) { 3194 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types"); 3195 IRBuilder<> Builder(L->getLoopLatch()->getTerminator()); 3196 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc()); 3197 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain"); 3198 } 3199 Phi.replaceUsesOfWith(PostIncV, IVOper); 3200 DeadInsts.emplace_back(PostIncV); 3201 } 3202 } 3203 } 3204 3205 void LSRInstance::CollectFixupsAndInitialFormulae() { 3206 for (const IVStrideUse &U : IU) { 3207 Instruction *UserInst = U.getUser(); 3208 // Skip IV users that are part of profitable IV Chains. 3209 User::op_iterator UseI = 3210 find(UserInst->operands(), U.getOperandValToReplace()); 3211 assert(UseI != UserInst->op_end() && "cannot find IV operand"); 3212 if (IVIncSet.count(UseI)) { 3213 LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n'); 3214 continue; 3215 } 3216 3217 LSRUse::KindType Kind = LSRUse::Basic; 3218 MemAccessTy AccessTy; 3219 if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) { 3220 Kind = LSRUse::Address; 3221 AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace()); 3222 } 3223 3224 const SCEV *S = IU.getExpr(U); 3225 PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops(); 3226 3227 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as 3228 // (N - i == 0), and this allows (N - i) to be the expression that we work 3229 // with rather than just N or i, so we can consider the register 3230 // requirements for both N and i at the same time. Limiting this code to 3231 // equality icmps is not a problem because all interesting loops use 3232 // equality icmps, thanks to IndVarSimplify. 3233 if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) 3234 if (CI->isEquality()) { 3235 // Swap the operands if needed to put the OperandValToReplace on the 3236 // left, for consistency. 3237 Value *NV = CI->getOperand(1); 3238 if (NV == U.getOperandValToReplace()) { 3239 CI->setOperand(1, CI->getOperand(0)); 3240 CI->setOperand(0, NV); 3241 NV = CI->getOperand(1); 3242 Changed = true; 3243 } 3244 3245 // x == y --> x - y == 0 3246 const SCEV *N = SE.getSCEV(NV); 3247 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) { 3248 // S is normalized, so normalize N before folding it into S 3249 // to keep the result normalized. 3250 N = normalizeForPostIncUse(N, TmpPostIncLoops, SE); 3251 Kind = LSRUse::ICmpZero; 3252 S = SE.getMinusSCEV(N, S); 3253 } 3254 3255 // -1 and the negations of all interesting strides (except the negation 3256 // of -1) are now also interesting. 3257 for (size_t i = 0, e = Factors.size(); i != e; ++i) 3258 if (Factors[i] != -1) 3259 Factors.insert(-(uint64_t)Factors[i]); 3260 Factors.insert(-1); 3261 } 3262 3263 // Get or create an LSRUse. 3264 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy); 3265 size_t LUIdx = P.first; 3266 int64_t Offset = P.second; 3267 LSRUse &LU = Uses[LUIdx]; 3268 3269 // Record the fixup. 3270 LSRFixup &LF = LU.getNewFixup(); 3271 LF.UserInst = UserInst; 3272 LF.OperandValToReplace = U.getOperandValToReplace(); 3273 LF.PostIncLoops = TmpPostIncLoops; 3274 LF.Offset = Offset; 3275 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); 3276 3277 if (!LU.WidestFixupType || 3278 SE.getTypeSizeInBits(LU.WidestFixupType) < 3279 SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) 3280 LU.WidestFixupType = LF.OperandValToReplace->getType(); 3281 3282 // If this is the first use of this LSRUse, give it a formula. 3283 if (LU.Formulae.empty()) { 3284 InsertInitialFormula(S, LU, LUIdx); 3285 CountRegisters(LU.Formulae.back(), LUIdx); 3286 } 3287 } 3288 3289 LLVM_DEBUG(print_fixups(dbgs())); 3290 } 3291 3292 /// Insert a formula for the given expression into the given use, separating out 3293 /// loop-variant portions from loop-invariant and loop-computable portions. 3294 void 3295 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) { 3296 // Mark uses whose expressions cannot be expanded. 3297 if (!isSafeToExpand(S, SE)) 3298 LU.RigidFormula = true; 3299 3300 Formula F; 3301 F.initialMatch(S, L, SE); 3302 bool Inserted = InsertFormula(LU, LUIdx, F); 3303 assert(Inserted && "Initial formula already exists!"); (void)Inserted; 3304 } 3305 3306 /// Insert a simple single-register formula for the given expression into the 3307 /// given use. 3308 void 3309 LSRInstance::InsertSupplementalFormula(const SCEV *S, 3310 LSRUse &LU, size_t LUIdx) { 3311 Formula F; 3312 F.BaseRegs.push_back(S); 3313 F.HasBaseReg = true; 3314 bool Inserted = InsertFormula(LU, LUIdx, F); 3315 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted; 3316 } 3317 3318 /// Note which registers are used by the given formula, updating RegUses. 3319 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) { 3320 if (F.ScaledReg) 3321 RegUses.countRegister(F.ScaledReg, LUIdx); 3322 for (const SCEV *BaseReg : F.BaseRegs) 3323 RegUses.countRegister(BaseReg, LUIdx); 3324 } 3325 3326 /// If the given formula has not yet been inserted, add it to the list, and 3327 /// return true. Return false otherwise. 3328 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) { 3329 // Do not insert formula that we will not be able to expand. 3330 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) && 3331 "Formula is illegal"); 3332 3333 if (!LU.InsertFormula(F, *L)) 3334 return false; 3335 3336 CountRegisters(F, LUIdx); 3337 return true; 3338 } 3339 3340 /// Check for other uses of loop-invariant values which we're tracking. These 3341 /// other uses will pin these values in registers, making them less profitable 3342 /// for elimination. 3343 /// TODO: This currently misses non-constant addrec step registers. 3344 /// TODO: Should this give more weight to users inside the loop? 3345 void 3346 LSRInstance::CollectLoopInvariantFixupsAndFormulae() { 3347 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end()); 3348 SmallPtrSet<const SCEV *, 32> Visited; 3349 3350 while (!Worklist.empty()) { 3351 const SCEV *S = Worklist.pop_back_val(); 3352 3353 // Don't process the same SCEV twice 3354 if (!Visited.insert(S).second) 3355 continue; 3356 3357 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) 3358 Worklist.append(N->op_begin(), N->op_end()); 3359 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) 3360 Worklist.push_back(C->getOperand()); 3361 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { 3362 Worklist.push_back(D->getLHS()); 3363 Worklist.push_back(D->getRHS()); 3364 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) { 3365 const Value *V = US->getValue(); 3366 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 3367 // Look for instructions defined outside the loop. 3368 if (L->contains(Inst)) continue; 3369 } else if (isa<UndefValue>(V)) 3370 // Undef doesn't have a live range, so it doesn't matter. 3371 continue; 3372 for (const Use &U : V->uses()) { 3373 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser()); 3374 // Ignore non-instructions. 3375 if (!UserInst) 3376 continue; 3377 // Ignore instructions in other functions (as can happen with 3378 // Constants). 3379 if (UserInst->getParent()->getParent() != L->getHeader()->getParent()) 3380 continue; 3381 // Ignore instructions not dominated by the loop. 3382 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ? 3383 UserInst->getParent() : 3384 cast<PHINode>(UserInst)->getIncomingBlock( 3385 PHINode::getIncomingValueNumForOperand(U.getOperandNo())); 3386 if (!DT.dominates(L->getHeader(), UseBB)) 3387 continue; 3388 // Don't bother if the instruction is in a BB which ends in an EHPad. 3389 if (UseBB->getTerminator()->isEHPad()) 3390 continue; 3391 // Don't bother rewriting PHIs in catchswitch blocks. 3392 if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator())) 3393 continue; 3394 // Ignore uses which are part of other SCEV expressions, to avoid 3395 // analyzing them multiple times. 3396 if (SE.isSCEVable(UserInst->getType())) { 3397 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst)); 3398 // If the user is a no-op, look through to its uses. 3399 if (!isa<SCEVUnknown>(UserS)) 3400 continue; 3401 if (UserS == US) { 3402 Worklist.push_back( 3403 SE.getUnknown(const_cast<Instruction *>(UserInst))); 3404 continue; 3405 } 3406 } 3407 // Ignore icmp instructions which are already being analyzed. 3408 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) { 3409 unsigned OtherIdx = !U.getOperandNo(); 3410 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx)); 3411 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L)) 3412 continue; 3413 } 3414 3415 std::pair<size_t, int64_t> P = getUse( 3416 S, LSRUse::Basic, MemAccessTy()); 3417 size_t LUIdx = P.first; 3418 int64_t Offset = P.second; 3419 LSRUse &LU = Uses[LUIdx]; 3420 LSRFixup &LF = LU.getNewFixup(); 3421 LF.UserInst = const_cast<Instruction *>(UserInst); 3422 LF.OperandValToReplace = U; 3423 LF.Offset = Offset; 3424 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); 3425 if (!LU.WidestFixupType || 3426 SE.getTypeSizeInBits(LU.WidestFixupType) < 3427 SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) 3428 LU.WidestFixupType = LF.OperandValToReplace->getType(); 3429 InsertSupplementalFormula(US, LU, LUIdx); 3430 CountRegisters(LU.Formulae.back(), Uses.size() - 1); 3431 break; 3432 } 3433 } 3434 } 3435 } 3436 3437 /// Split S into subexpressions which can be pulled out into separate 3438 /// registers. If C is non-null, multiply each subexpression by C. 3439 /// 3440 /// Return remainder expression after factoring the subexpressions captured by 3441 /// Ops. If Ops is complete, return NULL. 3442 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C, 3443 SmallVectorImpl<const SCEV *> &Ops, 3444 const Loop *L, 3445 ScalarEvolution &SE, 3446 unsigned Depth = 0) { 3447 // Arbitrarily cap recursion to protect compile time. 3448 if (Depth >= 3) 3449 return S; 3450 3451 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 3452 // Break out add operands. 3453 for (const SCEV *S : Add->operands()) { 3454 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1); 3455 if (Remainder) 3456 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); 3457 } 3458 return nullptr; 3459 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 3460 // Split a non-zero base out of an addrec. 3461 if (AR->getStart()->isZero() || !AR->isAffine()) 3462 return S; 3463 3464 const SCEV *Remainder = CollectSubexprs(AR->getStart(), 3465 C, Ops, L, SE, Depth+1); 3466 // Split the non-zero AddRec unless it is part of a nested recurrence that 3467 // does not pertain to this loop. 3468 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) { 3469 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); 3470 Remainder = nullptr; 3471 } 3472 if (Remainder != AR->getStart()) { 3473 if (!Remainder) 3474 Remainder = SE.getConstant(AR->getType(), 0); 3475 return SE.getAddRecExpr(Remainder, 3476 AR->getStepRecurrence(SE), 3477 AR->getLoop(), 3478 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW) 3479 SCEV::FlagAnyWrap); 3480 } 3481 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 3482 // Break (C * (a + b + c)) into C*a + C*b + C*c. 3483 if (Mul->getNumOperands() != 2) 3484 return S; 3485 if (const SCEVConstant *Op0 = 3486 dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3487 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0; 3488 const SCEV *Remainder = 3489 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1); 3490 if (Remainder) 3491 Ops.push_back(SE.getMulExpr(C, Remainder)); 3492 return nullptr; 3493 } 3494 } 3495 return S; 3496 } 3497 3498 /// Return true if the SCEV represents a value that may end up as a 3499 /// post-increment operation. 3500 static bool mayUsePostIncMode(const TargetTransformInfo &TTI, 3501 LSRUse &LU, const SCEV *S, const Loop *L, 3502 ScalarEvolution &SE) { 3503 if (LU.Kind != LSRUse::Address || 3504 !LU.AccessTy.getType()->isIntOrIntVectorTy()) 3505 return false; 3506 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 3507 if (!AR) 3508 return false; 3509 const SCEV *LoopStep = AR->getStepRecurrence(SE); 3510 if (!isa<SCEVConstant>(LoopStep)) 3511 return false; 3512 if (LU.AccessTy.getType()->getScalarSizeInBits() != 3513 LoopStep->getType()->getScalarSizeInBits()) 3514 return false; 3515 // Check if a post-indexed load/store can be used. 3516 if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) || 3517 TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) { 3518 const SCEV *LoopStart = AR->getStart(); 3519 if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L)) 3520 return true; 3521 } 3522 return false; 3523 } 3524 3525 /// Helper function for LSRInstance::GenerateReassociations. 3526 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, 3527 const Formula &Base, 3528 unsigned Depth, size_t Idx, 3529 bool IsScaledReg) { 3530 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3531 // Don't generate reassociations for the base register of a value that 3532 // may generate a post-increment operator. The reason is that the 3533 // reassociations cause extra base+register formula to be created, 3534 // and possibly chosen, but the post-increment is more efficient. 3535 if (TTI.shouldFavorPostInc() && mayUsePostIncMode(TTI, LU, BaseReg, L, SE)) 3536 return; 3537 SmallVector<const SCEV *, 8> AddOps; 3538 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE); 3539 if (Remainder) 3540 AddOps.push_back(Remainder); 3541 3542 if (AddOps.size() == 1) 3543 return; 3544 3545 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(), 3546 JE = AddOps.end(); 3547 J != JE; ++J) { 3548 // Loop-variant "unknown" values are uninteresting; we won't be able to 3549 // do anything meaningful with them. 3550 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L)) 3551 continue; 3552 3553 // Don't pull a constant into a register if the constant could be folded 3554 // into an immediate field. 3555 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, 3556 LU.AccessTy, *J, Base.getNumRegs() > 1)) 3557 continue; 3558 3559 // Collect all operands except *J. 3560 SmallVector<const SCEV *, 8> InnerAddOps( 3561 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J); 3562 InnerAddOps.append(std::next(J), 3563 ((const SmallVector<const SCEV *, 8> &)AddOps).end()); 3564 3565 // Don't leave just a constant behind in a register if the constant could 3566 // be folded into an immediate field. 3567 if (InnerAddOps.size() == 1 && 3568 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, 3569 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1)) 3570 continue; 3571 3572 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps); 3573 if (InnerSum->isZero()) 3574 continue; 3575 Formula F = Base; 3576 3577 // Add the remaining pieces of the add back into the new formula. 3578 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum); 3579 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 && 3580 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + 3581 InnerSumSC->getValue()->getZExtValue())) { 3582 F.UnfoldedOffset = 3583 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue(); 3584 if (IsScaledReg) 3585 F.ScaledReg = nullptr; 3586 else 3587 F.BaseRegs.erase(F.BaseRegs.begin() + Idx); 3588 } else if (IsScaledReg) 3589 F.ScaledReg = InnerSum; 3590 else 3591 F.BaseRegs[Idx] = InnerSum; 3592 3593 // Add J as its own register, or an unfolded immediate. 3594 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J); 3595 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 && 3596 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + 3597 SC->getValue()->getZExtValue())) 3598 F.UnfoldedOffset = 3599 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue(); 3600 else 3601 F.BaseRegs.push_back(*J); 3602 // We may have changed the number of register in base regs, adjust the 3603 // formula accordingly. 3604 F.canonicalize(*L); 3605 3606 if (InsertFormula(LU, LUIdx, F)) 3607 // If that formula hadn't been seen before, recurse to find more like 3608 // it. 3609 // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2) 3610 // Because just Depth is not enough to bound compile time. 3611 // This means that every time AddOps.size() is greater 16^x we will add 3612 // x to Depth. 3613 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), 3614 Depth + 1 + (Log2_32(AddOps.size()) >> 2)); 3615 } 3616 } 3617 3618 /// Split out subexpressions from adds and the bases of addrecs. 3619 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx, 3620 Formula Base, unsigned Depth) { 3621 assert(Base.isCanonical(*L) && "Input must be in the canonical form"); 3622 // Arbitrarily cap recursion to protect compile time. 3623 if (Depth >= 3) 3624 return; 3625 3626 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3627 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i); 3628 3629 if (Base.Scale == 1) 3630 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, 3631 /* Idx */ -1, /* IsScaledReg */ true); 3632 } 3633 3634 /// Generate a formula consisting of all of the loop-dominating registers added 3635 /// into a single register. 3636 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx, 3637 Formula Base) { 3638 // This method is only interesting on a plurality of registers. 3639 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1) 3640 return; 3641 3642 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before 3643 // processing the formula. 3644 Base.unscale(); 3645 Formula F = Base; 3646 F.BaseRegs.clear(); 3647 SmallVector<const SCEV *, 4> Ops; 3648 for (const SCEV *BaseReg : Base.BaseRegs) { 3649 if (SE.properlyDominates(BaseReg, L->getHeader()) && 3650 !SE.hasComputableLoopEvolution(BaseReg, L)) 3651 Ops.push_back(BaseReg); 3652 else 3653 F.BaseRegs.push_back(BaseReg); 3654 } 3655 if (Ops.size() > 1) { 3656 const SCEV *Sum = SE.getAddExpr(Ops); 3657 // TODO: If Sum is zero, it probably means ScalarEvolution missed an 3658 // opportunity to fold something. For now, just ignore such cases 3659 // rather than proceed with zero in a register. 3660 if (!Sum->isZero()) { 3661 F.BaseRegs.push_back(Sum); 3662 F.canonicalize(*L); 3663 (void)InsertFormula(LU, LUIdx, F); 3664 } 3665 } 3666 } 3667 3668 /// Helper function for LSRInstance::GenerateSymbolicOffsets. 3669 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, 3670 const Formula &Base, size_t Idx, 3671 bool IsScaledReg) { 3672 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3673 GlobalValue *GV = ExtractSymbol(G, SE); 3674 if (G->isZero() || !GV) 3675 return; 3676 Formula F = Base; 3677 F.BaseGV = GV; 3678 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) 3679 return; 3680 if (IsScaledReg) 3681 F.ScaledReg = G; 3682 else 3683 F.BaseRegs[Idx] = G; 3684 (void)InsertFormula(LU, LUIdx, F); 3685 } 3686 3687 /// Generate reuse formulae using symbolic offsets. 3688 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, 3689 Formula Base) { 3690 // We can't add a symbolic offset if the address already contains one. 3691 if (Base.BaseGV) return; 3692 3693 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3694 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i); 3695 if (Base.Scale == 1) 3696 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1, 3697 /* IsScaledReg */ true); 3698 } 3699 3700 /// Helper function for LSRInstance::GenerateConstantOffsets. 3701 void LSRInstance::GenerateConstantOffsetsImpl( 3702 LSRUse &LU, unsigned LUIdx, const Formula &Base, 3703 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) { 3704 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; 3705 for (int64_t Offset : Worklist) { 3706 Formula F = Base; 3707 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset; 3708 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind, 3709 LU.AccessTy, F)) { 3710 // Add the offset to the base register. 3711 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G); 3712 // If it cancelled out, drop the base register, otherwise update it. 3713 if (NewG->isZero()) { 3714 if (IsScaledReg) { 3715 F.Scale = 0; 3716 F.ScaledReg = nullptr; 3717 } else 3718 F.deleteBaseReg(F.BaseRegs[Idx]); 3719 F.canonicalize(*L); 3720 } else if (IsScaledReg) 3721 F.ScaledReg = NewG; 3722 else 3723 F.BaseRegs[Idx] = NewG; 3724 3725 (void)InsertFormula(LU, LUIdx, F); 3726 } 3727 } 3728 3729 int64_t Imm = ExtractImmediate(G, SE); 3730 if (G->isZero() || Imm == 0) 3731 return; 3732 Formula F = Base; 3733 F.BaseOffset = (uint64_t)F.BaseOffset + Imm; 3734 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) 3735 return; 3736 if (IsScaledReg) 3737 F.ScaledReg = G; 3738 else 3739 F.BaseRegs[Idx] = G; 3740 (void)InsertFormula(LU, LUIdx, F); 3741 } 3742 3743 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets. 3744 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, 3745 Formula Base) { 3746 // TODO: For now, just add the min and max offset, because it usually isn't 3747 // worthwhile looking at everything inbetween. 3748 SmallVector<int64_t, 2> Worklist; 3749 Worklist.push_back(LU.MinOffset); 3750 if (LU.MaxOffset != LU.MinOffset) 3751 Worklist.push_back(LU.MaxOffset); 3752 3753 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) 3754 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i); 3755 if (Base.Scale == 1) 3756 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1, 3757 /* IsScaledReg */ true); 3758 } 3759 3760 /// For ICmpZero, check to see if we can scale up the comparison. For example, x 3761 /// == y -> x*c == y*c. 3762 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, 3763 Formula Base) { 3764 if (LU.Kind != LSRUse::ICmpZero) return; 3765 3766 // Determine the integer type for the base formula. 3767 Type *IntTy = Base.getType(); 3768 if (!IntTy) return; 3769 if (SE.getTypeSizeInBits(IntTy) > 64) return; 3770 3771 // Don't do this if there is more than one offset. 3772 if (LU.MinOffset != LU.MaxOffset) return; 3773 3774 // Check if transformation is valid. It is illegal to multiply pointer. 3775 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy()) 3776 return; 3777 for (const SCEV *BaseReg : Base.BaseRegs) 3778 if (BaseReg->getType()->isPointerTy()) 3779 return; 3780 assert(!Base.BaseGV && "ICmpZero use is not legal!"); 3781 3782 // Check each interesting stride. 3783 for (int64_t Factor : Factors) { 3784 // Check that the multiplication doesn't overflow. 3785 if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1) 3786 continue; 3787 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor; 3788 if (NewBaseOffset / Factor != Base.BaseOffset) 3789 continue; 3790 // If the offset will be truncated at this use, check that it is in bounds. 3791 if (!IntTy->isPointerTy() && 3792 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset)) 3793 continue; 3794 3795 // Check that multiplying with the use offset doesn't overflow. 3796 int64_t Offset = LU.MinOffset; 3797 if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1) 3798 continue; 3799 Offset = (uint64_t)Offset * Factor; 3800 if (Offset / Factor != LU.MinOffset) 3801 continue; 3802 // If the offset will be truncated at this use, check that it is in bounds. 3803 if (!IntTy->isPointerTy() && 3804 !ConstantInt::isValueValidForType(IntTy, Offset)) 3805 continue; 3806 3807 Formula F = Base; 3808 F.BaseOffset = NewBaseOffset; 3809 3810 // Check that this scale is legal. 3811 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F)) 3812 continue; 3813 3814 // Compensate for the use having MinOffset built into it. 3815 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset; 3816 3817 const SCEV *FactorS = SE.getConstant(IntTy, Factor); 3818 3819 // Check that multiplying with each base register doesn't overflow. 3820 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) { 3821 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS); 3822 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i]) 3823 goto next; 3824 } 3825 3826 // Check that multiplying with the scaled register doesn't overflow. 3827 if (F.ScaledReg) { 3828 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS); 3829 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg) 3830 continue; 3831 } 3832 3833 // Check that multiplying with the unfolded offset doesn't overflow. 3834 if (F.UnfoldedOffset != 0) { 3835 if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() && 3836 Factor == -1) 3837 continue; 3838 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor; 3839 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset) 3840 continue; 3841 // If the offset will be truncated, check that it is in bounds. 3842 if (!IntTy->isPointerTy() && 3843 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset)) 3844 continue; 3845 } 3846 3847 // If we make it here and it's legal, add it. 3848 (void)InsertFormula(LU, LUIdx, F); 3849 next:; 3850 } 3851 } 3852 3853 /// Generate stride factor reuse formulae by making use of scaled-offset address 3854 /// modes, for example. 3855 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) { 3856 // Determine the integer type for the base formula. 3857 Type *IntTy = Base.getType(); 3858 if (!IntTy) return; 3859 3860 // If this Formula already has a scaled register, we can't add another one. 3861 // Try to unscale the formula to generate a better scale. 3862 if (Base.Scale != 0 && !Base.unscale()) 3863 return; 3864 3865 assert(Base.Scale == 0 && "unscale did not did its job!"); 3866 3867 // Check each interesting stride. 3868 for (int64_t Factor : Factors) { 3869 Base.Scale = Factor; 3870 Base.HasBaseReg = Base.BaseRegs.size() > 1; 3871 // Check whether this scale is going to be legal. 3872 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 3873 Base)) { 3874 // As a special-case, handle special out-of-loop Basic users specially. 3875 // TODO: Reconsider this special case. 3876 if (LU.Kind == LSRUse::Basic && 3877 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special, 3878 LU.AccessTy, Base) && 3879 LU.AllFixupsOutsideLoop) 3880 LU.Kind = LSRUse::Special; 3881 else 3882 continue; 3883 } 3884 // For an ICmpZero, negating a solitary base register won't lead to 3885 // new solutions. 3886 if (LU.Kind == LSRUse::ICmpZero && 3887 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV) 3888 continue; 3889 // For each addrec base reg, if its loop is current loop, apply the scale. 3890 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) { 3891 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]); 3892 if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) { 3893 const SCEV *FactorS = SE.getConstant(IntTy, Factor); 3894 if (FactorS->isZero()) 3895 continue; 3896 // Divide out the factor, ignoring high bits, since we'll be 3897 // scaling the value back up in the end. 3898 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) { 3899 // TODO: This could be optimized to avoid all the copying. 3900 Formula F = Base; 3901 F.ScaledReg = Quotient; 3902 F.deleteBaseReg(F.BaseRegs[i]); 3903 // The canonical representation of 1*reg is reg, which is already in 3904 // Base. In that case, do not try to insert the formula, it will be 3905 // rejected anyway. 3906 if (F.Scale == 1 && (F.BaseRegs.empty() || 3907 (AR->getLoop() != L && LU.AllFixupsOutsideLoop))) 3908 continue; 3909 // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate 3910 // non canonical Formula with ScaledReg's loop not being L. 3911 if (F.Scale == 1 && LU.AllFixupsOutsideLoop) 3912 F.canonicalize(*L); 3913 (void)InsertFormula(LU, LUIdx, F); 3914 } 3915 } 3916 } 3917 } 3918 } 3919 3920 /// Generate reuse formulae from different IV types. 3921 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) { 3922 // Don't bother truncating symbolic values. 3923 if (Base.BaseGV) return; 3924 3925 // Determine the integer type for the base formula. 3926 Type *DstTy = Base.getType(); 3927 if (!DstTy) return; 3928 DstTy = SE.getEffectiveSCEVType(DstTy); 3929 3930 for (Type *SrcTy : Types) { 3931 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) { 3932 Formula F = Base; 3933 3934 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy); 3935 for (const SCEV *&BaseReg : F.BaseRegs) 3936 BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy); 3937 3938 // TODO: This assumes we've done basic processing on all uses and 3939 // have an idea what the register usage is. 3940 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses)) 3941 continue; 3942 3943 F.canonicalize(*L); 3944 (void)InsertFormula(LU, LUIdx, F); 3945 } 3946 } 3947 } 3948 3949 namespace { 3950 3951 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer 3952 /// modifications so that the search phase doesn't have to worry about the data 3953 /// structures moving underneath it. 3954 struct WorkItem { 3955 size_t LUIdx; 3956 int64_t Imm; 3957 const SCEV *OrigReg; 3958 3959 WorkItem(size_t LI, int64_t I, const SCEV *R) 3960 : LUIdx(LI), Imm(I), OrigReg(R) {} 3961 3962 void print(raw_ostream &OS) const; 3963 void dump() const; 3964 }; 3965 3966 } // end anonymous namespace 3967 3968 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3969 void WorkItem::print(raw_ostream &OS) const { 3970 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx 3971 << " , add offset " << Imm; 3972 } 3973 3974 LLVM_DUMP_METHOD void WorkItem::dump() const { 3975 print(errs()); errs() << '\n'; 3976 } 3977 #endif 3978 3979 /// Look for registers which are a constant distance apart and try to form reuse 3980 /// opportunities between them. 3981 void LSRInstance::GenerateCrossUseConstantOffsets() { 3982 // Group the registers by their value without any added constant offset. 3983 using ImmMapTy = std::map<int64_t, const SCEV *>; 3984 3985 DenseMap<const SCEV *, ImmMapTy> Map; 3986 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap; 3987 SmallVector<const SCEV *, 8> Sequence; 3988 for (const SCEV *Use : RegUses) { 3989 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify. 3990 int64_t Imm = ExtractImmediate(Reg, SE); 3991 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy())); 3992 if (Pair.second) 3993 Sequence.push_back(Reg); 3994 Pair.first->second.insert(std::make_pair(Imm, Use)); 3995 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use); 3996 } 3997 3998 // Now examine each set of registers with the same base value. Build up 3999 // a list of work to do and do the work in a separate step so that we're 4000 // not adding formulae and register counts while we're searching. 4001 SmallVector<WorkItem, 32> WorkItems; 4002 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems; 4003 for (const SCEV *Reg : Sequence) { 4004 const ImmMapTy &Imms = Map.find(Reg)->second; 4005 4006 // It's not worthwhile looking for reuse if there's only one offset. 4007 if (Imms.size() == 1) 4008 continue; 4009 4010 LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':'; 4011 for (const auto &Entry 4012 : Imms) dbgs() 4013 << ' ' << Entry.first; 4014 dbgs() << '\n'); 4015 4016 // Examine each offset. 4017 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end(); 4018 J != JE; ++J) { 4019 const SCEV *OrigReg = J->second; 4020 4021 int64_t JImm = J->first; 4022 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg); 4023 4024 if (!isa<SCEVConstant>(OrigReg) && 4025 UsedByIndicesMap[Reg].count() == 1) { 4026 LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg 4027 << '\n'); 4028 continue; 4029 } 4030 4031 // Conservatively examine offsets between this orig reg a few selected 4032 // other orig regs. 4033 ImmMapTy::const_iterator OtherImms[] = { 4034 Imms.begin(), std::prev(Imms.end()), 4035 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) / 4036 2) 4037 }; 4038 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) { 4039 ImmMapTy::const_iterator M = OtherImms[i]; 4040 if (M == J || M == JE) continue; 4041 4042 // Compute the difference between the two. 4043 int64_t Imm = (uint64_t)JImm - M->first; 4044 for (unsigned LUIdx : UsedByIndices.set_bits()) 4045 // Make a memo of this use, offset, and register tuple. 4046 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second) 4047 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg)); 4048 } 4049 } 4050 } 4051 4052 Map.clear(); 4053 Sequence.clear(); 4054 UsedByIndicesMap.clear(); 4055 UniqueItems.clear(); 4056 4057 // Now iterate through the worklist and add new formulae. 4058 for (const WorkItem &WI : WorkItems) { 4059 size_t LUIdx = WI.LUIdx; 4060 LSRUse &LU = Uses[LUIdx]; 4061 int64_t Imm = WI.Imm; 4062 const SCEV *OrigReg = WI.OrigReg; 4063 4064 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType()); 4065 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm)); 4066 unsigned BitWidth = SE.getTypeSizeInBits(IntTy); 4067 4068 // TODO: Use a more targeted data structure. 4069 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) { 4070 Formula F = LU.Formulae[L]; 4071 // FIXME: The code for the scaled and unscaled registers looks 4072 // very similar but slightly different. Investigate if they 4073 // could be merged. That way, we would not have to unscale the 4074 // Formula. 4075 F.unscale(); 4076 // Use the immediate in the scaled register. 4077 if (F.ScaledReg == OrigReg) { 4078 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale; 4079 // Don't create 50 + reg(-50). 4080 if (F.referencesReg(SE.getSCEV( 4081 ConstantInt::get(IntTy, -(uint64_t)Offset)))) 4082 continue; 4083 Formula NewF = F; 4084 NewF.BaseOffset = Offset; 4085 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 4086 NewF)) 4087 continue; 4088 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg); 4089 4090 // If the new scale is a constant in a register, and adding the constant 4091 // value to the immediate would produce a value closer to zero than the 4092 // immediate itself, then the formula isn't worthwhile. 4093 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg)) 4094 if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) && 4095 (C->getAPInt().abs() * APInt(BitWidth, F.Scale)) 4096 .ule(std::abs(NewF.BaseOffset))) 4097 continue; 4098 4099 // OK, looks good. 4100 NewF.canonicalize(*this->L); 4101 (void)InsertFormula(LU, LUIdx, NewF); 4102 } else { 4103 // Use the immediate in a base register. 4104 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) { 4105 const SCEV *BaseReg = F.BaseRegs[N]; 4106 if (BaseReg != OrigReg) 4107 continue; 4108 Formula NewF = F; 4109 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm; 4110 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, 4111 LU.Kind, LU.AccessTy, NewF)) { 4112 if (TTI.shouldFavorPostInc() && 4113 mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE)) 4114 continue; 4115 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm)) 4116 continue; 4117 NewF = F; 4118 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm; 4119 } 4120 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg); 4121 4122 // If the new formula has a constant in a register, and adding the 4123 // constant value to the immediate would produce a value closer to 4124 // zero than the immediate itself, then the formula isn't worthwhile. 4125 for (const SCEV *NewReg : NewF.BaseRegs) 4126 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg)) 4127 if ((C->getAPInt() + NewF.BaseOffset) 4128 .abs() 4129 .slt(std::abs(NewF.BaseOffset)) && 4130 (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >= 4131 countTrailingZeros<uint64_t>(NewF.BaseOffset)) 4132 goto skip_formula; 4133 4134 // Ok, looks good. 4135 NewF.canonicalize(*this->L); 4136 (void)InsertFormula(LU, LUIdx, NewF); 4137 break; 4138 skip_formula:; 4139 } 4140 } 4141 } 4142 } 4143 } 4144 4145 /// Generate formulae for each use. 4146 void 4147 LSRInstance::GenerateAllReuseFormulae() { 4148 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan 4149 // queries are more precise. 4150 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4151 LSRUse &LU = Uses[LUIdx]; 4152 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4153 GenerateReassociations(LU, LUIdx, LU.Formulae[i]); 4154 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4155 GenerateCombinations(LU, LUIdx, LU.Formulae[i]); 4156 } 4157 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4158 LSRUse &LU = Uses[LUIdx]; 4159 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4160 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]); 4161 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4162 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]); 4163 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4164 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]); 4165 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4166 GenerateScales(LU, LUIdx, LU.Formulae[i]); 4167 } 4168 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4169 LSRUse &LU = Uses[LUIdx]; 4170 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) 4171 GenerateTruncates(LU, LUIdx, LU.Formulae[i]); 4172 } 4173 4174 GenerateCrossUseConstantOffsets(); 4175 4176 LLVM_DEBUG(dbgs() << "\n" 4177 "After generating reuse formulae:\n"; 4178 print_uses(dbgs())); 4179 } 4180 4181 /// If there are multiple formulae with the same set of registers used 4182 /// by other uses, pick the best one and delete the others. 4183 void LSRInstance::FilterOutUndesirableDedicatedRegisters() { 4184 DenseSet<const SCEV *> VisitedRegs; 4185 SmallPtrSet<const SCEV *, 16> Regs; 4186 SmallPtrSet<const SCEV *, 16> LoserRegs; 4187 #ifndef NDEBUG 4188 bool ChangedFormulae = false; 4189 #endif 4190 4191 // Collect the best formula for each unique set of shared registers. This 4192 // is reset for each use. 4193 using BestFormulaeTy = 4194 DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>; 4195 4196 BestFormulaeTy BestFormulae; 4197 4198 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4199 LSRUse &LU = Uses[LUIdx]; 4200 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); 4201 dbgs() << '\n'); 4202 4203 bool Any = false; 4204 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); 4205 FIdx != NumForms; ++FIdx) { 4206 Formula &F = LU.Formulae[FIdx]; 4207 4208 // Some formulas are instant losers. For example, they may depend on 4209 // nonexistent AddRecs from other loops. These need to be filtered 4210 // immediately, otherwise heuristics could choose them over others leading 4211 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here 4212 // avoids the need to recompute this information across formulae using the 4213 // same bad AddRec. Passing LoserRegs is also essential unless we remove 4214 // the corresponding bad register from the Regs set. 4215 Cost CostF; 4216 Regs.clear(); 4217 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs); 4218 if (CostF.isLoser()) { 4219 // During initial formula generation, undesirable formulae are generated 4220 // by uses within other loops that have some non-trivial address mode or 4221 // use the postinc form of the IV. LSR needs to provide these formulae 4222 // as the basis of rediscovering the desired formula that uses an AddRec 4223 // corresponding to the existing phi. Once all formulae have been 4224 // generated, these initial losers may be pruned. 4225 LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs()); 4226 dbgs() << "\n"); 4227 } 4228 else { 4229 SmallVector<const SCEV *, 4> Key; 4230 for (const SCEV *Reg : F.BaseRegs) { 4231 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx)) 4232 Key.push_back(Reg); 4233 } 4234 if (F.ScaledReg && 4235 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx)) 4236 Key.push_back(F.ScaledReg); 4237 // Unstable sort by host order ok, because this is only used for 4238 // uniquifying. 4239 llvm::sort(Key.begin(), Key.end()); 4240 4241 std::pair<BestFormulaeTy::const_iterator, bool> P = 4242 BestFormulae.insert(std::make_pair(Key, FIdx)); 4243 if (P.second) 4244 continue; 4245 4246 Formula &Best = LU.Formulae[P.first->second]; 4247 4248 Cost CostBest; 4249 Regs.clear(); 4250 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU); 4251 if (CostF.isLess(CostBest, TTI)) 4252 std::swap(F, Best); 4253 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs()); 4254 dbgs() << "\n" 4255 " in favor of formula "; 4256 Best.print(dbgs()); dbgs() << '\n'); 4257 } 4258 #ifndef NDEBUG 4259 ChangedFormulae = true; 4260 #endif 4261 LU.DeleteFormula(F); 4262 --FIdx; 4263 --NumForms; 4264 Any = true; 4265 } 4266 4267 // Now that we've filtered out some formulae, recompute the Regs set. 4268 if (Any) 4269 LU.RecomputeRegs(LUIdx, RegUses); 4270 4271 // Reset this to prepare for the next use. 4272 BestFormulae.clear(); 4273 } 4274 4275 LLVM_DEBUG(if (ChangedFormulae) { 4276 dbgs() << "\n" 4277 "After filtering out undesirable candidates:\n"; 4278 print_uses(dbgs()); 4279 }); 4280 } 4281 4282 // This is a rough guess that seems to work fairly well. 4283 static const size_t ComplexityLimit = std::numeric_limits<uint16_t>::max(); 4284 4285 /// Estimate the worst-case number of solutions the solver might have to 4286 /// consider. It almost never considers this many solutions because it prune the 4287 /// search space, but the pruning isn't always sufficient. 4288 size_t LSRInstance::EstimateSearchSpaceComplexity() const { 4289 size_t Power = 1; 4290 for (const LSRUse &LU : Uses) { 4291 size_t FSize = LU.Formulae.size(); 4292 if (FSize >= ComplexityLimit) { 4293 Power = ComplexityLimit; 4294 break; 4295 } 4296 Power *= FSize; 4297 if (Power >= ComplexityLimit) 4298 break; 4299 } 4300 return Power; 4301 } 4302 4303 /// When one formula uses a superset of the registers of another formula, it 4304 /// won't help reduce register pressure (though it may not necessarily hurt 4305 /// register pressure); remove it to simplify the system. 4306 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() { 4307 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4308 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4309 4310 LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae " 4311 "which use a superset of registers used by other " 4312 "formulae.\n"); 4313 4314 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4315 LSRUse &LU = Uses[LUIdx]; 4316 bool Any = false; 4317 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4318 Formula &F = LU.Formulae[i]; 4319 // Look for a formula with a constant or GV in a register. If the use 4320 // also has a formula with that same value in an immediate field, 4321 // delete the one that uses a register. 4322 for (SmallVectorImpl<const SCEV *>::const_iterator 4323 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) { 4324 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) { 4325 Formula NewF = F; 4326 NewF.BaseOffset += C->getValue()->getSExtValue(); 4327 NewF.BaseRegs.erase(NewF.BaseRegs.begin() + 4328 (I - F.BaseRegs.begin())); 4329 if (LU.HasFormulaWithSameRegs(NewF)) { 4330 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); 4331 dbgs() << '\n'); 4332 LU.DeleteFormula(F); 4333 --i; 4334 --e; 4335 Any = true; 4336 break; 4337 } 4338 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) { 4339 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) 4340 if (!F.BaseGV) { 4341 Formula NewF = F; 4342 NewF.BaseGV = GV; 4343 NewF.BaseRegs.erase(NewF.BaseRegs.begin() + 4344 (I - F.BaseRegs.begin())); 4345 if (LU.HasFormulaWithSameRegs(NewF)) { 4346 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); 4347 dbgs() << '\n'); 4348 LU.DeleteFormula(F); 4349 --i; 4350 --e; 4351 Any = true; 4352 break; 4353 } 4354 } 4355 } 4356 } 4357 } 4358 if (Any) 4359 LU.RecomputeRegs(LUIdx, RegUses); 4360 } 4361 4362 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4363 } 4364 } 4365 4366 /// When there are many registers for expressions like A, A+1, A+2, etc., 4367 /// allocate a single register for them. 4368 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() { 4369 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4370 return; 4371 4372 LLVM_DEBUG( 4373 dbgs() << "The search space is too complex.\n" 4374 "Narrowing the search space by assuming that uses separated " 4375 "by a constant offset will use the same registers.\n"); 4376 4377 // This is especially useful for unrolled loops. 4378 4379 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4380 LSRUse &LU = Uses[LUIdx]; 4381 for (const Formula &F : LU.Formulae) { 4382 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1)) 4383 continue; 4384 4385 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU); 4386 if (!LUThatHas) 4387 continue; 4388 4389 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false, 4390 LU.Kind, LU.AccessTy)) 4391 continue; 4392 4393 LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n'); 4394 4395 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop; 4396 4397 // Transfer the fixups of LU to LUThatHas. 4398 for (LSRFixup &Fixup : LU.Fixups) { 4399 Fixup.Offset += F.BaseOffset; 4400 LUThatHas->pushFixup(Fixup); 4401 LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n'); 4402 } 4403 4404 // Delete formulae from the new use which are no longer legal. 4405 bool Any = false; 4406 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) { 4407 Formula &F = LUThatHas->Formulae[i]; 4408 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset, 4409 LUThatHas->Kind, LUThatHas->AccessTy, F)) { 4410 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n'); 4411 LUThatHas->DeleteFormula(F); 4412 --i; 4413 --e; 4414 Any = true; 4415 } 4416 } 4417 4418 if (Any) 4419 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses); 4420 4421 // Delete the old use. 4422 DeleteUse(LU, LUIdx); 4423 --LUIdx; 4424 --NumUses; 4425 break; 4426 } 4427 } 4428 4429 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4430 } 4431 4432 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that 4433 /// we've done more filtering, as it may be able to find more formulae to 4434 /// eliminate. 4435 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){ 4436 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4437 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4438 4439 LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out " 4440 "undesirable dedicated registers.\n"); 4441 4442 FilterOutUndesirableDedicatedRegisters(); 4443 4444 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4445 } 4446 } 4447 4448 /// If a LSRUse has multiple formulae with the same ScaledReg and Scale. 4449 /// Pick the best one and delete the others. 4450 /// This narrowing heuristic is to keep as many formulae with different 4451 /// Scale and ScaledReg pair as possible while narrowing the search space. 4452 /// The benefit is that it is more likely to find out a better solution 4453 /// from a formulae set with more Scale and ScaledReg variations than 4454 /// a formulae set with the same Scale and ScaledReg. The picking winner 4455 /// reg heurstic will often keep the formulae with the same Scale and 4456 /// ScaledReg and filter others, and we want to avoid that if possible. 4457 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() { 4458 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4459 return; 4460 4461 LLVM_DEBUG( 4462 dbgs() << "The search space is too complex.\n" 4463 "Narrowing the search space by choosing the best Formula " 4464 "from the Formulae with the same Scale and ScaledReg.\n"); 4465 4466 // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse. 4467 using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>; 4468 4469 BestFormulaeTy BestFormulae; 4470 #ifndef NDEBUG 4471 bool ChangedFormulae = false; 4472 #endif 4473 DenseSet<const SCEV *> VisitedRegs; 4474 SmallPtrSet<const SCEV *, 16> Regs; 4475 4476 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4477 LSRUse &LU = Uses[LUIdx]; 4478 LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); 4479 dbgs() << '\n'); 4480 4481 // Return true if Formula FA is better than Formula FB. 4482 auto IsBetterThan = [&](Formula &FA, Formula &FB) { 4483 // First we will try to choose the Formula with fewer new registers. 4484 // For a register used by current Formula, the more the register is 4485 // shared among LSRUses, the less we increase the register number 4486 // counter of the formula. 4487 size_t FARegNum = 0; 4488 for (const SCEV *Reg : FA.BaseRegs) { 4489 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg); 4490 FARegNum += (NumUses - UsedByIndices.count() + 1); 4491 } 4492 size_t FBRegNum = 0; 4493 for (const SCEV *Reg : FB.BaseRegs) { 4494 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg); 4495 FBRegNum += (NumUses - UsedByIndices.count() + 1); 4496 } 4497 if (FARegNum != FBRegNum) 4498 return FARegNum < FBRegNum; 4499 4500 // If the new register numbers are the same, choose the Formula with 4501 // less Cost. 4502 Cost CostFA, CostFB; 4503 Regs.clear(); 4504 CostFA.RateFormula(TTI, FA, Regs, VisitedRegs, L, SE, DT, LU); 4505 Regs.clear(); 4506 CostFB.RateFormula(TTI, FB, Regs, VisitedRegs, L, SE, DT, LU); 4507 return CostFA.isLess(CostFB, TTI); 4508 }; 4509 4510 bool Any = false; 4511 for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms; 4512 ++FIdx) { 4513 Formula &F = LU.Formulae[FIdx]; 4514 if (!F.ScaledReg) 4515 continue; 4516 auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx}); 4517 if (P.second) 4518 continue; 4519 4520 Formula &Best = LU.Formulae[P.first->second]; 4521 if (IsBetterThan(F, Best)) 4522 std::swap(F, Best); 4523 LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs()); 4524 dbgs() << "\n" 4525 " in favor of formula "; 4526 Best.print(dbgs()); dbgs() << '\n'); 4527 #ifndef NDEBUG 4528 ChangedFormulae = true; 4529 #endif 4530 LU.DeleteFormula(F); 4531 --FIdx; 4532 --NumForms; 4533 Any = true; 4534 } 4535 if (Any) 4536 LU.RecomputeRegs(LUIdx, RegUses); 4537 4538 // Reset this to prepare for the next use. 4539 BestFormulae.clear(); 4540 } 4541 4542 LLVM_DEBUG(if (ChangedFormulae) { 4543 dbgs() << "\n" 4544 "After filtering out undesirable candidates:\n"; 4545 print_uses(dbgs()); 4546 }); 4547 } 4548 4549 /// The function delete formulas with high registers number expectation. 4550 /// Assuming we don't know the value of each formula (already delete 4551 /// all inefficient), generate probability of not selecting for each 4552 /// register. 4553 /// For example, 4554 /// Use1: 4555 /// reg(a) + reg({0,+,1}) 4556 /// reg(a) + reg({-1,+,1}) + 1 4557 /// reg({a,+,1}) 4558 /// Use2: 4559 /// reg(b) + reg({0,+,1}) 4560 /// reg(b) + reg({-1,+,1}) + 1 4561 /// reg({b,+,1}) 4562 /// Use3: 4563 /// reg(c) + reg(b) + reg({0,+,1}) 4564 /// reg(c) + reg({b,+,1}) 4565 /// 4566 /// Probability of not selecting 4567 /// Use1 Use2 Use3 4568 /// reg(a) (1/3) * 1 * 1 4569 /// reg(b) 1 * (1/3) * (1/2) 4570 /// reg({0,+,1}) (2/3) * (2/3) * (1/2) 4571 /// reg({-1,+,1}) (2/3) * (2/3) * 1 4572 /// reg({a,+,1}) (2/3) * 1 * 1 4573 /// reg({b,+,1}) 1 * (2/3) * (2/3) 4574 /// reg(c) 1 * 1 * 0 4575 /// 4576 /// Now count registers number mathematical expectation for each formula: 4577 /// Note that for each use we exclude probability if not selecting for the use. 4578 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding 4579 /// probabilty 1/3 of not selecting for Use1). 4580 /// Use1: 4581 /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted 4582 /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted 4583 /// reg({a,+,1}) 1 4584 /// Use2: 4585 /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted 4586 /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted 4587 /// reg({b,+,1}) 2/3 4588 /// Use3: 4589 /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted 4590 /// reg(c) + reg({b,+,1}) 1 + 2/3 4591 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() { 4592 if (EstimateSearchSpaceComplexity() < ComplexityLimit) 4593 return; 4594 // Ok, we have too many of formulae on our hands to conveniently handle. 4595 // Use a rough heuristic to thin out the list. 4596 4597 // Set of Regs wich will be 100% used in final solution. 4598 // Used in each formula of a solution (in example above this is reg(c)). 4599 // We can skip them in calculations. 4600 SmallPtrSet<const SCEV *, 4> UniqRegs; 4601 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4602 4603 // Map each register to probability of not selecting 4604 DenseMap <const SCEV *, float> RegNumMap; 4605 for (const SCEV *Reg : RegUses) { 4606 if (UniqRegs.count(Reg)) 4607 continue; 4608 float PNotSel = 1; 4609 for (const LSRUse &LU : Uses) { 4610 if (!LU.Regs.count(Reg)) 4611 continue; 4612 float P = LU.getNotSelectedProbability(Reg); 4613 if (P != 0.0) 4614 PNotSel *= P; 4615 else 4616 UniqRegs.insert(Reg); 4617 } 4618 RegNumMap.insert(std::make_pair(Reg, PNotSel)); 4619 } 4620 4621 LLVM_DEBUG( 4622 dbgs() << "Narrowing the search space by deleting costly formulas\n"); 4623 4624 // Delete formulas where registers number expectation is high. 4625 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4626 LSRUse &LU = Uses[LUIdx]; 4627 // If nothing to delete - continue. 4628 if (LU.Formulae.size() < 2) 4629 continue; 4630 // This is temporary solution to test performance. Float should be 4631 // replaced with round independent type (based on integers) to avoid 4632 // different results for different target builds. 4633 float FMinRegNum = LU.Formulae[0].getNumRegs(); 4634 float FMinARegNum = LU.Formulae[0].getNumRegs(); 4635 size_t MinIdx = 0; 4636 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4637 Formula &F = LU.Formulae[i]; 4638 float FRegNum = 0; 4639 float FARegNum = 0; 4640 for (const SCEV *BaseReg : F.BaseRegs) { 4641 if (UniqRegs.count(BaseReg)) 4642 continue; 4643 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); 4644 if (isa<SCEVAddRecExpr>(BaseReg)) 4645 FARegNum += 4646 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); 4647 } 4648 if (const SCEV *ScaledReg = F.ScaledReg) { 4649 if (!UniqRegs.count(ScaledReg)) { 4650 FRegNum += 4651 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); 4652 if (isa<SCEVAddRecExpr>(ScaledReg)) 4653 FARegNum += 4654 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); 4655 } 4656 } 4657 if (FMinRegNum > FRegNum || 4658 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) { 4659 FMinRegNum = FRegNum; 4660 FMinARegNum = FARegNum; 4661 MinIdx = i; 4662 } 4663 } 4664 LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs()); 4665 dbgs() << " with min reg num " << FMinRegNum << '\n'); 4666 if (MinIdx != 0) 4667 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]); 4668 while (LU.Formulae.size() != 1) { 4669 LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs()); 4670 dbgs() << '\n'); 4671 LU.Formulae.pop_back(); 4672 } 4673 LU.RecomputeRegs(LUIdx, RegUses); 4674 assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula"); 4675 Formula &F = LU.Formulae[0]; 4676 LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n'); 4677 // When we choose the formula, the regs become unique. 4678 UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); 4679 if (F.ScaledReg) 4680 UniqRegs.insert(F.ScaledReg); 4681 } 4682 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4683 } 4684 4685 /// Pick a register which seems likely to be profitable, and then in any use 4686 /// which has any reference to that register, delete all formulae which do not 4687 /// reference that register. 4688 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() { 4689 // With all other options exhausted, loop until the system is simple 4690 // enough to handle. 4691 SmallPtrSet<const SCEV *, 4> Taken; 4692 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) { 4693 // Ok, we have too many of formulae on our hands to conveniently handle. 4694 // Use a rough heuristic to thin out the list. 4695 LLVM_DEBUG(dbgs() << "The search space is too complex.\n"); 4696 4697 // Pick the register which is used by the most LSRUses, which is likely 4698 // to be a good reuse register candidate. 4699 const SCEV *Best = nullptr; 4700 unsigned BestNum = 0; 4701 for (const SCEV *Reg : RegUses) { 4702 if (Taken.count(Reg)) 4703 continue; 4704 if (!Best) { 4705 Best = Reg; 4706 BestNum = RegUses.getUsedByIndices(Reg).count(); 4707 } else { 4708 unsigned Count = RegUses.getUsedByIndices(Reg).count(); 4709 if (Count > BestNum) { 4710 Best = Reg; 4711 BestNum = Count; 4712 } 4713 } 4714 } 4715 4716 LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best 4717 << " will yield profitable reuse.\n"); 4718 Taken.insert(Best); 4719 4720 // In any use with formulae which references this register, delete formulae 4721 // which don't reference it. 4722 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { 4723 LSRUse &LU = Uses[LUIdx]; 4724 if (!LU.Regs.count(Best)) continue; 4725 4726 bool Any = false; 4727 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { 4728 Formula &F = LU.Formulae[i]; 4729 if (!F.referencesReg(Best)) { 4730 LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n'); 4731 LU.DeleteFormula(F); 4732 --e; 4733 --i; 4734 Any = true; 4735 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?"); 4736 continue; 4737 } 4738 } 4739 4740 if (Any) 4741 LU.RecomputeRegs(LUIdx, RegUses); 4742 } 4743 4744 LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs())); 4745 } 4746 } 4747 4748 /// If there are an extraordinary number of formulae to choose from, use some 4749 /// rough heuristics to prune down the number of formulae. This keeps the main 4750 /// solver from taking an extraordinary amount of time in some worst-case 4751 /// scenarios. 4752 void LSRInstance::NarrowSearchSpaceUsingHeuristics() { 4753 NarrowSearchSpaceByDetectingSupersets(); 4754 NarrowSearchSpaceByCollapsingUnrolledCode(); 4755 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); 4756 if (FilterSameScaledReg) 4757 NarrowSearchSpaceByFilterFormulaWithSameScaledReg(); 4758 if (LSRExpNarrow) 4759 NarrowSearchSpaceByDeletingCostlyFormulas(); 4760 else 4761 NarrowSearchSpaceByPickingWinnerRegs(); 4762 } 4763 4764 /// This is the recursive solver. 4765 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution, 4766 Cost &SolutionCost, 4767 SmallVectorImpl<const Formula *> &Workspace, 4768 const Cost &CurCost, 4769 const SmallPtrSet<const SCEV *, 16> &CurRegs, 4770 DenseSet<const SCEV *> &VisitedRegs) const { 4771 // Some ideas: 4772 // - prune more: 4773 // - use more aggressive filtering 4774 // - sort the formula so that the most profitable solutions are found first 4775 // - sort the uses too 4776 // - search faster: 4777 // - don't compute a cost, and then compare. compare while computing a cost 4778 // and bail early. 4779 // - track register sets with SmallBitVector 4780 4781 const LSRUse &LU = Uses[Workspace.size()]; 4782 4783 // If this use references any register that's already a part of the 4784 // in-progress solution, consider it a requirement that a formula must 4785 // reference that register in order to be considered. This prunes out 4786 // unprofitable searching. 4787 SmallSetVector<const SCEV *, 4> ReqRegs; 4788 for (const SCEV *S : CurRegs) 4789 if (LU.Regs.count(S)) 4790 ReqRegs.insert(S); 4791 4792 SmallPtrSet<const SCEV *, 16> NewRegs; 4793 Cost NewCost; 4794 for (const Formula &F : LU.Formulae) { 4795 // Ignore formulae which may not be ideal in terms of register reuse of 4796 // ReqRegs. The formula should use all required registers before 4797 // introducing new ones. 4798 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size()); 4799 for (const SCEV *Reg : ReqRegs) { 4800 if ((F.ScaledReg && F.ScaledReg == Reg) || 4801 is_contained(F.BaseRegs, Reg)) { 4802 --NumReqRegsToFind; 4803 if (NumReqRegsToFind == 0) 4804 break; 4805 } 4806 } 4807 if (NumReqRegsToFind != 0) { 4808 // If none of the formulae satisfied the required registers, then we could 4809 // clear ReqRegs and try again. Currently, we simply give up in this case. 4810 continue; 4811 } 4812 4813 // Evaluate the cost of the current formula. If it's already worse than 4814 // the current best, prune the search at that point. 4815 NewCost = CurCost; 4816 NewRegs = CurRegs; 4817 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU); 4818 if (NewCost.isLess(SolutionCost, TTI)) { 4819 Workspace.push_back(&F); 4820 if (Workspace.size() != Uses.size()) { 4821 SolveRecurse(Solution, SolutionCost, Workspace, NewCost, 4822 NewRegs, VisitedRegs); 4823 if (F.getNumRegs() == 1 && Workspace.size() == 1) 4824 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]); 4825 } else { 4826 LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs()); 4827 dbgs() << ".\n Regs:"; for (const SCEV *S 4828 : NewRegs) dbgs() 4829 << ' ' << *S; 4830 dbgs() << '\n'); 4831 4832 SolutionCost = NewCost; 4833 Solution = Workspace; 4834 } 4835 Workspace.pop_back(); 4836 } 4837 } 4838 } 4839 4840 /// Choose one formula from each use. Return the results in the given Solution 4841 /// vector. 4842 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const { 4843 SmallVector<const Formula *, 8> Workspace; 4844 Cost SolutionCost; 4845 SolutionCost.Lose(); 4846 Cost CurCost; 4847 SmallPtrSet<const SCEV *, 16> CurRegs; 4848 DenseSet<const SCEV *> VisitedRegs; 4849 Workspace.reserve(Uses.size()); 4850 4851 // SolveRecurse does all the work. 4852 SolveRecurse(Solution, SolutionCost, Workspace, CurCost, 4853 CurRegs, VisitedRegs); 4854 if (Solution.empty()) { 4855 LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n"); 4856 return; 4857 } 4858 4859 // Ok, we've now made all our decisions. 4860 LLVM_DEBUG(dbgs() << "\n" 4861 "The chosen solution requires "; 4862 SolutionCost.print(dbgs()); dbgs() << ":\n"; 4863 for (size_t i = 0, e = Uses.size(); i != e; ++i) { 4864 dbgs() << " "; 4865 Uses[i].print(dbgs()); 4866 dbgs() << "\n" 4867 " "; 4868 Solution[i]->print(dbgs()); 4869 dbgs() << '\n'; 4870 }); 4871 4872 assert(Solution.size() == Uses.size() && "Malformed solution!"); 4873 } 4874 4875 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as 4876 /// we can go while still being dominated by the input positions. This helps 4877 /// canonicalize the insert position, which encourages sharing. 4878 BasicBlock::iterator 4879 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP, 4880 const SmallVectorImpl<Instruction *> &Inputs) 4881 const { 4882 Instruction *Tentative = &*IP; 4883 while (true) { 4884 bool AllDominate = true; 4885 Instruction *BetterPos = nullptr; 4886 // Don't bother attempting to insert before a catchswitch, their basic block 4887 // cannot have other non-PHI instructions. 4888 if (isa<CatchSwitchInst>(Tentative)) 4889 return IP; 4890 4891 for (Instruction *Inst : Inputs) { 4892 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) { 4893 AllDominate = false; 4894 break; 4895 } 4896 // Attempt to find an insert position in the middle of the block, 4897 // instead of at the end, so that it can be used for other expansions. 4898 if (Tentative->getParent() == Inst->getParent() && 4899 (!BetterPos || !DT.dominates(Inst, BetterPos))) 4900 BetterPos = &*std::next(BasicBlock::iterator(Inst)); 4901 } 4902 if (!AllDominate) 4903 break; 4904 if (BetterPos) 4905 IP = BetterPos->getIterator(); 4906 else 4907 IP = Tentative->getIterator(); 4908 4909 const Loop *IPLoop = LI.getLoopFor(IP->getParent()); 4910 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0; 4911 4912 BasicBlock *IDom; 4913 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) { 4914 if (!Rung) return IP; 4915 Rung = Rung->getIDom(); 4916 if (!Rung) return IP; 4917 IDom = Rung->getBlock(); 4918 4919 // Don't climb into a loop though. 4920 const Loop *IDomLoop = LI.getLoopFor(IDom); 4921 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0; 4922 if (IDomDepth <= IPLoopDepth && 4923 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop)) 4924 break; 4925 } 4926 4927 Tentative = IDom->getTerminator(); 4928 } 4929 4930 return IP; 4931 } 4932 4933 /// Determine an input position which will be dominated by the operands and 4934 /// which will dominate the result. 4935 BasicBlock::iterator 4936 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP, 4937 const LSRFixup &LF, 4938 const LSRUse &LU, 4939 SCEVExpander &Rewriter) const { 4940 // Collect some instructions which must be dominated by the 4941 // expanding replacement. These must be dominated by any operands that 4942 // will be required in the expansion. 4943 SmallVector<Instruction *, 4> Inputs; 4944 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace)) 4945 Inputs.push_back(I); 4946 if (LU.Kind == LSRUse::ICmpZero) 4947 if (Instruction *I = 4948 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1))) 4949 Inputs.push_back(I); 4950 if (LF.PostIncLoops.count(L)) { 4951 if (LF.isUseFullyOutsideLoop(L)) 4952 Inputs.push_back(L->getLoopLatch()->getTerminator()); 4953 else 4954 Inputs.push_back(IVIncInsertPos); 4955 } 4956 // The expansion must also be dominated by the increment positions of any 4957 // loops it for which it is using post-inc mode. 4958 for (const Loop *PIL : LF.PostIncLoops) { 4959 if (PIL == L) continue; 4960 4961 // Be dominated by the loop exit. 4962 SmallVector<BasicBlock *, 4> ExitingBlocks; 4963 PIL->getExitingBlocks(ExitingBlocks); 4964 if (!ExitingBlocks.empty()) { 4965 BasicBlock *BB = ExitingBlocks[0]; 4966 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i) 4967 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]); 4968 Inputs.push_back(BB->getTerminator()); 4969 } 4970 } 4971 4972 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() 4973 && !isa<DbgInfoIntrinsic>(LowestIP) && 4974 "Insertion point must be a normal instruction"); 4975 4976 // Then, climb up the immediate dominator tree as far as we can go while 4977 // still being dominated by the input positions. 4978 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs); 4979 4980 // Don't insert instructions before PHI nodes. 4981 while (isa<PHINode>(IP)) ++IP; 4982 4983 // Ignore landingpad instructions. 4984 while (IP->isEHPad()) ++IP; 4985 4986 // Ignore debug intrinsics. 4987 while (isa<DbgInfoIntrinsic>(IP)) ++IP; 4988 4989 // Set IP below instructions recently inserted by SCEVExpander. This keeps the 4990 // IP consistent across expansions and allows the previously inserted 4991 // instructions to be reused by subsequent expansion. 4992 while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP) 4993 ++IP; 4994 4995 return IP; 4996 } 4997 4998 /// Emit instructions for the leading candidate expression for this LSRUse (this 4999 /// is called "expanding"). 5000 Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF, 5001 const Formula &F, BasicBlock::iterator IP, 5002 SCEVExpander &Rewriter, 5003 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5004 if (LU.RigidFormula) 5005 return LF.OperandValToReplace; 5006 5007 // Determine an input position which will be dominated by the operands and 5008 // which will dominate the result. 5009 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter); 5010 Rewriter.setInsertPoint(&*IP); 5011 5012 // Inform the Rewriter if we have a post-increment use, so that it can 5013 // perform an advantageous expansion. 5014 Rewriter.setPostInc(LF.PostIncLoops); 5015 5016 // This is the type that the user actually needs. 5017 Type *OpTy = LF.OperandValToReplace->getType(); 5018 // This will be the type that we'll initially expand to. 5019 Type *Ty = F.getType(); 5020 if (!Ty) 5021 // No type known; just expand directly to the ultimate type. 5022 Ty = OpTy; 5023 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy)) 5024 // Expand directly to the ultimate type if it's the right size. 5025 Ty = OpTy; 5026 // This is the type to do integer arithmetic in. 5027 Type *IntTy = SE.getEffectiveSCEVType(Ty); 5028 5029 // Build up a list of operands to add together to form the full base. 5030 SmallVector<const SCEV *, 8> Ops; 5031 5032 // Expand the BaseRegs portion. 5033 for (const SCEV *Reg : F.BaseRegs) { 5034 assert(!Reg->isZero() && "Zero allocated in a base register!"); 5035 5036 // If we're expanding for a post-inc user, make the post-inc adjustment. 5037 Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE); 5038 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr))); 5039 } 5040 5041 // Expand the ScaledReg portion. 5042 Value *ICmpScaledV = nullptr; 5043 if (F.Scale != 0) { 5044 const SCEV *ScaledS = F.ScaledReg; 5045 5046 // If we're expanding for a post-inc user, make the post-inc adjustment. 5047 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops); 5048 ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE); 5049 5050 if (LU.Kind == LSRUse::ICmpZero) { 5051 // Expand ScaleReg as if it was part of the base regs. 5052 if (F.Scale == 1) 5053 Ops.push_back( 5054 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr))); 5055 else { 5056 // An interesting way of "folding" with an icmp is to use a negated 5057 // scale, which we'll implement by inserting it into the other operand 5058 // of the icmp. 5059 assert(F.Scale == -1 && 5060 "The only scale supported by ICmpZero uses is -1!"); 5061 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr); 5062 } 5063 } else { 5064 // Otherwise just expand the scaled register and an explicit scale, 5065 // which is expected to be matched as part of the address. 5066 5067 // Flush the operand list to suppress SCEVExpander hoisting address modes. 5068 // Unless the addressing mode will not be folded. 5069 if (!Ops.empty() && LU.Kind == LSRUse::Address && 5070 isAMCompletelyFolded(TTI, LU, F)) { 5071 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr); 5072 Ops.clear(); 5073 Ops.push_back(SE.getUnknown(FullV)); 5074 } 5075 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)); 5076 if (F.Scale != 1) 5077 ScaledS = 5078 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale)); 5079 Ops.push_back(ScaledS); 5080 } 5081 } 5082 5083 // Expand the GV portion. 5084 if (F.BaseGV) { 5085 // Flush the operand list to suppress SCEVExpander hoisting. 5086 if (!Ops.empty()) { 5087 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); 5088 Ops.clear(); 5089 Ops.push_back(SE.getUnknown(FullV)); 5090 } 5091 Ops.push_back(SE.getUnknown(F.BaseGV)); 5092 } 5093 5094 // Flush the operand list to suppress SCEVExpander hoisting of both folded and 5095 // unfolded offsets. LSR assumes they both live next to their uses. 5096 if (!Ops.empty()) { 5097 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); 5098 Ops.clear(); 5099 Ops.push_back(SE.getUnknown(FullV)); 5100 } 5101 5102 // Expand the immediate portion. 5103 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset; 5104 if (Offset != 0) { 5105 if (LU.Kind == LSRUse::ICmpZero) { 5106 // The other interesting way of "folding" with an ICmpZero is to use a 5107 // negated immediate. 5108 if (!ICmpScaledV) 5109 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset); 5110 else { 5111 Ops.push_back(SE.getUnknown(ICmpScaledV)); 5112 ICmpScaledV = ConstantInt::get(IntTy, Offset); 5113 } 5114 } else { 5115 // Just add the immediate values. These again are expected to be matched 5116 // as part of the address. 5117 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset))); 5118 } 5119 } 5120 5121 // Expand the unfolded offset portion. 5122 int64_t UnfoldedOffset = F.UnfoldedOffset; 5123 if (UnfoldedOffset != 0) { 5124 // Just add the immediate values. 5125 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, 5126 UnfoldedOffset))); 5127 } 5128 5129 // Emit instructions summing all the operands. 5130 const SCEV *FullS = Ops.empty() ? 5131 SE.getConstant(IntTy, 0) : 5132 SE.getAddExpr(Ops); 5133 Value *FullV = Rewriter.expandCodeFor(FullS, Ty); 5134 5135 // We're done expanding now, so reset the rewriter. 5136 Rewriter.clearPostInc(); 5137 5138 // An ICmpZero Formula represents an ICmp which we're handling as a 5139 // comparison against zero. Now that we've expanded an expression for that 5140 // form, update the ICmp's other operand. 5141 if (LU.Kind == LSRUse::ICmpZero) { 5142 ICmpInst *CI = cast<ICmpInst>(LF.UserInst); 5143 DeadInsts.emplace_back(CI->getOperand(1)); 5144 assert(!F.BaseGV && "ICmp does not support folding a global value and " 5145 "a scale at the same time!"); 5146 if (F.Scale == -1) { 5147 if (ICmpScaledV->getType() != OpTy) { 5148 Instruction *Cast = 5149 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false, 5150 OpTy, false), 5151 ICmpScaledV, OpTy, "tmp", CI); 5152 ICmpScaledV = Cast; 5153 } 5154 CI->setOperand(1, ICmpScaledV); 5155 } else { 5156 // A scale of 1 means that the scale has been expanded as part of the 5157 // base regs. 5158 assert((F.Scale == 0 || F.Scale == 1) && 5159 "ICmp does not support folding a global value and " 5160 "a scale at the same time!"); 5161 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy), 5162 -(uint64_t)Offset); 5163 if (C->getType() != OpTy) 5164 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 5165 OpTy, false), 5166 C, OpTy); 5167 5168 CI->setOperand(1, C); 5169 } 5170 } 5171 5172 return FullV; 5173 } 5174 5175 /// Helper for Rewrite. PHI nodes are special because the use of their operands 5176 /// effectively happens in their predecessor blocks, so the expression may need 5177 /// to be expanded in multiple places. 5178 void LSRInstance::RewriteForPHI( 5179 PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F, 5180 SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5181 DenseMap<BasicBlock *, Value *> Inserted; 5182 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5183 if (PN->getIncomingValue(i) == LF.OperandValToReplace) { 5184 BasicBlock *BB = PN->getIncomingBlock(i); 5185 5186 // If this is a critical edge, split the edge so that we do not insert 5187 // the code on all predecessor/successor paths. We do this unless this 5188 // is the canonical backedge for this loop, which complicates post-inc 5189 // users. 5190 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 && 5191 !isa<IndirectBrInst>(BB->getTerminator()) && 5192 !isa<CatchSwitchInst>(BB->getTerminator())) { 5193 BasicBlock *Parent = PN->getParent(); 5194 Loop *PNLoop = LI.getLoopFor(Parent); 5195 if (!PNLoop || Parent != PNLoop->getHeader()) { 5196 // Split the critical edge. 5197 BasicBlock *NewBB = nullptr; 5198 if (!Parent->isLandingPad()) { 5199 NewBB = SplitCriticalEdge(BB, Parent, 5200 CriticalEdgeSplittingOptions(&DT, &LI) 5201 .setMergeIdenticalEdges() 5202 .setDontDeleteUselessPHIs()); 5203 } else { 5204 SmallVector<BasicBlock*, 2> NewBBs; 5205 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI); 5206 NewBB = NewBBs[0]; 5207 } 5208 // If NewBB==NULL, then SplitCriticalEdge refused to split because all 5209 // phi predecessors are identical. The simple thing to do is skip 5210 // splitting in this case rather than complicate the API. 5211 if (NewBB) { 5212 // If PN is outside of the loop and BB is in the loop, we want to 5213 // move the block to be immediately before the PHI block, not 5214 // immediately after BB. 5215 if (L->contains(BB) && !L->contains(PN)) 5216 NewBB->moveBefore(PN->getParent()); 5217 5218 // Splitting the edge can reduce the number of PHI entries we have. 5219 e = PN->getNumIncomingValues(); 5220 BB = NewBB; 5221 i = PN->getBasicBlockIndex(BB); 5222 } 5223 } 5224 } 5225 5226 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair = 5227 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr))); 5228 if (!Pair.second) 5229 PN->setIncomingValue(i, Pair.first->second); 5230 else { 5231 Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(), 5232 Rewriter, DeadInsts); 5233 5234 // If this is reuse-by-noop-cast, insert the noop cast. 5235 Type *OpTy = LF.OperandValToReplace->getType(); 5236 if (FullV->getType() != OpTy) 5237 FullV = 5238 CastInst::Create(CastInst::getCastOpcode(FullV, false, 5239 OpTy, false), 5240 FullV, LF.OperandValToReplace->getType(), 5241 "tmp", BB->getTerminator()); 5242 5243 PN->setIncomingValue(i, FullV); 5244 Pair.first->second = FullV; 5245 } 5246 } 5247 } 5248 5249 /// Emit instructions for the leading candidate expression for this LSRUse (this 5250 /// is called "expanding"), and update the UserInst to reference the newly 5251 /// expanded value. 5252 void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF, 5253 const Formula &F, SCEVExpander &Rewriter, 5254 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { 5255 // First, find an insertion point that dominates UserInst. For PHI nodes, 5256 // find the nearest block which dominates all the relevant uses. 5257 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) { 5258 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts); 5259 } else { 5260 Value *FullV = 5261 Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts); 5262 5263 // If this is reuse-by-noop-cast, insert the noop cast. 5264 Type *OpTy = LF.OperandValToReplace->getType(); 5265 if (FullV->getType() != OpTy) { 5266 Instruction *Cast = 5267 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false), 5268 FullV, OpTy, "tmp", LF.UserInst); 5269 FullV = Cast; 5270 } 5271 5272 // Update the user. ICmpZero is handled specially here (for now) because 5273 // Expand may have updated one of the operands of the icmp already, and 5274 // its new value may happen to be equal to LF.OperandValToReplace, in 5275 // which case doing replaceUsesOfWith leads to replacing both operands 5276 // with the same value. TODO: Reorganize this. 5277 if (LU.Kind == LSRUse::ICmpZero) 5278 LF.UserInst->setOperand(0, FullV); 5279 else 5280 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV); 5281 } 5282 5283 DeadInsts.emplace_back(LF.OperandValToReplace); 5284 } 5285 5286 /// Rewrite all the fixup locations with new values, following the chosen 5287 /// solution. 5288 void LSRInstance::ImplementSolution( 5289 const SmallVectorImpl<const Formula *> &Solution) { 5290 // Keep track of instructions we may have made dead, so that 5291 // we can remove them after we are done working. 5292 SmallVector<WeakTrackingVH, 16> DeadInsts; 5293 5294 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(), 5295 "lsr"); 5296 #ifndef NDEBUG 5297 Rewriter.setDebugType(DEBUG_TYPE); 5298 #endif 5299 Rewriter.disableCanonicalMode(); 5300 Rewriter.enableLSRMode(); 5301 Rewriter.setIVIncInsertPos(L, IVIncInsertPos); 5302 5303 // Mark phi nodes that terminate chains so the expander tries to reuse them. 5304 for (const IVChain &Chain : IVChainVec) { 5305 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst())) 5306 Rewriter.setChainedPhi(PN); 5307 } 5308 5309 // Expand the new value definitions and update the users. 5310 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) 5311 for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) { 5312 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts); 5313 Changed = true; 5314 } 5315 5316 for (const IVChain &Chain : IVChainVec) { 5317 GenerateIVChain(Chain, Rewriter, DeadInsts); 5318 Changed = true; 5319 } 5320 // Clean up after ourselves. This must be done before deleting any 5321 // instructions. 5322 Rewriter.clear(); 5323 5324 Changed |= DeleteTriviallyDeadInstructions(DeadInsts); 5325 } 5326 5327 LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, 5328 DominatorTree &DT, LoopInfo &LI, 5329 const TargetTransformInfo &TTI) 5330 : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L) { 5331 // If LoopSimplify form is not available, stay out of trouble. 5332 if (!L->isLoopSimplifyForm()) 5333 return; 5334 5335 // If there's no interesting work to be done, bail early. 5336 if (IU.empty()) return; 5337 5338 // If there's too much analysis to be done, bail early. We won't be able to 5339 // model the problem anyway. 5340 unsigned NumUsers = 0; 5341 for (const IVStrideUse &U : IU) { 5342 if (++NumUsers > MaxIVUsers) { 5343 (void)U; 5344 LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U 5345 << "\n"); 5346 return; 5347 } 5348 // Bail out if we have a PHI on an EHPad that gets a value from a 5349 // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is 5350 // no good place to stick any instructions. 5351 if (auto *PN = dyn_cast<PHINode>(U.getUser())) { 5352 auto *FirstNonPHI = PN->getParent()->getFirstNonPHI(); 5353 if (isa<FuncletPadInst>(FirstNonPHI) || 5354 isa<CatchSwitchInst>(FirstNonPHI)) 5355 for (BasicBlock *PredBB : PN->blocks()) 5356 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI())) 5357 return; 5358 } 5359 } 5360 5361 #ifndef NDEBUG 5362 // All dominating loops must have preheaders, or SCEVExpander may not be able 5363 // to materialize an AddRecExpr whose Start is an outer AddRecExpr. 5364 // 5365 // IVUsers analysis should only create users that are dominated by simple loop 5366 // headers. Since this loop should dominate all of its users, its user list 5367 // should be empty if this loop itself is not within a simple loop nest. 5368 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader()); 5369 Rung; Rung = Rung->getIDom()) { 5370 BasicBlock *BB = Rung->getBlock(); 5371 const Loop *DomLoop = LI.getLoopFor(BB); 5372 if (DomLoop && DomLoop->getHeader() == BB) { 5373 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest"); 5374 } 5375 } 5376 #endif // DEBUG 5377 5378 LLVM_DEBUG(dbgs() << "\nLSR on loop "; 5379 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false); 5380 dbgs() << ":\n"); 5381 5382 // First, perform some low-level loop optimizations. 5383 OptimizeShadowIV(); 5384 OptimizeLoopTermCond(); 5385 5386 // If loop preparation eliminates all interesting IV users, bail. 5387 if (IU.empty()) return; 5388 5389 // Skip nested loops until we can model them better with formulae. 5390 if (!L->empty()) { 5391 LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n"); 5392 return; 5393 } 5394 5395 // Start collecting data and preparing for the solver. 5396 CollectChains(); 5397 CollectInterestingTypesAndFactors(); 5398 CollectFixupsAndInitialFormulae(); 5399 CollectLoopInvariantFixupsAndFormulae(); 5400 5401 assert(!Uses.empty() && "IVUsers reported at least one use"); 5402 LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n"; 5403 print_uses(dbgs())); 5404 5405 // Now use the reuse data to generate a bunch of interesting ways 5406 // to formulate the values needed for the uses. 5407 GenerateAllReuseFormulae(); 5408 5409 FilterOutUndesirableDedicatedRegisters(); 5410 NarrowSearchSpaceUsingHeuristics(); 5411 5412 SmallVector<const Formula *, 8> Solution; 5413 Solve(Solution); 5414 5415 // Release memory that is no longer needed. 5416 Factors.clear(); 5417 Types.clear(); 5418 RegUses.clear(); 5419 5420 if (Solution.empty()) 5421 return; 5422 5423 #ifndef NDEBUG 5424 // Formulae should be legal. 5425 for (const LSRUse &LU : Uses) { 5426 for (const Formula &F : LU.Formulae) 5427 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, 5428 F) && "Illegal formula generated!"); 5429 }; 5430 #endif 5431 5432 // Now that we've decided what we want, make it so. 5433 ImplementSolution(Solution); 5434 } 5435 5436 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 5437 void LSRInstance::print_factors_and_types(raw_ostream &OS) const { 5438 if (Factors.empty() && Types.empty()) return; 5439 5440 OS << "LSR has identified the following interesting factors and types: "; 5441 bool First = true; 5442 5443 for (int64_t Factor : Factors) { 5444 if (!First) OS << ", "; 5445 First = false; 5446 OS << '*' << Factor; 5447 } 5448 5449 for (Type *Ty : Types) { 5450 if (!First) OS << ", "; 5451 First = false; 5452 OS << '(' << *Ty << ')'; 5453 } 5454 OS << '\n'; 5455 } 5456 5457 void LSRInstance::print_fixups(raw_ostream &OS) const { 5458 OS << "LSR is examining the following fixup sites:\n"; 5459 for (const LSRUse &LU : Uses) 5460 for (const LSRFixup &LF : LU.Fixups) { 5461 dbgs() << " "; 5462 LF.print(OS); 5463 OS << '\n'; 5464 } 5465 } 5466 5467 void LSRInstance::print_uses(raw_ostream &OS) const { 5468 OS << "LSR is examining the following uses:\n"; 5469 for (const LSRUse &LU : Uses) { 5470 dbgs() << " "; 5471 LU.print(OS); 5472 OS << '\n'; 5473 for (const Formula &F : LU.Formulae) { 5474 OS << " "; 5475 F.print(OS); 5476 OS << '\n'; 5477 } 5478 } 5479 } 5480 5481 void LSRInstance::print(raw_ostream &OS) const { 5482 print_factors_and_types(OS); 5483 print_fixups(OS); 5484 print_uses(OS); 5485 } 5486 5487 LLVM_DUMP_METHOD void LSRInstance::dump() const { 5488 print(errs()); errs() << '\n'; 5489 } 5490 #endif 5491 5492 namespace { 5493 5494 class LoopStrengthReduce : public LoopPass { 5495 public: 5496 static char ID; // Pass ID, replacement for typeid 5497 5498 LoopStrengthReduce(); 5499 5500 private: 5501 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 5502 void getAnalysisUsage(AnalysisUsage &AU) const override; 5503 }; 5504 5505 } // end anonymous namespace 5506 5507 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) { 5508 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry()); 5509 } 5510 5511 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const { 5512 // We split critical edges, so we change the CFG. However, we do update 5513 // many analyses if they are around. 5514 AU.addPreservedID(LoopSimplifyID); 5515 5516 AU.addRequired<LoopInfoWrapperPass>(); 5517 AU.addPreserved<LoopInfoWrapperPass>(); 5518 AU.addRequiredID(LoopSimplifyID); 5519 AU.addRequired<DominatorTreeWrapperPass>(); 5520 AU.addPreserved<DominatorTreeWrapperPass>(); 5521 AU.addRequired<ScalarEvolutionWrapperPass>(); 5522 AU.addPreserved<ScalarEvolutionWrapperPass>(); 5523 // Requiring LoopSimplify a second time here prevents IVUsers from running 5524 // twice, since LoopSimplify was invalidated by running ScalarEvolution. 5525 AU.addRequiredID(LoopSimplifyID); 5526 AU.addRequired<IVUsersWrapperPass>(); 5527 AU.addPreserved<IVUsersWrapperPass>(); 5528 AU.addRequired<TargetTransformInfoWrapperPass>(); 5529 } 5530 5531 static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE, 5532 DominatorTree &DT, LoopInfo &LI, 5533 const TargetTransformInfo &TTI) { 5534 bool Changed = false; 5535 5536 // Run the main LSR transformation. 5537 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged(); 5538 5539 // Remove any extra phis created by processing inner loops. 5540 Changed |= DeleteDeadPHIs(L->getHeader()); 5541 if (EnablePhiElim && L->isLoopSimplifyForm()) { 5542 SmallVector<WeakTrackingVH, 16> DeadInsts; 5543 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 5544 SCEVExpander Rewriter(SE, DL, "lsr"); 5545 #ifndef NDEBUG 5546 Rewriter.setDebugType(DEBUG_TYPE); 5547 #endif 5548 unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI); 5549 if (numFolded) { 5550 Changed = true; 5551 DeleteTriviallyDeadInstructions(DeadInsts); 5552 DeleteDeadPHIs(L->getHeader()); 5553 } 5554 } 5555 return Changed; 5556 } 5557 5558 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) { 5559 if (skipLoop(L)) 5560 return false; 5561 5562 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU(); 5563 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 5564 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 5565 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 5566 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI( 5567 *L->getHeader()->getParent()); 5568 return ReduceLoopStrength(L, IU, SE, DT, LI, TTI); 5569 } 5570 5571 PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM, 5572 LoopStandardAnalysisResults &AR, 5573 LPMUpdater &) { 5574 if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE, 5575 AR.DT, AR.LI, AR.TTI)) 5576 return PreservedAnalyses::all(); 5577 5578 return getLoopPassPreservedAnalyses(); 5579 } 5580 5581 char LoopStrengthReduce::ID = 0; 5582 5583 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce", 5584 "Loop Strength Reduction", false, false) 5585 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 5586 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 5587 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 5588 INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass) 5589 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 5590 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 5591 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce", 5592 "Loop Strength Reduction", false, false) 5593 5594 Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); } 5595