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