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