1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution expander, 10 // which is used to generate the code corresponding to a given scalar evolution 11 // expression. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/ScopeExit.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Transforms/Utils/LoopUtils.h" 30 31 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS 32 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X) 33 #else 34 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) 35 #endif 36 37 using namespace llvm; 38 39 cl::opt<unsigned> llvm::SCEVCheapExpansionBudget( 40 "scev-cheap-expansion-budget", cl::Hidden, cl::init(4), 41 cl::desc("When performing SCEV expansion only if it is cheap to do, this " 42 "controls the budget that is considered cheap (default = 4)")); 43 44 using namespace PatternMatch; 45 46 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP, 47 /// reusing an existing cast if a suitable one (= dominating IP) exists, or 48 /// creating a new one. 49 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty, 50 Instruction::CastOps Op, 51 BasicBlock::iterator IP) { 52 // This function must be called with the builder having a valid insertion 53 // point. It doesn't need to be the actual IP where the uses of the returned 54 // cast will be added, but it must dominate such IP. 55 // We use this precondition to produce a cast that will dominate all its 56 // uses. In particular, this is crucial for the case where the builder's 57 // insertion point *is* the point where we were asked to put the cast. 58 // Since we don't know the builder's insertion point is actually 59 // where the uses will be added (only that it dominates it), we are 60 // not allowed to move it. 61 BasicBlock::iterator BIP = Builder.GetInsertPoint(); 62 63 Value *Ret = nullptr; 64 65 // Check to see if there is already a cast! 66 for (User *U : V->users()) { 67 if (U->getType() != Ty) 68 continue; 69 CastInst *CI = dyn_cast<CastInst>(U); 70 if (!CI || CI->getOpcode() != Op) 71 continue; 72 73 // Found a suitable cast that is at IP or comes before IP. Use it. Note that 74 // the cast must also properly dominate the Builder's insertion point. 75 if (IP->getParent() == CI->getParent() && &*BIP != CI && 76 (&*IP == CI || CI->comesBefore(&*IP))) { 77 Ret = CI; 78 break; 79 } 80 } 81 82 // Create a new cast. 83 if (!Ret) { 84 SCEVInsertPointGuard Guard(Builder, this); 85 Builder.SetInsertPoint(&*IP); 86 Ret = Builder.CreateCast(Op, V, Ty, V->getName()); 87 } 88 89 // We assert at the end of the function since IP might point to an 90 // instruction with different dominance properties than a cast 91 // (an invoke for example) and not dominate BIP (but the cast does). 92 assert(!isa<Instruction>(Ret) || 93 SE.DT.dominates(cast<Instruction>(Ret), &*BIP)); 94 95 return Ret; 96 } 97 98 BasicBlock::iterator 99 SCEVExpander::findInsertPointAfter(Instruction *I, 100 Instruction *MustDominate) const { 101 BasicBlock::iterator IP = ++I->getIterator(); 102 if (auto *II = dyn_cast<InvokeInst>(I)) 103 IP = II->getNormalDest()->begin(); 104 105 while (isa<PHINode>(IP)) 106 ++IP; 107 108 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) { 109 ++IP; 110 } else if (isa<CatchSwitchInst>(IP)) { 111 IP = MustDominate->getParent()->getFirstInsertionPt(); 112 } else { 113 assert(!IP->isEHPad() && "unexpected eh pad!"); 114 } 115 116 // Adjust insert point to be after instructions inserted by the expander, so 117 // we can re-use already inserted instructions. Avoid skipping past the 118 // original \p MustDominate, in case it is an inserted instruction. 119 while (isInsertedInstruction(&*IP) && &*IP != MustDominate) 120 ++IP; 121 122 return IP; 123 } 124 125 BasicBlock::iterator 126 SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const { 127 // Cast the argument at the beginning of the entry block, after 128 // any bitcasts of other arguments. 129 if (Argument *A = dyn_cast<Argument>(V)) { 130 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin(); 131 while ((isa<BitCastInst>(IP) && 132 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) && 133 cast<BitCastInst>(IP)->getOperand(0) != A) || 134 isa<DbgInfoIntrinsic>(IP)) 135 ++IP; 136 return IP; 137 } 138 139 // Cast the instruction immediately after the instruction. 140 if (Instruction *I = dyn_cast<Instruction>(V)) 141 return findInsertPointAfter(I, &*Builder.GetInsertPoint()); 142 143 // Otherwise, this must be some kind of a constant, 144 // so let's plop this cast into the function's entry block. 145 assert(isa<Constant>(V) && 146 "Expected the cast argument to be a global/constant"); 147 return Builder.GetInsertBlock() 148 ->getParent() 149 ->getEntryBlock() 150 .getFirstInsertionPt(); 151 } 152 153 /// InsertNoopCastOfTo - Insert a cast of V to the specified type, 154 /// which must be possible with a noop cast, doing what we can to share 155 /// the casts. 156 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) { 157 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false); 158 assert((Op == Instruction::BitCast || 159 Op == Instruction::PtrToInt || 160 Op == Instruction::IntToPtr) && 161 "InsertNoopCastOfTo cannot perform non-noop casts!"); 162 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) && 163 "InsertNoopCastOfTo cannot change sizes!"); 164 165 // inttoptr only works for integral pointers. For non-integral pointers, we 166 // can create a GEP on null with the integral value as index. Note that 167 // it is safe to use GEP of null instead of inttoptr here, because only 168 // expressions already based on a GEP of null should be converted to pointers 169 // during expansion. 170 if (Op == Instruction::IntToPtr) { 171 auto *PtrTy = cast<PointerType>(Ty); 172 if (DL.isNonIntegralPointerType(PtrTy)) 173 return Builder.CreatePtrAdd(Constant::getNullValue(PtrTy), V, "scevgep"); 174 } 175 // Short-circuit unnecessary bitcasts. 176 if (Op == Instruction::BitCast) { 177 if (V->getType() == Ty) 178 return V; 179 if (CastInst *CI = dyn_cast<CastInst>(V)) { 180 if (CI->getOperand(0)->getType() == Ty) 181 return CI->getOperand(0); 182 } 183 } 184 // Short-circuit unnecessary inttoptr<->ptrtoint casts. 185 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) && 186 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) { 187 if (CastInst *CI = dyn_cast<CastInst>(V)) 188 if ((CI->getOpcode() == Instruction::PtrToInt || 189 CI->getOpcode() == Instruction::IntToPtr) && 190 SE.getTypeSizeInBits(CI->getType()) == 191 SE.getTypeSizeInBits(CI->getOperand(0)->getType())) 192 return CI->getOperand(0); 193 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 194 if ((CE->getOpcode() == Instruction::PtrToInt || 195 CE->getOpcode() == Instruction::IntToPtr) && 196 SE.getTypeSizeInBits(CE->getType()) == 197 SE.getTypeSizeInBits(CE->getOperand(0)->getType())) 198 return CE->getOperand(0); 199 } 200 201 // Fold a cast of a constant. 202 if (Constant *C = dyn_cast<Constant>(V)) 203 return ConstantExpr::getCast(Op, C, Ty); 204 205 // Try to reuse existing cast, or insert one. 206 return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V)); 207 } 208 209 /// InsertBinop - Insert the specified binary operator, doing a small amount 210 /// of work to avoid inserting an obviously redundant operation, and hoisting 211 /// to an outer loop when the opportunity is there and it is safe. 212 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, 213 Value *LHS, Value *RHS, 214 SCEV::NoWrapFlags Flags, bool IsSafeToHoist) { 215 // Fold a binop with constant operands. 216 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 217 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 218 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL)) 219 return Res; 220 221 // Do a quick scan to see if we have this binop nearby. If so, reuse it. 222 unsigned ScanLimit = 6; 223 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 224 // Scanning starts from the last instruction before the insertion point. 225 BasicBlock::iterator IP = Builder.GetInsertPoint(); 226 if (IP != BlockBegin) { 227 --IP; 228 for (; ScanLimit; --IP, --ScanLimit) { 229 // Don't count dbg.value against the ScanLimit, to avoid perturbing the 230 // generated code. 231 if (isa<DbgInfoIntrinsic>(IP)) 232 ScanLimit++; 233 234 auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) { 235 // Ensure that no-wrap flags match. 236 if (isa<OverflowingBinaryOperator>(I)) { 237 if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW)) 238 return true; 239 if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW)) 240 return true; 241 } 242 // Conservatively, do not use any instruction which has any of exact 243 // flags installed. 244 if (isa<PossiblyExactOperator>(I) && I->isExact()) 245 return true; 246 return false; 247 }; 248 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS && 249 IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP)) 250 return &*IP; 251 if (IP == BlockBegin) break; 252 } 253 } 254 255 // Save the original insertion point so we can restore it when we're done. 256 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc(); 257 SCEVInsertPointGuard Guard(Builder, this); 258 259 if (IsSafeToHoist) { 260 // Move the insertion point out of as many loops as we can. 261 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { 262 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break; 263 BasicBlock *Preheader = L->getLoopPreheader(); 264 if (!Preheader) break; 265 266 // Ok, move up a level. 267 Builder.SetInsertPoint(Preheader->getTerminator()); 268 } 269 } 270 271 // If we haven't found this binop, insert it. 272 // TODO: Use the Builder, which will make CreateBinOp below fold with 273 // InstSimplifyFolder. 274 Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS)); 275 BO->setDebugLoc(Loc); 276 if (Flags & SCEV::FlagNUW) 277 BO->setHasNoUnsignedWrap(); 278 if (Flags & SCEV::FlagNSW) 279 BO->setHasNoSignedWrap(); 280 281 return BO; 282 } 283 284 /// expandAddToGEP - Expand an addition expression with a pointer type into 285 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps 286 /// BasicAliasAnalysis and other passes analyze the result. See the rules 287 /// for getelementptr vs. inttoptr in 288 /// http://llvm.org/docs/LangRef.html#pointeraliasing 289 /// for details. 290 /// 291 /// Design note: The correctness of using getelementptr here depends on 292 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as 293 /// they may introduce pointer arithmetic which may not be safely converted 294 /// into getelementptr. 295 /// 296 /// Design note: It might seem desirable for this function to be more 297 /// loop-aware. If some of the indices are loop-invariant while others 298 /// aren't, it might seem desirable to emit multiple GEPs, keeping the 299 /// loop-invariant portions of the overall computation outside the loop. 300 /// However, there are a few reasons this is not done here. Hoisting simple 301 /// arithmetic is a low-level optimization that often isn't very 302 /// important until late in the optimization process. In fact, passes 303 /// like InstructionCombining will combine GEPs, even if it means 304 /// pushing loop-invariant computation down into loops, so even if the 305 /// GEPs were split here, the work would quickly be undone. The 306 /// LoopStrengthReduction pass, which is usually run quite late (and 307 /// after the last InstructionCombining pass), takes care of hoisting 308 /// loop-invariant portions of expressions, after considering what 309 /// can be folded using target addressing modes. 310 /// 311 Value *SCEVExpander::expandAddToGEP(const SCEV *Offset, Value *V) { 312 assert(!isa<Instruction>(V) || 313 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint())); 314 315 Value *Idx = expand(Offset); 316 317 // Fold a GEP with constant operands. 318 if (Constant *CLHS = dyn_cast<Constant>(V)) 319 if (Constant *CRHS = dyn_cast<Constant>(Idx)) 320 return Builder.CreatePtrAdd(CLHS, CRHS); 321 322 // Do a quick scan to see if we have this GEP nearby. If so, reuse it. 323 unsigned ScanLimit = 6; 324 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 325 // Scanning starts from the last instruction before the insertion point. 326 BasicBlock::iterator IP = Builder.GetInsertPoint(); 327 if (IP != BlockBegin) { 328 --IP; 329 for (; ScanLimit; --IP, --ScanLimit) { 330 // Don't count dbg.value against the ScanLimit, to avoid perturbing the 331 // generated code. 332 if (isa<DbgInfoIntrinsic>(IP)) 333 ScanLimit++; 334 if (IP->getOpcode() == Instruction::GetElementPtr && 335 IP->getOperand(0) == V && IP->getOperand(1) == Idx && 336 cast<GEPOperator>(&*IP)->getSourceElementType() == 337 Builder.getInt8Ty()) 338 return &*IP; 339 if (IP == BlockBegin) break; 340 } 341 } 342 343 // Save the original insertion point so we can restore it when we're done. 344 SCEVInsertPointGuard Guard(Builder, this); 345 346 // Move the insertion point out of as many loops as we can. 347 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) { 348 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break; 349 BasicBlock *Preheader = L->getLoopPreheader(); 350 if (!Preheader) break; 351 352 // Ok, move up a level. 353 Builder.SetInsertPoint(Preheader->getTerminator()); 354 } 355 356 // Emit a GEP. 357 return Builder.CreatePtrAdd(V, Idx, "scevgep"); 358 } 359 360 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for 361 /// SCEV expansion. If they are nested, this is the most nested. If they are 362 /// neighboring, pick the later. 363 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B, 364 DominatorTree &DT) { 365 if (!A) return B; 366 if (!B) return A; 367 if (A->contains(B)) return B; 368 if (B->contains(A)) return A; 369 if (DT.dominates(A->getHeader(), B->getHeader())) return B; 370 if (DT.dominates(B->getHeader(), A->getHeader())) return A; 371 return A; // Arbitrarily break the tie. 372 } 373 374 /// getRelevantLoop - Get the most relevant loop associated with the given 375 /// expression, according to PickMostRelevantLoop. 376 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) { 377 // Test whether we've already computed the most relevant loop for this SCEV. 378 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr)); 379 if (!Pair.second) 380 return Pair.first->second; 381 382 switch (S->getSCEVType()) { 383 case scConstant: 384 case scVScale: 385 return nullptr; // A constant has no relevant loops. 386 case scTruncate: 387 case scZeroExtend: 388 case scSignExtend: 389 case scPtrToInt: 390 case scAddExpr: 391 case scMulExpr: 392 case scUDivExpr: 393 case scAddRecExpr: 394 case scUMaxExpr: 395 case scSMaxExpr: 396 case scUMinExpr: 397 case scSMinExpr: 398 case scSequentialUMinExpr: { 399 const Loop *L = nullptr; 400 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 401 L = AR->getLoop(); 402 for (const SCEV *Op : S->operands()) 403 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT); 404 return RelevantLoops[S] = L; 405 } 406 case scUnknown: { 407 const SCEVUnknown *U = cast<SCEVUnknown>(S); 408 if (const Instruction *I = dyn_cast<Instruction>(U->getValue())) 409 return Pair.first->second = SE.LI.getLoopFor(I->getParent()); 410 // A non-instruction has no relevant loops. 411 return nullptr; 412 } 413 case scCouldNotCompute: 414 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 415 } 416 llvm_unreachable("Unexpected SCEV type!"); 417 } 418 419 namespace { 420 421 /// LoopCompare - Compare loops by PickMostRelevantLoop. 422 class LoopCompare { 423 DominatorTree &DT; 424 public: 425 explicit LoopCompare(DominatorTree &dt) : DT(dt) {} 426 427 bool operator()(std::pair<const Loop *, const SCEV *> LHS, 428 std::pair<const Loop *, const SCEV *> RHS) const { 429 // Keep pointer operands sorted at the end. 430 if (LHS.second->getType()->isPointerTy() != 431 RHS.second->getType()->isPointerTy()) 432 return LHS.second->getType()->isPointerTy(); 433 434 // Compare loops with PickMostRelevantLoop. 435 if (LHS.first != RHS.first) 436 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first; 437 438 // If one operand is a non-constant negative and the other is not, 439 // put the non-constant negative on the right so that a sub can 440 // be used instead of a negate and add. 441 if (LHS.second->isNonConstantNegative()) { 442 if (!RHS.second->isNonConstantNegative()) 443 return false; 444 } else if (RHS.second->isNonConstantNegative()) 445 return true; 446 447 // Otherwise they are equivalent according to this comparison. 448 return false; 449 } 450 }; 451 452 } 453 454 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) { 455 // Collect all the add operands in a loop, along with their associated loops. 456 // Iterate in reverse so that constants are emitted last, all else equal, and 457 // so that pointer operands are inserted first, which the code below relies on 458 // to form more involved GEPs. 459 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; 460 for (const SCEV *Op : reverse(S->operands())) 461 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op)); 462 463 // Sort by loop. Use a stable sort so that constants follow non-constants and 464 // pointer operands precede non-pointer operands. 465 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT)); 466 467 // Emit instructions to add all the operands. Hoist as much as possible 468 // out of loops, and form meaningful getelementptrs where possible. 469 Value *Sum = nullptr; 470 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) { 471 const Loop *CurLoop = I->first; 472 const SCEV *Op = I->second; 473 if (!Sum) { 474 // This is the first operand. Just expand it. 475 Sum = expand(Op); 476 ++I; 477 continue; 478 } 479 480 assert(!Op->getType()->isPointerTy() && "Only first op can be pointer"); 481 if (isa<PointerType>(Sum->getType())) { 482 // The running sum expression is a pointer. Try to form a getelementptr 483 // at this level with that as the base. 484 SmallVector<const SCEV *, 4> NewOps; 485 for (; I != E && I->first == CurLoop; ++I) { 486 // If the operand is SCEVUnknown and not instructions, peek through 487 // it, to enable more of it to be folded into the GEP. 488 const SCEV *X = I->second; 489 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X)) 490 if (!isa<Instruction>(U->getValue())) 491 X = SE.getSCEV(U->getValue()); 492 NewOps.push_back(X); 493 } 494 Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum); 495 } else if (Op->isNonConstantNegative()) { 496 // Instead of doing a negate and add, just do a subtract. 497 Value *W = expand(SE.getNegativeSCEV(Op)); 498 Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap, 499 /*IsSafeToHoist*/ true); 500 ++I; 501 } else { 502 // A simple add. 503 Value *W = expand(Op); 504 // Canonicalize a constant to the RHS. 505 if (isa<Constant>(Sum)) 506 std::swap(Sum, W); 507 Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(), 508 /*IsSafeToHoist*/ true); 509 ++I; 510 } 511 } 512 513 return Sum; 514 } 515 516 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) { 517 Type *Ty = S->getType(); 518 519 // Collect all the mul operands in a loop, along with their associated loops. 520 // Iterate in reverse so that constants are emitted last, all else equal. 521 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; 522 for (const SCEV *Op : reverse(S->operands())) 523 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op)); 524 525 // Sort by loop. Use a stable sort so that constants follow non-constants. 526 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT)); 527 528 // Emit instructions to mul all the operands. Hoist as much as possible 529 // out of loops. 530 Value *Prod = nullptr; 531 auto I = OpsAndLoops.begin(); 532 533 // Expand the calculation of X pow N in the following manner: 534 // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then: 535 // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK). 536 const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() { 537 auto E = I; 538 // Calculate how many times the same operand from the same loop is included 539 // into this power. 540 uint64_t Exponent = 0; 541 const uint64_t MaxExponent = UINT64_MAX >> 1; 542 // No one sane will ever try to calculate such huge exponents, but if we 543 // need this, we stop on UINT64_MAX / 2 because we need to exit the loop 544 // below when the power of 2 exceeds our Exponent, and we want it to be 545 // 1u << 31 at most to not deal with unsigned overflow. 546 while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) { 547 ++Exponent; 548 ++E; 549 } 550 assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?"); 551 552 // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them 553 // that are needed into the result. 554 Value *P = expand(I->second); 555 Value *Result = nullptr; 556 if (Exponent & 1) 557 Result = P; 558 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) { 559 P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap, 560 /*IsSafeToHoist*/ true); 561 if (Exponent & BinExp) 562 Result = Result ? InsertBinop(Instruction::Mul, Result, P, 563 SCEV::FlagAnyWrap, 564 /*IsSafeToHoist*/ true) 565 : P; 566 } 567 568 I = E; 569 assert(Result && "Nothing was expanded?"); 570 return Result; 571 }; 572 573 while (I != OpsAndLoops.end()) { 574 if (!Prod) { 575 // This is the first operand. Just expand it. 576 Prod = ExpandOpBinPowN(); 577 } else if (I->second->isAllOnesValue()) { 578 // Instead of doing a multiply by negative one, just do a negate. 579 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod, 580 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true); 581 ++I; 582 } else { 583 // A simple mul. 584 Value *W = ExpandOpBinPowN(); 585 // Canonicalize a constant to the RHS. 586 if (isa<Constant>(Prod)) std::swap(Prod, W); 587 const APInt *RHS; 588 if (match(W, m_Power2(RHS))) { 589 // Canonicalize Prod*(1<<C) to Prod<<C. 590 assert(!Ty->isVectorTy() && "vector types are not SCEVable"); 591 auto NWFlags = S->getNoWrapFlags(); 592 // clear nsw flag if shl will produce poison value. 593 if (RHS->logBase2() == RHS->getBitWidth() - 1) 594 NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW); 595 Prod = InsertBinop(Instruction::Shl, Prod, 596 ConstantInt::get(Ty, RHS->logBase2()), NWFlags, 597 /*IsSafeToHoist*/ true); 598 } else { 599 Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(), 600 /*IsSafeToHoist*/ true); 601 } 602 } 603 } 604 605 return Prod; 606 } 607 608 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) { 609 Value *LHS = expand(S->getLHS()); 610 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) { 611 const APInt &RHS = SC->getAPInt(); 612 if (RHS.isPowerOf2()) 613 return InsertBinop(Instruction::LShr, LHS, 614 ConstantInt::get(SC->getType(), RHS.logBase2()), 615 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true); 616 } 617 618 Value *RHS = expand(S->getRHS()); 619 return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap, 620 /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS())); 621 } 622 623 /// Determine if this is a well-behaved chain of instructions leading back to 624 /// the PHI. If so, it may be reused by expanded expressions. 625 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, 626 const Loop *L) { 627 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) || 628 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV))) 629 return false; 630 // If any of the operands don't dominate the insert position, bail. 631 // Addrec operands are always loop-invariant, so this can only happen 632 // if there are instructions which haven't been hoisted. 633 if (L == IVIncInsertLoop) { 634 for (Use &Op : llvm::drop_begin(IncV->operands())) 635 if (Instruction *OInst = dyn_cast<Instruction>(Op)) 636 if (!SE.DT.dominates(OInst, IVIncInsertPos)) 637 return false; 638 } 639 // Advance to the next instruction. 640 IncV = dyn_cast<Instruction>(IncV->getOperand(0)); 641 if (!IncV) 642 return false; 643 644 if (IncV->mayHaveSideEffects()) 645 return false; 646 647 if (IncV == PN) 648 return true; 649 650 return isNormalAddRecExprPHI(PN, IncV, L); 651 } 652 653 /// getIVIncOperand returns an induction variable increment's induction 654 /// variable operand. 655 /// 656 /// If allowScale is set, any type of GEP is allowed as long as the nonIV 657 /// operands dominate InsertPos. 658 /// 659 /// If allowScale is not set, ensure that a GEP increment conforms to one of the 660 /// simple patterns generated by getAddRecExprPHILiterally and 661 /// expandAddtoGEP. If the pattern isn't recognized, return NULL. 662 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV, 663 Instruction *InsertPos, 664 bool allowScale) { 665 if (IncV == InsertPos) 666 return nullptr; 667 668 switch (IncV->getOpcode()) { 669 default: 670 return nullptr; 671 // Check for a simple Add/Sub or GEP of a loop invariant step. 672 case Instruction::Add: 673 case Instruction::Sub: { 674 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1)); 675 if (!OInst || SE.DT.dominates(OInst, InsertPos)) 676 return dyn_cast<Instruction>(IncV->getOperand(0)); 677 return nullptr; 678 } 679 case Instruction::BitCast: 680 return dyn_cast<Instruction>(IncV->getOperand(0)); 681 case Instruction::GetElementPtr: 682 for (Use &U : llvm::drop_begin(IncV->operands())) { 683 if (isa<Constant>(U)) 684 continue; 685 if (Instruction *OInst = dyn_cast<Instruction>(U)) { 686 if (!SE.DT.dominates(OInst, InsertPos)) 687 return nullptr; 688 } 689 if (allowScale) { 690 // allow any kind of GEP as long as it can be hoisted. 691 continue; 692 } 693 // GEPs produced by SCEVExpander use i8 element type. 694 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8)) 695 return nullptr; 696 break; 697 } 698 return dyn_cast<Instruction>(IncV->getOperand(0)); 699 } 700 } 701 702 /// If the insert point of the current builder or any of the builders on the 703 /// stack of saved builders has 'I' as its insert point, update it to point to 704 /// the instruction after 'I'. This is intended to be used when the instruction 705 /// 'I' is being moved. If this fixup is not done and 'I' is moved to a 706 /// different block, the inconsistent insert point (with a mismatched 707 /// Instruction and Block) can lead to an instruction being inserted in a block 708 /// other than its parent. 709 void SCEVExpander::fixupInsertPoints(Instruction *I) { 710 BasicBlock::iterator It(*I); 711 BasicBlock::iterator NewInsertPt = std::next(It); 712 if (Builder.GetInsertPoint() == It) 713 Builder.SetInsertPoint(&*NewInsertPt); 714 for (auto *InsertPtGuard : InsertPointGuards) 715 if (InsertPtGuard->GetInsertPoint() == It) 716 InsertPtGuard->SetInsertPoint(NewInsertPt); 717 } 718 719 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make 720 /// it available to other uses in this loop. Recursively hoist any operands, 721 /// until we reach a value that dominates InsertPos. 722 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos, 723 bool RecomputePoisonFlags) { 724 auto FixupPoisonFlags = [this](Instruction *I) { 725 // Drop flags that are potentially inferred from old context and infer flags 726 // in new context. 727 I->dropPoisonGeneratingFlags(); 728 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) 729 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) { 730 auto *BO = cast<BinaryOperator>(I); 731 BO->setHasNoUnsignedWrap( 732 ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW); 733 BO->setHasNoSignedWrap( 734 ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW); 735 } 736 }; 737 738 if (SE.DT.dominates(IncV, InsertPos)) { 739 if (RecomputePoisonFlags) 740 FixupPoisonFlags(IncV); 741 return true; 742 } 743 744 // InsertPos must itself dominate IncV so that IncV's new position satisfies 745 // its existing users. 746 if (isa<PHINode>(InsertPos) || 747 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent())) 748 return false; 749 750 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos)) 751 return false; 752 753 // Check that the chain of IV operands leading back to Phi can be hoisted. 754 SmallVector<Instruction*, 4> IVIncs; 755 for(;;) { 756 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true); 757 if (!Oper) 758 return false; 759 // IncV is safe to hoist. 760 IVIncs.push_back(IncV); 761 IncV = Oper; 762 if (SE.DT.dominates(IncV, InsertPos)) 763 break; 764 } 765 for (Instruction *I : llvm::reverse(IVIncs)) { 766 fixupInsertPoints(I); 767 I->moveBefore(InsertPos); 768 if (RecomputePoisonFlags) 769 FixupPoisonFlags(I); 770 } 771 return true; 772 } 773 774 /// Determine if this cyclic phi is in a form that would have been generated by 775 /// LSR. We don't care if the phi was actually expanded in this pass, as long 776 /// as it is in a low-cost form, for example, no implied multiplication. This 777 /// should match any patterns generated by getAddRecExprPHILiterally and 778 /// expandAddtoGEP. 779 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, 780 const Loop *L) { 781 for(Instruction *IVOper = IncV; 782 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(), 783 /*allowScale=*/false));) { 784 if (IVOper == PN) 785 return true; 786 } 787 return false; 788 } 789 790 /// expandIVInc - Expand an IV increment at Builder's current InsertPos. 791 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may 792 /// need to materialize IV increments elsewhere to handle difficult situations. 793 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L, 794 bool useSubtract) { 795 Value *IncV; 796 // If the PHI is a pointer, use a GEP, otherwise use an add or sub. 797 if (PN->getType()->isPointerTy()) { 798 IncV = expandAddToGEP(SE.getSCEV(StepV), PN); 799 } else { 800 IncV = useSubtract ? 801 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") : 802 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next"); 803 } 804 return IncV; 805 } 806 807 /// Check whether we can cheaply express the requested SCEV in terms of 808 /// the available PHI SCEV by truncation and/or inversion of the step. 809 static bool canBeCheaplyTransformed(ScalarEvolution &SE, 810 const SCEVAddRecExpr *Phi, 811 const SCEVAddRecExpr *Requested, 812 bool &InvertStep) { 813 // We can't transform to match a pointer PHI. 814 Type *PhiTy = Phi->getType(); 815 Type *RequestedTy = Requested->getType(); 816 if (PhiTy->isPointerTy() || RequestedTy->isPointerTy()) 817 return false; 818 819 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth()) 820 return false; 821 822 // Try truncate it if necessary. 823 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy)); 824 if (!Phi) 825 return false; 826 827 // Check whether truncation will help. 828 if (Phi == Requested) { 829 InvertStep = false; 830 return true; 831 } 832 833 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}. 834 if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) { 835 InvertStep = true; 836 return true; 837 } 838 839 return false; 840 } 841 842 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) { 843 if (!isa<IntegerType>(AR->getType())) 844 return false; 845 846 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth(); 847 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2); 848 const SCEV *Step = AR->getStepRecurrence(SE); 849 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy), 850 SE.getSignExtendExpr(AR, WideTy)); 851 const SCEV *ExtendAfterOp = 852 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy); 853 return ExtendAfterOp == OpAfterExtend; 854 } 855 856 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) { 857 if (!isa<IntegerType>(AR->getType())) 858 return false; 859 860 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth(); 861 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2); 862 const SCEV *Step = AR->getStepRecurrence(SE); 863 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy), 864 SE.getZeroExtendExpr(AR, WideTy)); 865 const SCEV *ExtendAfterOp = 866 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy); 867 return ExtendAfterOp == OpAfterExtend; 868 } 869 870 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand 871 /// the base addrec, which is the addrec without any non-loop-dominating 872 /// values, and return the PHI. 873 PHINode * 874 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized, 875 const Loop *L, Type *&TruncTy, 876 bool &InvertStep) { 877 assert((!IVIncInsertLoop || IVIncInsertPos) && 878 "Uninitialized insert position"); 879 880 // Reuse a previously-inserted PHI, if present. 881 BasicBlock *LatchBlock = L->getLoopLatch(); 882 if (LatchBlock) { 883 PHINode *AddRecPhiMatch = nullptr; 884 Instruction *IncV = nullptr; 885 TruncTy = nullptr; 886 InvertStep = false; 887 888 // Only try partially matching scevs that need truncation and/or 889 // step-inversion if we know this loop is outside the current loop. 890 bool TryNonMatchingSCEV = 891 IVIncInsertLoop && 892 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader()); 893 894 for (PHINode &PN : L->getHeader()->phis()) { 895 if (!SE.isSCEVable(PN.getType())) 896 continue; 897 898 // We should not look for a incomplete PHI. Getting SCEV for a incomplete 899 // PHI has no meaning at all. 900 if (!PN.isComplete()) { 901 SCEV_DEBUG_WITH_TYPE( 902 DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n"); 903 continue; 904 } 905 906 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN)); 907 if (!PhiSCEV) 908 continue; 909 910 bool IsMatchingSCEV = PhiSCEV == Normalized; 911 // We only handle truncation and inversion of phi recurrences for the 912 // expanded expression if the expanded expression's loop dominates the 913 // loop we insert to. Check now, so we can bail out early. 914 if (!IsMatchingSCEV && !TryNonMatchingSCEV) 915 continue; 916 917 // TODO: this possibly can be reworked to avoid this cast at all. 918 Instruction *TempIncV = 919 dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock)); 920 if (!TempIncV) 921 continue; 922 923 // Check whether we can reuse this PHI node. 924 if (LSRMode) { 925 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L)) 926 continue; 927 } else { 928 if (!isNormalAddRecExprPHI(&PN, TempIncV, L)) 929 continue; 930 } 931 932 // Stop if we have found an exact match SCEV. 933 if (IsMatchingSCEV) { 934 IncV = TempIncV; 935 TruncTy = nullptr; 936 InvertStep = false; 937 AddRecPhiMatch = &PN; 938 break; 939 } 940 941 // Try whether the phi can be translated into the requested form 942 // (truncated and/or offset by a constant). 943 if ((!TruncTy || InvertStep) && 944 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) { 945 // Record the phi node. But don't stop we might find an exact match 946 // later. 947 AddRecPhiMatch = &PN; 948 IncV = TempIncV; 949 TruncTy = Normalized->getType(); 950 } 951 } 952 953 if (AddRecPhiMatch) { 954 // Ok, the add recurrence looks usable. 955 // Remember this PHI, even in post-inc mode. 956 InsertedValues.insert(AddRecPhiMatch); 957 // Remember the increment. 958 rememberInstruction(IncV); 959 // Those values were not actually inserted but re-used. 960 ReusedValues.insert(AddRecPhiMatch); 961 ReusedValues.insert(IncV); 962 return AddRecPhiMatch; 963 } 964 } 965 966 // Save the original insertion point so we can restore it when we're done. 967 SCEVInsertPointGuard Guard(Builder, this); 968 969 // Another AddRec may need to be recursively expanded below. For example, if 970 // this AddRec is quadratic, the StepV may itself be an AddRec in this 971 // loop. Remove this loop from the PostIncLoops set before expanding such 972 // AddRecs. Otherwise, we cannot find a valid position for the step 973 // (i.e. StepV can never dominate its loop header). Ideally, we could do 974 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element, 975 // so it's not worth implementing SmallPtrSet::swap. 976 PostIncLoopSet SavedPostIncLoops = PostIncLoops; 977 PostIncLoops.clear(); 978 979 // Expand code for the start value into the loop preheader. 980 assert(L->getLoopPreheader() && 981 "Can't expand add recurrences without a loop preheader!"); 982 Value *StartV = 983 expand(Normalized->getStart(), L->getLoopPreheader()->getTerminator()); 984 985 // StartV must have been be inserted into L's preheader to dominate the new 986 // phi. 987 assert(!isa<Instruction>(StartV) || 988 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(), 989 L->getHeader())); 990 991 // Expand code for the step value. Do this before creating the PHI so that PHI 992 // reuse code doesn't see an incomplete PHI. 993 const SCEV *Step = Normalized->getStepRecurrence(SE); 994 Type *ExpandTy = Normalized->getType(); 995 // If the stride is negative, insert a sub instead of an add for the increment 996 // (unless it's a constant, because subtracts of constants are canonicalized 997 // to adds). 998 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative(); 999 if (useSubtract) 1000 Step = SE.getNegativeSCEV(Step); 1001 // Expand the step somewhere that dominates the loop header. 1002 Value *StepV = expand(Step, L->getHeader()->getFirstInsertionPt()); 1003 1004 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if 1005 // we actually do emit an addition. It does not apply if we emit a 1006 // subtraction. 1007 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized); 1008 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized); 1009 1010 // Create the PHI. 1011 BasicBlock *Header = L->getHeader(); 1012 Builder.SetInsertPoint(Header, Header->begin()); 1013 PHINode *PN = 1014 Builder.CreatePHI(ExpandTy, pred_size(Header), Twine(IVName) + ".iv"); 1015 1016 // Create the step instructions and populate the PHI. 1017 for (BasicBlock *Pred : predecessors(Header)) { 1018 // Add a start value. 1019 if (!L->contains(Pred)) { 1020 PN->addIncoming(StartV, Pred); 1021 continue; 1022 } 1023 1024 // Create a step value and add it to the PHI. 1025 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the 1026 // instructions at IVIncInsertPos. 1027 Instruction *InsertPos = L == IVIncInsertLoop ? 1028 IVIncInsertPos : Pred->getTerminator(); 1029 Builder.SetInsertPoint(InsertPos); 1030 Value *IncV = expandIVInc(PN, StepV, L, useSubtract); 1031 1032 if (isa<OverflowingBinaryOperator>(IncV)) { 1033 if (IncrementIsNUW) 1034 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap(); 1035 if (IncrementIsNSW) 1036 cast<BinaryOperator>(IncV)->setHasNoSignedWrap(); 1037 } 1038 PN->addIncoming(IncV, Pred); 1039 } 1040 1041 // After expanding subexpressions, restore the PostIncLoops set so the caller 1042 // can ensure that IVIncrement dominates the current uses. 1043 PostIncLoops = SavedPostIncLoops; 1044 1045 // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most 1046 // effective when we are able to use an IV inserted here, so record it. 1047 InsertedValues.insert(PN); 1048 InsertedIVs.push_back(PN); 1049 return PN; 1050 } 1051 1052 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) { 1053 const Loop *L = S->getLoop(); 1054 1055 // Determine a normalized form of this expression, which is the expression 1056 // before any post-inc adjustment is made. 1057 const SCEVAddRecExpr *Normalized = S; 1058 if (PostIncLoops.count(L)) { 1059 PostIncLoopSet Loops; 1060 Loops.insert(L); 1061 Normalized = cast<SCEVAddRecExpr>( 1062 normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false)); 1063 } 1064 1065 [[maybe_unused]] const SCEV *Start = Normalized->getStart(); 1066 const SCEV *Step = Normalized->getStepRecurrence(SE); 1067 assert(SE.properlyDominates(Start, L->getHeader()) && 1068 "Start does not properly dominate loop header"); 1069 assert(SE.dominates(Step, L->getHeader()) && "Step not dominate loop header"); 1070 1071 // In some cases, we decide to reuse an existing phi node but need to truncate 1072 // it and/or invert the step. 1073 Type *TruncTy = nullptr; 1074 bool InvertStep = false; 1075 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep); 1076 1077 // Accommodate post-inc mode, if necessary. 1078 Value *Result; 1079 if (!PostIncLoops.count(L)) 1080 Result = PN; 1081 else { 1082 // In PostInc mode, use the post-incremented value. 1083 BasicBlock *LatchBlock = L->getLoopLatch(); 1084 assert(LatchBlock && "PostInc mode requires a unique loop latch!"); 1085 Result = PN->getIncomingValueForBlock(LatchBlock); 1086 1087 // We might be introducing a new use of the post-inc IV that is not poison 1088 // safe, in which case we should drop poison generating flags. Only keep 1089 // those flags for which SCEV has proven that they always hold. 1090 if (isa<OverflowingBinaryOperator>(Result)) { 1091 auto *I = cast<Instruction>(Result); 1092 if (!S->hasNoUnsignedWrap()) 1093 I->setHasNoUnsignedWrap(false); 1094 if (!S->hasNoSignedWrap()) 1095 I->setHasNoSignedWrap(false); 1096 } 1097 1098 // For an expansion to use the postinc form, the client must call 1099 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop 1100 // or dominated by IVIncInsertPos. 1101 if (isa<Instruction>(Result) && 1102 !SE.DT.dominates(cast<Instruction>(Result), 1103 &*Builder.GetInsertPoint())) { 1104 // The induction variable's postinc expansion does not dominate this use. 1105 // IVUsers tries to prevent this case, so it is rare. However, it can 1106 // happen when an IVUser outside the loop is not dominated by the latch 1107 // block. Adjusting IVIncInsertPos before expansion begins cannot handle 1108 // all cases. Consider a phi outside whose operand is replaced during 1109 // expansion with the value of the postinc user. Without fundamentally 1110 // changing the way postinc users are tracked, the only remedy is 1111 // inserting an extra IV increment. StepV might fold into PostLoopOffset, 1112 // but hopefully expandCodeFor handles that. 1113 bool useSubtract = 1114 !S->getType()->isPointerTy() && Step->isNonConstantNegative(); 1115 if (useSubtract) 1116 Step = SE.getNegativeSCEV(Step); 1117 Value *StepV; 1118 { 1119 // Expand the step somewhere that dominates the loop header. 1120 SCEVInsertPointGuard Guard(Builder, this); 1121 StepV = expand(Step, L->getHeader()->getFirstInsertionPt()); 1122 } 1123 Result = expandIVInc(PN, StepV, L, useSubtract); 1124 } 1125 } 1126 1127 // We have decided to reuse an induction variable of a dominating loop. Apply 1128 // truncation and/or inversion of the step. 1129 if (TruncTy) { 1130 // Truncate the result. 1131 if (TruncTy != Result->getType()) 1132 Result = Builder.CreateTrunc(Result, TruncTy); 1133 1134 // Invert the result. 1135 if (InvertStep) 1136 Result = Builder.CreateSub(expand(Normalized->getStart()), Result); 1137 } 1138 1139 return Result; 1140 } 1141 1142 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) { 1143 // In canonical mode we compute the addrec as an expression of a canonical IV 1144 // using evaluateAtIteration and expand the resulting SCEV expression. This 1145 // way we avoid introducing new IVs to carry on the computation of the addrec 1146 // throughout the loop. 1147 // 1148 // For nested addrecs evaluateAtIteration might need a canonical IV of a 1149 // type wider than the addrec itself. Emitting a canonical IV of the 1150 // proper type might produce non-legal types, for example expanding an i64 1151 // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall 1152 // back to non-canonical mode for nested addrecs. 1153 if (!CanonicalMode || (S->getNumOperands() > 2)) 1154 return expandAddRecExprLiterally(S); 1155 1156 Type *Ty = SE.getEffectiveSCEVType(S->getType()); 1157 const Loop *L = S->getLoop(); 1158 1159 // First check for an existing canonical IV in a suitable type. 1160 PHINode *CanonicalIV = nullptr; 1161 if (PHINode *PN = L->getCanonicalInductionVariable()) 1162 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty)) 1163 CanonicalIV = PN; 1164 1165 // Rewrite an AddRec in terms of the canonical induction variable, if 1166 // its type is more narrow. 1167 if (CanonicalIV && 1168 SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) && 1169 !S->getType()->isPointerTy()) { 1170 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands()); 1171 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i) 1172 NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType()); 1173 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(), 1174 S->getNoWrapFlags(SCEV::FlagNW))); 1175 BasicBlock::iterator NewInsertPt = 1176 findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint()); 1177 V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt); 1178 return V; 1179 } 1180 1181 // {X,+,F} --> X + {0,+,F} 1182 if (!S->getStart()->isZero()) { 1183 if (isa<PointerType>(S->getType())) { 1184 Value *StartV = expand(SE.getPointerBase(S)); 1185 return expandAddToGEP(SE.removePointerBase(S), StartV); 1186 } 1187 1188 SmallVector<const SCEV *, 4> NewOps(S->operands()); 1189 NewOps[0] = SE.getConstant(Ty, 0); 1190 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, 1191 S->getNoWrapFlags(SCEV::FlagNW)); 1192 1193 // Just do a normal add. Pre-expand the operands to suppress folding. 1194 // 1195 // The LHS and RHS values are factored out of the expand call to make the 1196 // output independent of the argument evaluation order. 1197 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart())); 1198 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest)); 1199 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS)); 1200 } 1201 1202 // If we don't yet have a canonical IV, create one. 1203 if (!CanonicalIV) { 1204 // Create and insert the PHI node for the induction variable in the 1205 // specified loop. 1206 BasicBlock *Header = L->getHeader(); 1207 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header); 1208 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar"); 1209 CanonicalIV->insertBefore(Header->begin()); 1210 rememberInstruction(CanonicalIV); 1211 1212 SmallSet<BasicBlock *, 4> PredSeen; 1213 Constant *One = ConstantInt::get(Ty, 1); 1214 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) { 1215 BasicBlock *HP = *HPI; 1216 if (!PredSeen.insert(HP).second) { 1217 // There must be an incoming value for each predecessor, even the 1218 // duplicates! 1219 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP); 1220 continue; 1221 } 1222 1223 if (L->contains(HP)) { 1224 // Insert a unit add instruction right before the terminator 1225 // corresponding to the back-edge. 1226 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One, 1227 "indvar.next", 1228 HP->getTerminator()); 1229 Add->setDebugLoc(HP->getTerminator()->getDebugLoc()); 1230 rememberInstruction(Add); 1231 CanonicalIV->addIncoming(Add, HP); 1232 } else { 1233 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP); 1234 } 1235 } 1236 } 1237 1238 // {0,+,1} --> Insert a canonical induction variable into the loop! 1239 if (S->isAffine() && S->getOperand(1)->isOne()) { 1240 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) && 1241 "IVs with types different from the canonical IV should " 1242 "already have been handled!"); 1243 return CanonicalIV; 1244 } 1245 1246 // {0,+,F} --> {0,+,1} * F 1247 1248 // If this is a simple linear addrec, emit it now as a special case. 1249 if (S->isAffine()) // {0,+,F} --> i*F 1250 return 1251 expand(SE.getTruncateOrNoop( 1252 SE.getMulExpr(SE.getUnknown(CanonicalIV), 1253 SE.getNoopOrAnyExtend(S->getOperand(1), 1254 CanonicalIV->getType())), 1255 Ty)); 1256 1257 // If this is a chain of recurrences, turn it into a closed form, using the 1258 // folders, then expandCodeFor the closed form. This allows the folders to 1259 // simplify the expression without having to build a bunch of special code 1260 // into this folder. 1261 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV. 1262 1263 // Promote S up to the canonical IV type, if the cast is foldable. 1264 const SCEV *NewS = S; 1265 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType()); 1266 if (isa<SCEVAddRecExpr>(Ext)) 1267 NewS = Ext; 1268 1269 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE); 1270 1271 // Truncate the result down to the original type, if needed. 1272 const SCEV *T = SE.getTruncateOrNoop(V, Ty); 1273 return expand(T); 1274 } 1275 1276 Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) { 1277 Value *V = expand(S->getOperand()); 1278 return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt, 1279 GetOptimalInsertionPointForCastOf(V)); 1280 } 1281 1282 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) { 1283 Value *V = expand(S->getOperand()); 1284 return Builder.CreateTrunc(V, S->getType()); 1285 } 1286 1287 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) { 1288 Value *V = expand(S->getOperand()); 1289 return Builder.CreateZExt(V, S->getType(), "", 1290 SE.isKnownNonNegative(S->getOperand())); 1291 } 1292 1293 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) { 1294 Value *V = expand(S->getOperand()); 1295 return Builder.CreateSExt(V, S->getType()); 1296 } 1297 1298 Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S, 1299 Intrinsic::ID IntrinID, Twine Name, 1300 bool IsSequential) { 1301 Value *LHS = expand(S->getOperand(S->getNumOperands() - 1)); 1302 Type *Ty = LHS->getType(); 1303 if (IsSequential) 1304 LHS = Builder.CreateFreeze(LHS); 1305 for (int i = S->getNumOperands() - 2; i >= 0; --i) { 1306 Value *RHS = expand(S->getOperand(i)); 1307 if (IsSequential && i != 0) 1308 RHS = Builder.CreateFreeze(RHS); 1309 Value *Sel; 1310 if (Ty->isIntegerTy()) 1311 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS}, 1312 /*FMFSource=*/nullptr, Name); 1313 else { 1314 Value *ICmp = 1315 Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS); 1316 Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name); 1317 } 1318 LHS = Sel; 1319 } 1320 return LHS; 1321 } 1322 1323 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) { 1324 return expandMinMaxExpr(S, Intrinsic::smax, "smax"); 1325 } 1326 1327 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) { 1328 return expandMinMaxExpr(S, Intrinsic::umax, "umax"); 1329 } 1330 1331 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) { 1332 return expandMinMaxExpr(S, Intrinsic::smin, "smin"); 1333 } 1334 1335 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) { 1336 return expandMinMaxExpr(S, Intrinsic::umin, "umin"); 1337 } 1338 1339 Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) { 1340 return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true); 1341 } 1342 1343 Value *SCEVExpander::visitVScale(const SCEVVScale *S) { 1344 return Builder.CreateVScale(ConstantInt::get(S->getType(), 1)); 1345 } 1346 1347 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty, 1348 BasicBlock::iterator IP) { 1349 setInsertPoint(IP); 1350 Value *V = expandCodeFor(SH, Ty); 1351 return V; 1352 } 1353 1354 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) { 1355 // Expand the code for this SCEV. 1356 Value *V = expand(SH); 1357 1358 if (Ty) { 1359 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) && 1360 "non-trivial casts should be done with the SCEVs directly!"); 1361 V = InsertNoopCastOfTo(V, Ty); 1362 } 1363 return V; 1364 } 1365 1366 Value *SCEVExpander::FindValueInExprValueMap( 1367 const SCEV *S, const Instruction *InsertPt, 1368 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) { 1369 // If the expansion is not in CanonicalMode, and the SCEV contains any 1370 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally. 1371 if (!CanonicalMode && SE.containsAddRecurrence(S)) 1372 return nullptr; 1373 1374 // If S is a constant, it may be worse to reuse an existing Value. 1375 if (isa<SCEVConstant>(S)) 1376 return nullptr; 1377 1378 for (Value *V : SE.getSCEVValues(S)) { 1379 Instruction *EntInst = dyn_cast<Instruction>(V); 1380 if (!EntInst) 1381 continue; 1382 1383 // Choose a Value from the set which dominates the InsertPt. 1384 // InsertPt should be inside the Value's parent loop so as not to break 1385 // the LCSSA form. 1386 assert(EntInst->getFunction() == InsertPt->getFunction()); 1387 if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) || 1388 !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr || 1389 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt))) 1390 continue; 1391 1392 // Make sure reusing the instruction is poison-safe. 1393 if (SE.canReuseInstruction(S, EntInst, DropPoisonGeneratingInsts)) 1394 return V; 1395 DropPoisonGeneratingInsts.clear(); 1396 } 1397 return nullptr; 1398 } 1399 1400 // The expansion of SCEV will either reuse a previous Value in ExprValueMap, 1401 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode, 1402 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded 1403 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise, 1404 // the expansion will try to reuse Value from ExprValueMap, and only when it 1405 // fails, expand the SCEV literally. 1406 Value *SCEVExpander::expand(const SCEV *S) { 1407 // Compute an insertion point for this SCEV object. Hoist the instructions 1408 // as far out in the loop nest as possible. 1409 BasicBlock::iterator InsertPt = Builder.GetInsertPoint(); 1410 1411 // We can move insertion point only if there is no div or rem operations 1412 // otherwise we are risky to move it over the check for zero denominator. 1413 auto SafeToHoist = [](const SCEV *S) { 1414 return !SCEVExprContains(S, [](const SCEV *S) { 1415 if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) { 1416 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS())) 1417 // Division by non-zero constants can be hoisted. 1418 return SC->getValue()->isZero(); 1419 // All other divisions should not be moved as they may be 1420 // divisions by zero and should be kept within the 1421 // conditions of the surrounding loops that guard their 1422 // execution (see PR35406). 1423 return true; 1424 } 1425 return false; 1426 }); 1427 }; 1428 if (SafeToHoist(S)) { 1429 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());; 1430 L = L->getParentLoop()) { 1431 if (SE.isLoopInvariant(S, L)) { 1432 if (!L) break; 1433 if (BasicBlock *Preheader = L->getLoopPreheader()) { 1434 InsertPt = Preheader->getTerminator()->getIterator(); 1435 } else { 1436 // LSR sets the insertion point for AddRec start/step values to the 1437 // block start to simplify value reuse, even though it's an invalid 1438 // position. SCEVExpander must correct for this in all cases. 1439 InsertPt = L->getHeader()->getFirstInsertionPt(); 1440 } 1441 } else { 1442 // If the SCEV is computable at this level, insert it into the header 1443 // after the PHIs (and after any other instructions that we've inserted 1444 // there) so that it is guaranteed to dominate any user inside the loop. 1445 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L)) 1446 InsertPt = L->getHeader()->getFirstInsertionPt(); 1447 1448 while (InsertPt != Builder.GetInsertPoint() && 1449 (isInsertedInstruction(&*InsertPt) || 1450 isa<DbgInfoIntrinsic>(&*InsertPt))) { 1451 InsertPt = std::next(InsertPt); 1452 } 1453 break; 1454 } 1455 } 1456 } 1457 1458 // Check to see if we already expanded this here. 1459 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt)); 1460 if (I != InsertedExpressions.end()) 1461 return I->second; 1462 1463 SCEVInsertPointGuard Guard(Builder, this); 1464 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt); 1465 1466 // Expand the expression into instructions. 1467 SmallVector<Instruction *> DropPoisonGeneratingInsts; 1468 Value *V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts); 1469 if (!V) { 1470 V = visit(S); 1471 V = fixupLCSSAFormFor(V); 1472 } else { 1473 for (Instruction *I : DropPoisonGeneratingInsts) { 1474 I->dropPoisonGeneratingFlagsAndMetadata(); 1475 // See if we can re-infer from first principles any of the flags we just 1476 // dropped. 1477 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) 1478 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) { 1479 auto *BO = cast<BinaryOperator>(I); 1480 BO->setHasNoUnsignedWrap( 1481 ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW); 1482 BO->setHasNoSignedWrap( 1483 ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW); 1484 } 1485 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(I)) { 1486 auto *Src = NNI->getOperand(0); 1487 if (isImpliedByDomCondition(ICmpInst::ICMP_SGE, Src, 1488 Constant::getNullValue(Src->getType()), I, 1489 DL).value_or(false)) 1490 NNI->setNonNeg(true); 1491 } 1492 } 1493 } 1494 // Remember the expanded value for this SCEV at this location. 1495 // 1496 // This is independent of PostIncLoops. The mapped value simply materializes 1497 // the expression at this insertion point. If the mapped value happened to be 1498 // a postinc expansion, it could be reused by a non-postinc user, but only if 1499 // its insertion point was already at the head of the loop. 1500 InsertedExpressions[std::make_pair(S, &*InsertPt)] = V; 1501 return V; 1502 } 1503 1504 void SCEVExpander::rememberInstruction(Value *I) { 1505 auto DoInsert = [this](Value *V) { 1506 if (!PostIncLoops.empty()) 1507 InsertedPostIncValues.insert(V); 1508 else 1509 InsertedValues.insert(V); 1510 }; 1511 DoInsert(I); 1512 } 1513 1514 void SCEVExpander::replaceCongruentIVInc( 1515 PHINode *&Phi, PHINode *&OrigPhi, Loop *L, const DominatorTree *DT, 1516 SmallVectorImpl<WeakTrackingVH> &DeadInsts) { 1517 BasicBlock *LatchBlock = L->getLoopLatch(); 1518 if (!LatchBlock) 1519 return; 1520 1521 Instruction *OrigInc = 1522 dyn_cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); 1523 Instruction *IsomorphicInc = 1524 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock)); 1525 if (!OrigInc || !IsomorphicInc) 1526 return; 1527 1528 // If this phi has the same width but is more canonical, replace the 1529 // original with it. As part of the "more canonical" determination, 1530 // respect a prior decision to use an IV chain. 1531 if (OrigPhi->getType() == Phi->getType() && 1532 !(ChainedPhis.count(Phi) || 1533 isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) && 1534 (ChainedPhis.count(Phi) || 1535 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) { 1536 std::swap(OrigPhi, Phi); 1537 std::swap(OrigInc, IsomorphicInc); 1538 } 1539 1540 // Replacing the congruent phi is sufficient because acyclic 1541 // redundancy elimination, CSE/GVN, should handle the 1542 // rest. However, once SCEV proves that a phi is congruent, 1543 // it's often the head of an IV user cycle that is isomorphic 1544 // with the original phi. It's worth eagerly cleaning up the 1545 // common case of a single IV increment so that DeleteDeadPHIs 1546 // can remove cycles that had postinc uses. 1547 // Because we may potentially introduce a new use of OrigIV that didn't 1548 // exist before at this point, its poison flags need readjustment. 1549 const SCEV *TruncExpr = 1550 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType()); 1551 if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) || 1552 !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc)) 1553 return; 1554 1555 bool BothHaveNUW = false; 1556 bool BothHaveNSW = false; 1557 auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc); 1558 auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc); 1559 if (OBOIncV && OBOIsomorphic) { 1560 BothHaveNUW = 1561 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap(); 1562 BothHaveNSW = 1563 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap(); 1564 } 1565 1566 if (!hoistIVInc(OrigInc, IsomorphicInc, 1567 /*RecomputePoisonFlags*/ true)) 1568 return; 1569 1570 // We are replacing with a wider increment. If both OrigInc and IsomorphicInc 1571 // are NUW/NSW, then we can preserve them on the wider increment; the narrower 1572 // IsomorphicInc would wrap before the wider OrigInc, so the replacement won't 1573 // make IsomorphicInc's uses more poisonous. 1574 assert(OrigInc->getType()->getScalarSizeInBits() >= 1575 IsomorphicInc->getType()->getScalarSizeInBits() && 1576 "Should only replace an increment with a wider one."); 1577 if (BothHaveNUW || BothHaveNSW) { 1578 OrigInc->setHasNoUnsignedWrap(OBOIncV->hasNoUnsignedWrap() || BothHaveNUW); 1579 OrigInc->setHasNoSignedWrap(OBOIncV->hasNoSignedWrap() || BothHaveNSW); 1580 } 1581 1582 SCEV_DEBUG_WITH_TYPE(DebugType, 1583 dbgs() << "INDVARS: Eliminated congruent iv.inc: " 1584 << *IsomorphicInc << '\n'); 1585 Value *NewInc = OrigInc; 1586 if (OrigInc->getType() != IsomorphicInc->getType()) { 1587 BasicBlock::iterator IP; 1588 if (PHINode *PN = dyn_cast<PHINode>(OrigInc)) 1589 IP = PN->getParent()->getFirstInsertionPt(); 1590 else 1591 IP = OrigInc->getNextNonDebugInstruction()->getIterator(); 1592 1593 IRBuilder<> Builder(IP->getParent(), IP); 1594 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc()); 1595 NewInc = 1596 Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName); 1597 } 1598 IsomorphicInc->replaceAllUsesWith(NewInc); 1599 DeadInsts.emplace_back(IsomorphicInc); 1600 } 1601 1602 /// replaceCongruentIVs - Check for congruent phis in this loop header and 1603 /// replace them with their most canonical representative. Return the number of 1604 /// phis eliminated. 1605 /// 1606 /// This does not depend on any SCEVExpander state but should be used in 1607 /// the same context that SCEVExpander is used. 1608 unsigned 1609 SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT, 1610 SmallVectorImpl<WeakTrackingVH> &DeadInsts, 1611 const TargetTransformInfo *TTI) { 1612 // Find integer phis in order of increasing width. 1613 SmallVector<PHINode*, 8> Phis; 1614 for (PHINode &PN : L->getHeader()->phis()) 1615 Phis.push_back(&PN); 1616 1617 if (TTI) 1618 // Use stable_sort to preserve order of equivalent PHIs, so the order 1619 // of the sorted Phis is the same from run to run on the same loop. 1620 llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) { 1621 // Put pointers at the back and make sure pointer < pointer = false. 1622 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 1623 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy(); 1624 return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() < 1625 LHS->getType()->getPrimitiveSizeInBits().getFixedValue(); 1626 }); 1627 1628 unsigned NumElim = 0; 1629 DenseMap<const SCEV *, PHINode *> ExprToIVMap; 1630 // Process phis from wide to narrow. Map wide phis to their truncation 1631 // so narrow phis can reuse them. 1632 for (PHINode *Phi : Phis) { 1633 auto SimplifyPHINode = [&](PHINode *PN) -> Value * { 1634 if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC})) 1635 return V; 1636 if (!SE.isSCEVable(PN->getType())) 1637 return nullptr; 1638 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN)); 1639 if (!Const) 1640 return nullptr; 1641 return Const->getValue(); 1642 }; 1643 1644 // Fold constant phis. They may be congruent to other constant phis and 1645 // would confuse the logic below that expects proper IVs. 1646 if (Value *V = SimplifyPHINode(Phi)) { 1647 if (V->getType() != Phi->getType()) 1648 continue; 1649 SE.forgetValue(Phi); 1650 Phi->replaceAllUsesWith(V); 1651 DeadInsts.emplace_back(Phi); 1652 ++NumElim; 1653 SCEV_DEBUG_WITH_TYPE(DebugType, 1654 dbgs() << "INDVARS: Eliminated constant iv: " << *Phi 1655 << '\n'); 1656 continue; 1657 } 1658 1659 if (!SE.isSCEVable(Phi->getType())) 1660 continue; 1661 1662 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)]; 1663 if (!OrigPhiRef) { 1664 OrigPhiRef = Phi; 1665 if (Phi->getType()->isIntegerTy() && TTI && 1666 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) { 1667 // Make sure we only rewrite using simple induction variables; 1668 // otherwise, we can make the trip count of a loop unanalyzable 1669 // to SCEV. 1670 const SCEV *PhiExpr = SE.getSCEV(Phi); 1671 if (isa<SCEVAddRecExpr>(PhiExpr)) { 1672 // This phi can be freely truncated to the narrowest phi type. Map the 1673 // truncated expression to it so it will be reused for narrow types. 1674 const SCEV *TruncExpr = 1675 SE.getTruncateExpr(PhiExpr, Phis.back()->getType()); 1676 ExprToIVMap[TruncExpr] = Phi; 1677 } 1678 } 1679 continue; 1680 } 1681 1682 // Replacing a pointer phi with an integer phi or vice-versa doesn't make 1683 // sense. 1684 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy()) 1685 continue; 1686 1687 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts); 1688 SCEV_DEBUG_WITH_TYPE(DebugType, 1689 dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi 1690 << '\n'); 1691 SCEV_DEBUG_WITH_TYPE( 1692 DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n'); 1693 ++NumElim; 1694 Value *NewIV = OrigPhiRef; 1695 if (OrigPhiRef->getType() != Phi->getType()) { 1696 IRBuilder<> Builder(L->getHeader(), 1697 L->getHeader()->getFirstInsertionPt()); 1698 Builder.SetCurrentDebugLocation(Phi->getDebugLoc()); 1699 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName); 1700 } 1701 Phi->replaceAllUsesWith(NewIV); 1702 DeadInsts.emplace_back(Phi); 1703 } 1704 return NumElim; 1705 } 1706 1707 bool SCEVExpander::hasRelatedExistingExpansion(const SCEV *S, 1708 const Instruction *At, 1709 Loop *L) { 1710 using namespace llvm::PatternMatch; 1711 1712 SmallVector<BasicBlock *, 4> ExitingBlocks; 1713 L->getExitingBlocks(ExitingBlocks); 1714 1715 // Look for suitable value in simple conditions at the loop exits. 1716 for (BasicBlock *BB : ExitingBlocks) { 1717 ICmpInst::Predicate Pred; 1718 Instruction *LHS, *RHS; 1719 1720 if (!match(BB->getTerminator(), 1721 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)), 1722 m_BasicBlock(), m_BasicBlock()))) 1723 continue; 1724 1725 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At)) 1726 return true; 1727 1728 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At)) 1729 return true; 1730 } 1731 1732 // Use expand's logic which is used for reusing a previous Value in 1733 // ExprValueMap. Note that we don't currently model the cost of 1734 // needing to drop poison generating flags on the instruction if we 1735 // want to reuse it. We effectively assume that has zero cost. 1736 SmallVector<Instruction *> DropPoisonGeneratingInsts; 1737 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr; 1738 } 1739 1740 template<typename T> static InstructionCost costAndCollectOperands( 1741 const SCEVOperand &WorkItem, const TargetTransformInfo &TTI, 1742 TargetTransformInfo::TargetCostKind CostKind, 1743 SmallVectorImpl<SCEVOperand> &Worklist) { 1744 1745 const T *S = cast<T>(WorkItem.S); 1746 InstructionCost Cost = 0; 1747 // Object to help map SCEV operands to expanded IR instructions. 1748 struct OperationIndices { 1749 OperationIndices(unsigned Opc, size_t min, size_t max) : 1750 Opcode(Opc), MinIdx(min), MaxIdx(max) { } 1751 unsigned Opcode; 1752 size_t MinIdx; 1753 size_t MaxIdx; 1754 }; 1755 1756 // Collect the operations of all the instructions that will be needed to 1757 // expand the SCEVExpr. This is so that when we come to cost the operands, 1758 // we know what the generated user(s) will be. 1759 SmallVector<OperationIndices, 2> Operations; 1760 1761 auto CastCost = [&](unsigned Opcode) -> InstructionCost { 1762 Operations.emplace_back(Opcode, 0, 0); 1763 return TTI.getCastInstrCost(Opcode, S->getType(), 1764 S->getOperand(0)->getType(), 1765 TTI::CastContextHint::None, CostKind); 1766 }; 1767 1768 auto ArithCost = [&](unsigned Opcode, unsigned NumRequired, 1769 unsigned MinIdx = 0, 1770 unsigned MaxIdx = 1) -> InstructionCost { 1771 Operations.emplace_back(Opcode, MinIdx, MaxIdx); 1772 return NumRequired * 1773 TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind); 1774 }; 1775 1776 auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx, 1777 unsigned MaxIdx) -> InstructionCost { 1778 Operations.emplace_back(Opcode, MinIdx, MaxIdx); 1779 Type *OpType = S->getType(); 1780 return NumRequired * TTI.getCmpSelInstrCost( 1781 Opcode, OpType, CmpInst::makeCmpResultType(OpType), 1782 CmpInst::BAD_ICMP_PREDICATE, CostKind); 1783 }; 1784 1785 switch (S->getSCEVType()) { 1786 case scCouldNotCompute: 1787 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 1788 case scUnknown: 1789 case scConstant: 1790 case scVScale: 1791 return 0; 1792 case scPtrToInt: 1793 Cost = CastCost(Instruction::PtrToInt); 1794 break; 1795 case scTruncate: 1796 Cost = CastCost(Instruction::Trunc); 1797 break; 1798 case scZeroExtend: 1799 Cost = CastCost(Instruction::ZExt); 1800 break; 1801 case scSignExtend: 1802 Cost = CastCost(Instruction::SExt); 1803 break; 1804 case scUDivExpr: { 1805 unsigned Opcode = Instruction::UDiv; 1806 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1))) 1807 if (SC->getAPInt().isPowerOf2()) 1808 Opcode = Instruction::LShr; 1809 Cost = ArithCost(Opcode, 1); 1810 break; 1811 } 1812 case scAddExpr: 1813 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1); 1814 break; 1815 case scMulExpr: 1816 // TODO: this is a very pessimistic cost modelling for Mul, 1817 // because of Bin Pow algorithm actually used by the expander, 1818 // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN(). 1819 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1); 1820 break; 1821 case scSMaxExpr: 1822 case scUMaxExpr: 1823 case scSMinExpr: 1824 case scUMinExpr: 1825 case scSequentialUMinExpr: { 1826 // FIXME: should this ask the cost for Intrinsic's? 1827 // The reduction tree. 1828 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1); 1829 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2); 1830 switch (S->getSCEVType()) { 1831 case scSequentialUMinExpr: { 1832 // The safety net against poison. 1833 // FIXME: this is broken. 1834 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0); 1835 Cost += ArithCost(Instruction::Or, 1836 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0); 1837 Cost += CmpSelCost(Instruction::Select, 1, 0, 1); 1838 break; 1839 } 1840 default: 1841 assert(!isa<SCEVSequentialMinMaxExpr>(S) && 1842 "Unhandled SCEV expression type?"); 1843 break; 1844 } 1845 break; 1846 } 1847 case scAddRecExpr: { 1848 // In this polynominal, we may have some zero operands, and we shouldn't 1849 // really charge for those. So how many non-zero coefficients are there? 1850 int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) { 1851 return !Op->isZero(); 1852 }); 1853 1854 assert(NumTerms >= 1 && "Polynominal should have at least one term."); 1855 assert(!(*std::prev(S->operands().end()))->isZero() && 1856 "Last operand should not be zero"); 1857 1858 // Ignoring constant term (operand 0), how many of the coefficients are u> 1? 1859 int NumNonZeroDegreeNonOneTerms = 1860 llvm::count_if(S->operands(), [](const SCEV *Op) { 1861 auto *SConst = dyn_cast<SCEVConstant>(Op); 1862 return !SConst || SConst->getAPInt().ugt(1); 1863 }); 1864 1865 // Much like with normal add expr, the polynominal will require 1866 // one less addition than the number of it's terms. 1867 InstructionCost AddCost = ArithCost(Instruction::Add, NumTerms - 1, 1868 /*MinIdx*/ 1, /*MaxIdx*/ 1); 1869 // Here, *each* one of those will require a multiplication. 1870 InstructionCost MulCost = 1871 ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms); 1872 Cost = AddCost + MulCost; 1873 1874 // What is the degree of this polynominal? 1875 int PolyDegree = S->getNumOperands() - 1; 1876 assert(PolyDegree >= 1 && "Should be at least affine."); 1877 1878 // The final term will be: 1879 // Op_{PolyDegree} * x ^ {PolyDegree} 1880 // Where x ^ {PolyDegree} will again require PolyDegree-1 mul operations. 1881 // Note that x ^ {PolyDegree} = x * x ^ {PolyDegree-1} so charging for 1882 // x ^ {PolyDegree} will give us x ^ {2} .. x ^ {PolyDegree-1} for free. 1883 // FIXME: this is conservatively correct, but might be overly pessimistic. 1884 Cost += MulCost * (PolyDegree - 1); 1885 break; 1886 } 1887 } 1888 1889 for (auto &CostOp : Operations) { 1890 for (auto SCEVOp : enumerate(S->operands())) { 1891 // Clamp the index to account for multiple IR operations being chained. 1892 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx); 1893 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx); 1894 Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value()); 1895 } 1896 } 1897 return Cost; 1898 } 1899 1900 bool SCEVExpander::isHighCostExpansionHelper( 1901 const SCEVOperand &WorkItem, Loop *L, const Instruction &At, 1902 InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI, 1903 SmallPtrSetImpl<const SCEV *> &Processed, 1904 SmallVectorImpl<SCEVOperand> &Worklist) { 1905 if (Cost > Budget) 1906 return true; // Already run out of budget, give up. 1907 1908 const SCEV *S = WorkItem.S; 1909 // Was the cost of expansion of this expression already accounted for? 1910 if (!isa<SCEVConstant>(S) && !Processed.insert(S).second) 1911 return false; // We have already accounted for this expression. 1912 1913 // If we can find an existing value for this scev available at the point "At" 1914 // then consider the expression cheap. 1915 if (hasRelatedExistingExpansion(S, &At, L)) 1916 return false; // Consider the expression to be free. 1917 1918 TargetTransformInfo::TargetCostKind CostKind = 1919 L->getHeader()->getParent()->hasMinSize() 1920 ? TargetTransformInfo::TCK_CodeSize 1921 : TargetTransformInfo::TCK_RecipThroughput; 1922 1923 switch (S->getSCEVType()) { 1924 case scCouldNotCompute: 1925 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 1926 case scUnknown: 1927 case scVScale: 1928 // Assume to be zero-cost. 1929 return false; 1930 case scConstant: { 1931 // Only evalulate the costs of constants when optimizing for size. 1932 if (CostKind != TargetTransformInfo::TCK_CodeSize) 1933 return false; 1934 const APInt &Imm = cast<SCEVConstant>(S)->getAPInt(); 1935 Type *Ty = S->getType(); 1936 Cost += TTI.getIntImmCostInst( 1937 WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind); 1938 return Cost > Budget; 1939 } 1940 case scTruncate: 1941 case scPtrToInt: 1942 case scZeroExtend: 1943 case scSignExtend: { 1944 Cost += 1945 costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist); 1946 return false; // Will answer upon next entry into this function. 1947 } 1948 case scUDivExpr: { 1949 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or 1950 // HowManyLessThans produced to compute a precise expression, rather than a 1951 // UDiv from the user's code. If we can't find a UDiv in the code with some 1952 // simple searching, we need to account for it's cost. 1953 1954 // At the beginning of this function we already tried to find existing 1955 // value for plain 'S'. Now try to lookup 'S + 1' since it is common 1956 // pattern involving division. This is just a simple search heuristic. 1957 if (hasRelatedExistingExpansion( 1958 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L)) 1959 return false; // Consider it to be free. 1960 1961 Cost += 1962 costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist); 1963 return false; // Will answer upon next entry into this function. 1964 } 1965 case scAddExpr: 1966 case scMulExpr: 1967 case scUMaxExpr: 1968 case scSMaxExpr: 1969 case scUMinExpr: 1970 case scSMinExpr: 1971 case scSequentialUMinExpr: { 1972 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 && 1973 "Nary expr should have more than 1 operand."); 1974 // The simple nary expr will require one less op (or pair of ops) 1975 // than the number of it's terms. 1976 Cost += 1977 costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist); 1978 return Cost > Budget; 1979 } 1980 case scAddRecExpr: { 1981 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 && 1982 "Polynomial should be at least linear"); 1983 Cost += costAndCollectOperands<SCEVAddRecExpr>( 1984 WorkItem, TTI, CostKind, Worklist); 1985 return Cost > Budget; 1986 } 1987 } 1988 llvm_unreachable("Unknown SCEV kind!"); 1989 } 1990 1991 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred, 1992 Instruction *IP) { 1993 assert(IP); 1994 switch (Pred->getKind()) { 1995 case SCEVPredicate::P_Union: 1996 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP); 1997 case SCEVPredicate::P_Compare: 1998 return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP); 1999 case SCEVPredicate::P_Wrap: { 2000 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred); 2001 return expandWrapPredicate(AddRecPred, IP); 2002 } 2003 } 2004 llvm_unreachable("Unknown SCEV predicate type"); 2005 } 2006 2007 Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred, 2008 Instruction *IP) { 2009 Value *Expr0 = expand(Pred->getLHS(), IP); 2010 Value *Expr1 = expand(Pred->getRHS(), IP); 2011 2012 Builder.SetInsertPoint(IP); 2013 auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate()); 2014 auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check"); 2015 return I; 2016 } 2017 2018 Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR, 2019 Instruction *Loc, bool Signed) { 2020 assert(AR->isAffine() && "Cannot generate RT check for " 2021 "non-affine expression"); 2022 2023 // FIXME: It is highly suspicious that we're ignoring the predicates here. 2024 SmallVector<const SCEVPredicate *, 4> Pred; 2025 const SCEV *ExitCount = 2026 SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred); 2027 2028 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count"); 2029 2030 const SCEV *Step = AR->getStepRecurrence(SE); 2031 const SCEV *Start = AR->getStart(); 2032 2033 Type *ARTy = AR->getType(); 2034 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType()); 2035 unsigned DstBits = SE.getTypeSizeInBits(ARTy); 2036 2037 // The expression {Start,+,Step} has nusw/nssw if 2038 // Step < 0, Start - |Step| * Backedge <= Start 2039 // Step >= 0, Start + |Step| * Backedge > Start 2040 // and |Step| * Backedge doesn't unsigned overflow. 2041 2042 Builder.SetInsertPoint(Loc); 2043 Value *TripCountVal = expand(ExitCount, Loc); 2044 2045 IntegerType *Ty = 2046 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy)); 2047 2048 Value *StepValue = expand(Step, Loc); 2049 Value *NegStepValue = expand(SE.getNegativeSCEV(Step), Loc); 2050 Value *StartValue = expand(Start, Loc); 2051 2052 ConstantInt *Zero = 2053 ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits)); 2054 2055 Builder.SetInsertPoint(Loc); 2056 // Compute |Step| 2057 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero); 2058 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue); 2059 2060 // Compute |Step| * Backedge 2061 // Compute: 2062 // 1. Start + |Step| * Backedge < Start 2063 // 2. Start - |Step| * Backedge > Start 2064 // 2065 // And select either 1. or 2. depending on whether step is positive or 2066 // negative. If Step is known to be positive or negative, only create 2067 // either 1. or 2. 2068 auto ComputeEndCheck = [&]() -> Value * { 2069 // Checking <u 0 is always false. 2070 if (!Signed && Start->isZero() && SE.isKnownPositive(Step)) 2071 return ConstantInt::getFalse(Loc->getContext()); 2072 2073 // Get the backedge taken count and truncate or extended to the AR type. 2074 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty); 2075 2076 Value *MulV, *OfMul; 2077 if (Step->isOne()) { 2078 // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't 2079 // needed, there is never an overflow, so to avoid artificially inflating 2080 // the cost of the check, directly emit the optimized IR. 2081 MulV = TruncTripCount; 2082 OfMul = ConstantInt::getFalse(MulV->getContext()); 2083 } else { 2084 auto *MulF = Intrinsic::getDeclaration(Loc->getModule(), 2085 Intrinsic::umul_with_overflow, Ty); 2086 CallInst *Mul = 2087 Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul"); 2088 MulV = Builder.CreateExtractValue(Mul, 0, "mul.result"); 2089 OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow"); 2090 } 2091 2092 Value *Add = nullptr, *Sub = nullptr; 2093 bool NeedPosCheck = !SE.isKnownNegative(Step); 2094 bool NeedNegCheck = !SE.isKnownPositive(Step); 2095 2096 if (isa<PointerType>(ARTy)) { 2097 Value *NegMulV = Builder.CreateNeg(MulV); 2098 if (NeedPosCheck) 2099 Add = Builder.CreatePtrAdd(StartValue, MulV); 2100 if (NeedNegCheck) 2101 Sub = Builder.CreatePtrAdd(StartValue, NegMulV); 2102 } else { 2103 if (NeedPosCheck) 2104 Add = Builder.CreateAdd(StartValue, MulV); 2105 if (NeedNegCheck) 2106 Sub = Builder.CreateSub(StartValue, MulV); 2107 } 2108 2109 Value *EndCompareLT = nullptr; 2110 Value *EndCompareGT = nullptr; 2111 Value *EndCheck = nullptr; 2112 if (NeedPosCheck) 2113 EndCheck = EndCompareLT = Builder.CreateICmp( 2114 Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue); 2115 if (NeedNegCheck) 2116 EndCheck = EndCompareGT = Builder.CreateICmp( 2117 Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue); 2118 if (NeedPosCheck && NeedNegCheck) { 2119 // Select the answer based on the sign of Step. 2120 EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT); 2121 } 2122 return Builder.CreateOr(EndCheck, OfMul); 2123 }; 2124 Value *EndCheck = ComputeEndCheck(); 2125 2126 // If the backedge taken count type is larger than the AR type, 2127 // check that we don't drop any bits by truncating it. If we are 2128 // dropping bits, then we have overflow (unless the step is zero). 2129 if (SrcBits > DstBits) { 2130 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits); 2131 auto *BackedgeCheck = 2132 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal, 2133 ConstantInt::get(Loc->getContext(), MaxVal)); 2134 BackedgeCheck = Builder.CreateAnd( 2135 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero)); 2136 2137 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck); 2138 } 2139 2140 return EndCheck; 2141 } 2142 2143 Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred, 2144 Instruction *IP) { 2145 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr()); 2146 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr; 2147 2148 // Add a check for NUSW 2149 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW) 2150 NUSWCheck = generateOverflowCheck(A, IP, false); 2151 2152 // Add a check for NSSW 2153 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW) 2154 NSSWCheck = generateOverflowCheck(A, IP, true); 2155 2156 if (NUSWCheck && NSSWCheck) 2157 return Builder.CreateOr(NUSWCheck, NSSWCheck); 2158 2159 if (NUSWCheck) 2160 return NUSWCheck; 2161 2162 if (NSSWCheck) 2163 return NSSWCheck; 2164 2165 return ConstantInt::getFalse(IP->getContext()); 2166 } 2167 2168 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union, 2169 Instruction *IP) { 2170 // Loop over all checks in this set. 2171 SmallVector<Value *> Checks; 2172 for (const auto *Pred : Union->getPredicates()) { 2173 Checks.push_back(expandCodeForPredicate(Pred, IP)); 2174 Builder.SetInsertPoint(IP); 2175 } 2176 2177 if (Checks.empty()) 2178 return ConstantInt::getFalse(IP->getContext()); 2179 return Builder.CreateOr(Checks); 2180 } 2181 2182 Value *SCEVExpander::fixupLCSSAFormFor(Value *V) { 2183 auto *DefI = dyn_cast<Instruction>(V); 2184 if (!PreserveLCSSA || !DefI) 2185 return V; 2186 2187 Instruction *InsertPt = &*Builder.GetInsertPoint(); 2188 Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent()); 2189 Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent()); 2190 if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop)) 2191 return V; 2192 2193 // Create a temporary instruction to at the current insertion point, so we 2194 // can hand it off to the helper to create LCSSA PHIs if required for the 2195 // new use. 2196 // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor) 2197 // would accept a insertion point and return an LCSSA phi for that 2198 // insertion point, so there is no need to insert & remove the temporary 2199 // instruction. 2200 Type *ToTy; 2201 if (DefI->getType()->isIntegerTy()) 2202 ToTy = PointerType::get(DefI->getContext(), 0); 2203 else 2204 ToTy = Type::getInt32Ty(DefI->getContext()); 2205 Instruction *User = 2206 CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt); 2207 auto RemoveUserOnExit = 2208 make_scope_exit([User]() { User->eraseFromParent(); }); 2209 2210 SmallVector<Instruction *, 1> ToUpdate; 2211 ToUpdate.push_back(DefI); 2212 SmallVector<PHINode *, 16> PHIsToRemove; 2213 SmallVector<PHINode *, 16> InsertedPHIs; 2214 formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove, 2215 &InsertedPHIs); 2216 for (PHINode *PN : InsertedPHIs) 2217 rememberInstruction(PN); 2218 for (PHINode *PN : PHIsToRemove) { 2219 if (!PN->use_empty()) 2220 continue; 2221 InsertedValues.erase(PN); 2222 InsertedPostIncValues.erase(PN); 2223 PN->eraseFromParent(); 2224 } 2225 2226 return User->getOperand(0); 2227 } 2228 2229 namespace { 2230 // Search for a SCEV subexpression that is not safe to expand. Any expression 2231 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely 2232 // UDiv expressions. We don't know if the UDiv is derived from an IR divide 2233 // instruction, but the important thing is that we prove the denominator is 2234 // nonzero before expansion. 2235 // 2236 // IVUsers already checks that IV-derived expressions are safe. So this check is 2237 // only needed when the expression includes some subexpression that is not IV 2238 // derived. 2239 // 2240 // Currently, we only allow division by a value provably non-zero here. 2241 // 2242 // We cannot generally expand recurrences unless the step dominates the loop 2243 // header. The expander handles the special case of affine recurrences by 2244 // scaling the recurrence outside the loop, but this technique isn't generally 2245 // applicable. Expanding a nested recurrence outside a loop requires computing 2246 // binomial coefficients. This could be done, but the recurrence has to be in a 2247 // perfectly reduced form, which can't be guaranteed. 2248 struct SCEVFindUnsafe { 2249 ScalarEvolution &SE; 2250 bool CanonicalMode; 2251 bool IsUnsafe = false; 2252 2253 SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode) 2254 : SE(SE), CanonicalMode(CanonicalMode) {} 2255 2256 bool follow(const SCEV *S) { 2257 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { 2258 if (!SE.isKnownNonZero(D->getRHS())) { 2259 IsUnsafe = true; 2260 return false; 2261 } 2262 } 2263 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 2264 // For non-affine addrecs or in non-canonical mode we need a preheader 2265 // to insert into. 2266 if (!AR->getLoop()->getLoopPreheader() && 2267 (!CanonicalMode || !AR->isAffine())) { 2268 IsUnsafe = true; 2269 return false; 2270 } 2271 } 2272 return true; 2273 } 2274 bool isDone() const { return IsUnsafe; } 2275 }; 2276 } // namespace 2277 2278 bool SCEVExpander::isSafeToExpand(const SCEV *S) const { 2279 SCEVFindUnsafe Search(SE, CanonicalMode); 2280 visitAll(S, Search); 2281 return !Search.IsUnsafe; 2282 } 2283 2284 bool SCEVExpander::isSafeToExpandAt(const SCEV *S, 2285 const Instruction *InsertionPoint) const { 2286 if (!isSafeToExpand(S)) 2287 return false; 2288 // We have to prove that the expanded site of S dominates InsertionPoint. 2289 // This is easy when not in the same block, but hard when S is an instruction 2290 // to be expanded somewhere inside the same block as our insertion point. 2291 // What we really need here is something analogous to an OrderedBasicBlock, 2292 // but for the moment, we paper over the problem by handling two common and 2293 // cheap to check cases. 2294 if (SE.properlyDominates(S, InsertionPoint->getParent())) 2295 return true; 2296 if (SE.dominates(S, InsertionPoint->getParent())) { 2297 if (InsertionPoint->getParent()->getTerminator() == InsertionPoint) 2298 return true; 2299 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) 2300 if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue())) 2301 return true; 2302 } 2303 return false; 2304 } 2305 2306 void SCEVExpanderCleaner::cleanup() { 2307 // Result is used, nothing to remove. 2308 if (ResultUsed) 2309 return; 2310 2311 auto InsertedInstructions = Expander.getAllInsertedInstructions(); 2312 #ifndef NDEBUG 2313 SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(), 2314 InsertedInstructions.end()); 2315 (void)InsertedSet; 2316 #endif 2317 // Remove sets with value handles. 2318 Expander.clear(); 2319 2320 // Remove all inserted instructions. 2321 for (Instruction *I : reverse(InsertedInstructions)) { 2322 #ifndef NDEBUG 2323 assert(all_of(I->users(), 2324 [&InsertedSet](Value *U) { 2325 return InsertedSet.contains(cast<Instruction>(U)); 2326 }) && 2327 "removed instruction should only be used by instructions inserted " 2328 "during expansion"); 2329 #endif 2330 assert(!I->getType()->isVoidTy() && 2331 "inserted instruction should have non-void types"); 2332 I->replaceAllUsesWith(PoisonValue::get(I->getType())); 2333 I->eraseFromParent(); 2334 } 2335 } 2336