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