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