ScalarEvolutionExpander.cpp revision c40f17b08774c2dcc5787fd83241e3c64ba82974
1//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains the implementation of the scalar evolution expander, 11// which is used to generate the code corresponding to a given scalar evolution 12// expression. 13// 14//===----------------------------------------------------------------------===// 15 16#include "llvm/Analysis/ScalarEvolutionExpander.h" 17#include "llvm/Analysis/LoopInfo.h" 18#include "llvm/LLVMContext.h" 19#include "llvm/Target/TargetData.h" 20#include "llvm/ADT/STLExtras.h" 21using namespace llvm; 22 23/// InsertNoopCastOfTo - Insert a cast of V to the specified type, 24/// which must be possible with a noop cast, doing what we can to share 25/// the casts. 26Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) { 27 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false); 28 assert((Op == Instruction::BitCast || 29 Op == Instruction::PtrToInt || 30 Op == Instruction::IntToPtr) && 31 "InsertNoopCastOfTo cannot perform non-noop casts!"); 32 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) && 33 "InsertNoopCastOfTo cannot change sizes!"); 34 35 // Short-circuit unnecessary bitcasts. 36 if (Op == Instruction::BitCast && V->getType() == Ty) 37 return V; 38 39 // Short-circuit unnecessary inttoptr<->ptrtoint casts. 40 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) && 41 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) { 42 if (CastInst *CI = dyn_cast<CastInst>(V)) 43 if ((CI->getOpcode() == Instruction::PtrToInt || 44 CI->getOpcode() == Instruction::IntToPtr) && 45 SE.getTypeSizeInBits(CI->getType()) == 46 SE.getTypeSizeInBits(CI->getOperand(0)->getType())) 47 return CI->getOperand(0); 48 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 49 if ((CE->getOpcode() == Instruction::PtrToInt || 50 CE->getOpcode() == Instruction::IntToPtr) && 51 SE.getTypeSizeInBits(CE->getType()) == 52 SE.getTypeSizeInBits(CE->getOperand(0)->getType())) 53 return CE->getOperand(0); 54 } 55 56 // FIXME: keep track of the cast instruction. 57 if (Constant *C = dyn_cast<Constant>(V)) 58 return ConstantExpr::getCast(Op, C, Ty); 59 60 if (Argument *A = dyn_cast<Argument>(V)) { 61 // Check to see if there is already a cast! 62 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); 63 UI != E; ++UI) 64 if ((*UI)->getType() == Ty) 65 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) 66 if (CI->getOpcode() == Op) { 67 // If the cast isn't the first instruction of the function, move it. 68 if (BasicBlock::iterator(CI) != 69 A->getParent()->getEntryBlock().begin()) { 70 // Recreate the cast at the beginning of the entry block. 71 // The old cast is left in place in case it is being used 72 // as an insert point. 73 Instruction *NewCI = 74 CastInst::Create(Op, V, Ty, "", 75 A->getParent()->getEntryBlock().begin()); 76 NewCI->takeName(CI); 77 CI->replaceAllUsesWith(NewCI); 78 return NewCI; 79 } 80 return CI; 81 } 82 83 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), 84 A->getParent()->getEntryBlock().begin()); 85 InsertedValues.insert(I); 86 return I; 87 } 88 89 Instruction *I = cast<Instruction>(V); 90 91 // Check to see if there is already a cast. If there is, use it. 92 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 93 UI != E; ++UI) { 94 if ((*UI)->getType() == Ty) 95 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) 96 if (CI->getOpcode() == Op) { 97 BasicBlock::iterator It = I; ++It; 98 if (isa<InvokeInst>(I)) 99 It = cast<InvokeInst>(I)->getNormalDest()->begin(); 100 while (isa<PHINode>(It)) ++It; 101 if (It != BasicBlock::iterator(CI)) { 102 // Recreate the cast at the beginning of the entry block. 103 // The old cast is left in place in case it is being used 104 // as an insert point. 105 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It); 106 NewCI->takeName(CI); 107 CI->replaceAllUsesWith(NewCI); 108 return NewCI; 109 } 110 return CI; 111 } 112 } 113 BasicBlock::iterator IP = I; ++IP; 114 if (InvokeInst *II = dyn_cast<InvokeInst>(I)) 115 IP = II->getNormalDest()->begin(); 116 while (isa<PHINode>(IP)) ++IP; 117 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP); 118 InsertedValues.insert(CI); 119 return CI; 120} 121 122/// InsertBinop - Insert the specified binary operator, doing a small amount 123/// of work to avoid inserting an obviously redundant operation. 124Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, 125 Value *LHS, Value *RHS) { 126 // Fold a binop with constant operands. 127 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 128 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 129 return ConstantExpr::get(Opcode, CLHS, CRHS); 130 131 // Do a quick scan to see if we have this binop nearby. If so, reuse it. 132 unsigned ScanLimit = 6; 133 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 134 // Scanning starts from the last instruction before the insertion point. 135 BasicBlock::iterator IP = Builder.GetInsertPoint(); 136 if (IP != BlockBegin) { 137 --IP; 138 for (; ScanLimit; --IP, --ScanLimit) { 139 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS && 140 IP->getOperand(1) == RHS) 141 return IP; 142 if (IP == BlockBegin) break; 143 } 144 } 145 146 // If we haven't found this binop, insert it. 147 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp"); 148 InsertedValues.insert(BO); 149 return BO; 150} 151 152/// FactorOutConstant - Test if S is divisible by Factor, using signed 153/// division. If so, update S with Factor divided out and return true. 154/// S need not be evenly divisble if a reasonable remainder can be 155/// computed. 156/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made 157/// unnecessary; in its place, just signed-divide Ops[i] by the scale and 158/// check to see if the divide was folded. 159static bool FactorOutConstant(const SCEV *&S, 160 const SCEV *&Remainder, 161 const SCEV *Factor, 162 ScalarEvolution &SE, 163 const TargetData *TD) { 164 // Everything is divisible by one. 165 if (Factor->isOne()) 166 return true; 167 168 // x/x == 1. 169 if (S == Factor) { 170 S = SE.getIntegerSCEV(1, S->getType()); 171 return true; 172 } 173 174 // For a Constant, check for a multiple of the given factor. 175 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 176 // 0/x == 0. 177 if (C->isZero()) 178 return true; 179 // Check for divisibility. 180 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) { 181 ConstantInt *CI = 182 ConstantInt::get(SE.getContext(), 183 C->getValue()->getValue().sdiv( 184 FC->getValue()->getValue())); 185 // If the quotient is zero and the remainder is non-zero, reject 186 // the value at this scale. It will be considered for subsequent 187 // smaller scales. 188 if (!CI->isZero()) { 189 const SCEV *Div = SE.getConstant(CI); 190 S = Div; 191 Remainder = 192 SE.getAddExpr(Remainder, 193 SE.getConstant(C->getValue()->getValue().srem( 194 FC->getValue()->getValue()))); 195 return true; 196 } 197 } 198 } 199 200 // In a Mul, check if there is a constant operand which is a multiple 201 // of the given factor. 202 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 203 if (TD) { 204 // With TargetData, the size is known. Check if there is a constant 205 // operand which is a multiple of the given factor. If so, we can 206 // factor it. 207 const SCEVConstant *FC = cast<SCEVConstant>(Factor); 208 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0))) 209 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) { 210 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands(); 211 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(), 212 MOperands.end()); 213 NewMulOps[0] = 214 SE.getConstant(C->getValue()->getValue().sdiv( 215 FC->getValue()->getValue())); 216 S = SE.getMulExpr(NewMulOps); 217 return true; 218 } 219 } else { 220 // Without TargetData, check if Factor can be factored out of any of the 221 // Mul's operands. If so, we can just remove it. 222 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 223 const SCEV *SOp = M->getOperand(i); 224 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType()); 225 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) && 226 Remainder->isZero()) { 227 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands(); 228 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(), 229 MOperands.end()); 230 NewMulOps[i] = SOp; 231 S = SE.getMulExpr(NewMulOps); 232 return true; 233 } 234 } 235 } 236 } 237 238 // In an AddRec, check if both start and step are divisible. 239 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 240 const SCEV *Step = A->getStepRecurrence(SE); 241 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType()); 242 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD)) 243 return false; 244 if (!StepRem->isZero()) 245 return false; 246 const SCEV *Start = A->getStart(); 247 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD)) 248 return false; 249 S = SE.getAddRecExpr(Start, Step, A->getLoop()); 250 return true; 251 } 252 253 return false; 254} 255 256/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs 257/// is the number of SCEVAddRecExprs present, which are kept at the end of 258/// the list. 259/// 260static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops, 261 const Type *Ty, 262 ScalarEvolution &SE) { 263 unsigned NumAddRecs = 0; 264 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i) 265 ++NumAddRecs; 266 // Group Ops into non-addrecs and addrecs. 267 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs); 268 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end()); 269 // Let ScalarEvolution sort and simplify the non-addrecs list. 270 const SCEV *Sum = NoAddRecs.empty() ? 271 SE.getIntegerSCEV(0, Ty) : 272 SE.getAddExpr(NoAddRecs); 273 // If it returned an add, use the operands. Otherwise it simplified 274 // the sum into a single value, so just use that. 275 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum)) 276 Ops = Add->getOperands(); 277 else { 278 Ops.clear(); 279 if (!Sum->isZero()) 280 Ops.push_back(Sum); 281 } 282 // Then append the addrecs. 283 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end()); 284} 285 286/// SplitAddRecs - Flatten a list of add operands, moving addrec start values 287/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}. 288/// This helps expose more opportunities for folding parts of the expressions 289/// into GEP indices. 290/// 291static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops, 292 const Type *Ty, 293 ScalarEvolution &SE) { 294 // Find the addrecs. 295 SmallVector<const SCEV *, 8> AddRecs; 296 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 297 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) { 298 const SCEV *Start = A->getStart(); 299 if (Start->isZero()) break; 300 const SCEV *Zero = SE.getIntegerSCEV(0, Ty); 301 AddRecs.push_back(SE.getAddRecExpr(Zero, 302 A->getStepRecurrence(SE), 303 A->getLoop())); 304 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) { 305 Ops[i] = Zero; 306 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 307 e += Add->getNumOperands(); 308 } else { 309 Ops[i] = Start; 310 } 311 } 312 if (!AddRecs.empty()) { 313 // Add the addrecs onto the end of the list. 314 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end()); 315 // Resort the operand list, moving any constants to the front. 316 SimplifyAddOperands(Ops, Ty, SE); 317 } 318} 319 320/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP 321/// instead of using ptrtoint+arithmetic+inttoptr. This helps 322/// BasicAliasAnalysis and other passes analyze the result. 323/// 324/// Design note: This depends on ScalarEvolution not recognizing inttoptr 325/// and ptrtoint operators, as they may introduce pointer arithmetic 326/// which may not be safely converted into getelementptr. 327/// 328/// Design note: It might seem desirable for this function to be more 329/// loop-aware. If some of the indices are loop-invariant while others 330/// aren't, it might seem desirable to emit multiple GEPs, keeping the 331/// loop-invariant portions of the overall computation outside the loop. 332/// However, there are a few reasons this is not done here. Hoisting simple 333/// arithmetic is a low-level optimization that often isn't very 334/// important until late in the optimization process. In fact, passes 335/// like InstructionCombining will combine GEPs, even if it means 336/// pushing loop-invariant computation down into loops, so even if the 337/// GEPs were split here, the work would quickly be undone. The 338/// LoopStrengthReduction pass, which is usually run quite late (and 339/// after the last InstructionCombining pass), takes care of hoisting 340/// loop-invariant portions of expressions, after considering what 341/// can be folded using target addressing modes. 342/// 343Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin, 344 const SCEV *const *op_end, 345 const PointerType *PTy, 346 const Type *Ty, 347 Value *V) { 348 const Type *ElTy = PTy->getElementType(); 349 SmallVector<Value *, 4> GepIndices; 350 SmallVector<const SCEV *, 8> Ops(op_begin, op_end); 351 bool AnyNonZeroIndices = false; 352 353 // Split AddRecs up into parts as either of the parts may be usable 354 // without the other. 355 SplitAddRecs(Ops, Ty, SE); 356 357 // Decend down the pointer's type and attempt to convert the other 358 // operands into GEP indices, at each level. The first index in a GEP 359 // indexes into the array implied by the pointer operand; the rest of 360 // the indices index into the element or field type selected by the 361 // preceding index. 362 for (;;) { 363 const SCEV *ElSize = SE.getAllocSizeExpr(ElTy); 364 // If the scale size is not 0, attempt to factor out a scale for 365 // array indexing. 366 SmallVector<const SCEV *, 8> ScaledOps; 367 if (ElTy->isSized() && !ElSize->isZero()) { 368 SmallVector<const SCEV *, 8> NewOps; 369 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 370 const SCEV *Op = Ops[i]; 371 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty); 372 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) { 373 // Op now has ElSize factored out. 374 ScaledOps.push_back(Op); 375 if (!Remainder->isZero()) 376 NewOps.push_back(Remainder); 377 AnyNonZeroIndices = true; 378 } else { 379 // The operand was not divisible, so add it to the list of operands 380 // we'll scan next iteration. 381 NewOps.push_back(Ops[i]); 382 } 383 } 384 // If we made any changes, update Ops. 385 if (!ScaledOps.empty()) { 386 Ops = NewOps; 387 SimplifyAddOperands(Ops, Ty, SE); 388 } 389 } 390 391 // Record the scaled array index for this level of the type. If 392 // we didn't find any operands that could be factored, tentatively 393 // assume that element zero was selected (since the zero offset 394 // would obviously be folded away). 395 Value *Scaled = ScaledOps.empty() ? 396 Constant::getNullValue(Ty) : 397 expandCodeFor(SE.getAddExpr(ScaledOps), Ty); 398 GepIndices.push_back(Scaled); 399 400 // Collect struct field index operands. 401 while (const StructType *STy = dyn_cast<StructType>(ElTy)) { 402 bool FoundFieldNo = false; 403 // An empty struct has no fields. 404 if (STy->getNumElements() == 0) break; 405 if (SE.TD) { 406 // With TargetData, field offsets are known. See if a constant offset 407 // falls within any of the struct fields. 408 if (Ops.empty()) break; 409 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0])) 410 if (SE.getTypeSizeInBits(C->getType()) <= 64) { 411 const StructLayout &SL = *SE.TD->getStructLayout(STy); 412 uint64_t FullOffset = C->getValue()->getZExtValue(); 413 if (FullOffset < SL.getSizeInBytes()) { 414 unsigned ElIdx = SL.getElementContainingOffset(FullOffset); 415 GepIndices.push_back( 416 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx)); 417 ElTy = STy->getTypeAtIndex(ElIdx); 418 Ops[0] = 419 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx)); 420 AnyNonZeroIndices = true; 421 FoundFieldNo = true; 422 } 423 } 424 } else { 425 // Without TargetData, just check for a SCEVFieldOffsetExpr of the 426 // appropriate struct type. 427 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 428 if (const SCEVFieldOffsetExpr *FO = 429 dyn_cast<SCEVFieldOffsetExpr>(Ops[i])) 430 if (FO->getStructType() == STy) { 431 unsigned FieldNo = FO->getFieldNo(); 432 GepIndices.push_back( 433 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 434 FieldNo)); 435 ElTy = STy->getTypeAtIndex(FieldNo); 436 Ops[i] = SE.getConstant(Ty, 0); 437 AnyNonZeroIndices = true; 438 FoundFieldNo = true; 439 break; 440 } 441 } 442 // If no struct field offsets were found, tentatively assume that 443 // field zero was selected (since the zero offset would obviously 444 // be folded away). 445 if (!FoundFieldNo) { 446 ElTy = STy->getTypeAtIndex(0u); 447 GepIndices.push_back( 448 Constant::getNullValue(Type::getInt32Ty(Ty->getContext()))); 449 } 450 } 451 452 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) 453 ElTy = ATy->getElementType(); 454 else 455 break; 456 } 457 458 // If none of the operands were convertable to proper GEP indices, cast 459 // the base to i8* and do an ugly getelementptr with that. It's still 460 // better than ptrtoint+arithmetic+inttoptr at least. 461 if (!AnyNonZeroIndices) { 462 // Cast the base to i8*. 463 V = InsertNoopCastOfTo(V, 464 Type::getInt8Ty(Ty->getContext())->getPointerTo(PTy->getAddressSpace())); 465 466 // Expand the operands for a plain byte offset. 467 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty); 468 469 // Fold a GEP with constant operands. 470 if (Constant *CLHS = dyn_cast<Constant>(V)) 471 if (Constant *CRHS = dyn_cast<Constant>(Idx)) 472 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1); 473 474 // Do a quick scan to see if we have this GEP nearby. If so, reuse it. 475 unsigned ScanLimit = 6; 476 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 477 // Scanning starts from the last instruction before the insertion point. 478 BasicBlock::iterator IP = Builder.GetInsertPoint(); 479 if (IP != BlockBegin) { 480 --IP; 481 for (; ScanLimit; --IP, --ScanLimit) { 482 if (IP->getOpcode() == Instruction::GetElementPtr && 483 IP->getOperand(0) == V && IP->getOperand(1) == Idx) 484 return IP; 485 if (IP == BlockBegin) break; 486 } 487 } 488 489 // Emit a GEP. 490 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep"); 491 InsertedValues.insert(GEP); 492 return GEP; 493 } 494 495 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds, 496 // because ScalarEvolution may have changed the address arithmetic to 497 // compute a value which is beyond the end of the allocated object. 498 Value *GEP = Builder.CreateGEP(V, 499 GepIndices.begin(), 500 GepIndices.end(), 501 "scevgep"); 502 Ops.push_back(SE.getUnknown(GEP)); 503 InsertedValues.insert(GEP); 504 return expand(SE.getAddExpr(Ops)); 505} 506 507Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) { 508 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 509 Value *V = expand(S->getOperand(S->getNumOperands()-1)); 510 511 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the 512 // comments on expandAddToGEP for details. 513 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) { 514 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands(); 515 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V); 516 } 517 518 V = InsertNoopCastOfTo(V, Ty); 519 520 // Emit a bunch of add instructions 521 for (int i = S->getNumOperands()-2; i >= 0; --i) { 522 Value *W = expandCodeFor(S->getOperand(i), Ty); 523 V = InsertBinop(Instruction::Add, V, W); 524 } 525 return V; 526} 527 528Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) { 529 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 530 int FirstOp = 0; // Set if we should emit a subtract. 531 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0))) 532 if (SC->getValue()->isAllOnesValue()) 533 FirstOp = 1; 534 535 int i = S->getNumOperands()-2; 536 Value *V = expandCodeFor(S->getOperand(i+1), Ty); 537 538 // Emit a bunch of multiply instructions 539 for (; i >= FirstOp; --i) { 540 Value *W = expandCodeFor(S->getOperand(i), Ty); 541 V = InsertBinop(Instruction::Mul, V, W); 542 } 543 544 // -1 * ... ---> 0 - ... 545 if (FirstOp == 1) 546 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V); 547 return V; 548} 549 550Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) { 551 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 552 553 Value *LHS = expandCodeFor(S->getLHS(), Ty); 554 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) { 555 const APInt &RHS = SC->getValue()->getValue(); 556 if (RHS.isPowerOf2()) 557 return InsertBinop(Instruction::LShr, LHS, 558 ConstantInt::get(Ty, RHS.logBase2())); 559 } 560 561 Value *RHS = expandCodeFor(S->getRHS(), Ty); 562 return InsertBinop(Instruction::UDiv, LHS, RHS); 563} 564 565/// Move parts of Base into Rest to leave Base with the minimal 566/// expression that provides a pointer operand suitable for a 567/// GEP expansion. 568static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest, 569 ScalarEvolution &SE) { 570 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) { 571 Base = A->getStart(); 572 Rest = SE.getAddExpr(Rest, 573 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()), 574 A->getStepRecurrence(SE), 575 A->getLoop())); 576 } 577 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) { 578 Base = A->getOperand(A->getNumOperands()-1); 579 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end()); 580 NewAddOps.back() = Rest; 581 Rest = SE.getAddExpr(NewAddOps); 582 ExposePointerBase(Base, Rest, SE); 583 } 584} 585 586Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) { 587 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 588 const Loop *L = S->getLoop(); 589 590 // First check for an existing canonical IV in a suitable type. 591 PHINode *CanonicalIV = 0; 592 if (PHINode *PN = L->getCanonicalInductionVariable()) 593 if (SE.isSCEVable(PN->getType()) && 594 isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) && 595 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty)) 596 CanonicalIV = PN; 597 598 // Rewrite an AddRec in terms of the canonical induction variable, if 599 // its type is more narrow. 600 if (CanonicalIV && 601 SE.getTypeSizeInBits(CanonicalIV->getType()) > 602 SE.getTypeSizeInBits(Ty)) { 603 const SCEV *Start = SE.getAnyExtendExpr(S->getStart(), 604 CanonicalIV->getType()); 605 const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE), 606 CanonicalIV->getType()); 607 Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop())); 608 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 609 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 610 BasicBlock::iterator NewInsertPt = 611 next(BasicBlock::iterator(cast<Instruction>(V))); 612 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt; 613 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0, 614 NewInsertPt); 615 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt); 616 return V; 617 } 618 619 // {X,+,F} --> X + {0,+,F} 620 if (!S->getStart()->isZero()) { 621 const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands(); 622 SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end()); 623 NewOps[0] = SE.getIntegerSCEV(0, Ty); 624 const SCEV *Rest = SE.getAddRecExpr(NewOps, L); 625 626 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the 627 // comments on expandAddToGEP for details. 628 const SCEV *Base = S->getStart(); 629 const SCEV *RestArray[1] = { Rest }; 630 // Dig into the expression to find the pointer base for a GEP. 631 ExposePointerBase(Base, RestArray[0], SE); 632 // If we found a pointer, expand the AddRec with a GEP. 633 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) { 634 // Make sure the Base isn't something exotic, such as a multiplied 635 // or divided pointer value. In those cases, the result type isn't 636 // actually a pointer type. 637 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) { 638 Value *StartV = expand(Base); 639 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!"); 640 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV); 641 } 642 } 643 644 // Just do a normal add. Pre-expand the operands to suppress folding. 645 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())), 646 SE.getUnknown(expand(Rest)))); 647 } 648 649 // {0,+,1} --> Insert a canonical induction variable into the loop! 650 if (S->isAffine() && 651 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) { 652 // If there's a canonical IV, just use it. 653 if (CanonicalIV) { 654 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) && 655 "IVs with types different from the canonical IV should " 656 "already have been handled!"); 657 return CanonicalIV; 658 } 659 660 // Create and insert the PHI node for the induction variable in the 661 // specified loop. 662 BasicBlock *Header = L->getHeader(); 663 BasicBlock *Preheader = L->getLoopPreheader(); 664 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin()); 665 InsertedValues.insert(PN); 666 PN->addIncoming(Constant::getNullValue(Ty), Preheader); 667 668 pred_iterator HPI = pred_begin(Header); 669 assert(HPI != pred_end(Header) && "Loop with zero preds???"); 670 if (!L->contains(*HPI)) ++HPI; 671 assert(HPI != pred_end(Header) && L->contains(*HPI) && 672 "No backedge in loop?"); 673 674 // Insert a unit add instruction right before the terminator corresponding 675 // to the back-edge. 676 Constant *One = ConstantInt::get(Ty, 1); 677 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next", 678 (*HPI)->getTerminator()); 679 InsertedValues.insert(Add); 680 681 pred_iterator PI = pred_begin(Header); 682 if (*PI == Preheader) 683 ++PI; 684 PN->addIncoming(Add, *PI); 685 return PN; 686 } 687 688 // {0,+,F} --> {0,+,1} * F 689 // Get the canonical induction variable I for this loop. 690 Value *I = CanonicalIV ? 691 CanonicalIV : 692 getOrInsertCanonicalInductionVariable(L, Ty); 693 694 // If this is a simple linear addrec, emit it now as a special case. 695 if (S->isAffine()) // {0,+,F} --> i*F 696 return 697 expand(SE.getTruncateOrNoop( 698 SE.getMulExpr(SE.getUnknown(I), 699 SE.getNoopOrAnyExtend(S->getOperand(1), 700 I->getType())), 701 Ty)); 702 703 // If this is a chain of recurrences, turn it into a closed form, using the 704 // folders, then expandCodeFor the closed form. This allows the folders to 705 // simplify the expression without having to build a bunch of special code 706 // into this folder. 707 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV. 708 709 // Promote S up to the canonical IV type, if the cast is foldable. 710 const SCEV *NewS = S; 711 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType()); 712 if (isa<SCEVAddRecExpr>(Ext)) 713 NewS = Ext; 714 715 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE); 716 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n"; 717 718 // Truncate the result down to the original type, if needed. 719 const SCEV *T = SE.getTruncateOrNoop(V, Ty); 720 return expand(T); 721} 722 723Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) { 724 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 725 Value *V = expandCodeFor(S->getOperand(), 726 SE.getEffectiveSCEVType(S->getOperand()->getType())); 727 Value *I = Builder.CreateTrunc(V, Ty, "tmp"); 728 InsertedValues.insert(I); 729 return I; 730} 731 732Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) { 733 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 734 Value *V = expandCodeFor(S->getOperand(), 735 SE.getEffectiveSCEVType(S->getOperand()->getType())); 736 Value *I = Builder.CreateZExt(V, Ty, "tmp"); 737 InsertedValues.insert(I); 738 return I; 739} 740 741Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) { 742 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 743 Value *V = expandCodeFor(S->getOperand(), 744 SE.getEffectiveSCEVType(S->getOperand()->getType())); 745 Value *I = Builder.CreateSExt(V, Ty, "tmp"); 746 InsertedValues.insert(I); 747 return I; 748} 749 750Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) { 751 Value *LHS = expand(S->getOperand(S->getNumOperands()-1)); 752 const Type *Ty = LHS->getType(); 753 for (int i = S->getNumOperands()-2; i >= 0; --i) { 754 // In the case of mixed integer and pointer types, do the 755 // rest of the comparisons as integer. 756 if (S->getOperand(i)->getType() != Ty) { 757 Ty = SE.getEffectiveSCEVType(Ty); 758 LHS = InsertNoopCastOfTo(LHS, Ty); 759 } 760 Value *RHS = expandCodeFor(S->getOperand(i), Ty); 761 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp"); 762 InsertedValues.insert(ICmp); 763 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax"); 764 InsertedValues.insert(Sel); 765 LHS = Sel; 766 } 767 // In the case of mixed integer and pointer types, cast the 768 // final result back to the pointer type. 769 if (LHS->getType() != S->getType()) 770 LHS = InsertNoopCastOfTo(LHS, S->getType()); 771 return LHS; 772} 773 774Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) { 775 Value *LHS = expand(S->getOperand(S->getNumOperands()-1)); 776 const Type *Ty = LHS->getType(); 777 for (int i = S->getNumOperands()-2; i >= 0; --i) { 778 // In the case of mixed integer and pointer types, do the 779 // rest of the comparisons as integer. 780 if (S->getOperand(i)->getType() != Ty) { 781 Ty = SE.getEffectiveSCEVType(Ty); 782 LHS = InsertNoopCastOfTo(LHS, Ty); 783 } 784 Value *RHS = expandCodeFor(S->getOperand(i), Ty); 785 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp"); 786 InsertedValues.insert(ICmp); 787 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax"); 788 InsertedValues.insert(Sel); 789 LHS = Sel; 790 } 791 // In the case of mixed integer and pointer types, cast the 792 // final result back to the pointer type. 793 if (LHS->getType() != S->getType()) 794 LHS = InsertNoopCastOfTo(LHS, S->getType()); 795 return LHS; 796} 797 798Value *SCEVExpander::visitFieldOffsetExpr(const SCEVFieldOffsetExpr *S) { 799 return ConstantExpr::getOffsetOf(S->getStructType(), S->getFieldNo()); 800} 801 802Value *SCEVExpander::visitAllocSizeExpr(const SCEVAllocSizeExpr *S) { 803 return ConstantExpr::getSizeOf(S->getAllocType()); 804} 805 806Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) { 807 // Expand the code for this SCEV. 808 Value *V = expand(SH); 809 if (Ty) { 810 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) && 811 "non-trivial casts should be done with the SCEVs directly!"); 812 V = InsertNoopCastOfTo(V, Ty); 813 } 814 return V; 815} 816 817Value *SCEVExpander::expand(const SCEV *S) { 818 // Compute an insertion point for this SCEV object. Hoist the instructions 819 // as far out in the loop nest as possible. 820 Instruction *InsertPt = Builder.GetInsertPoint(); 821 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ; 822 L = L->getParentLoop()) 823 if (S->isLoopInvariant(L)) { 824 if (!L) break; 825 if (BasicBlock *Preheader = L->getLoopPreheader()) 826 InsertPt = Preheader->getTerminator(); 827 } else { 828 // If the SCEV is computable at this level, insert it into the header 829 // after the PHIs (and after any other instructions that we've inserted 830 // there) so that it is guaranteed to dominate any user inside the loop. 831 if (L && S->hasComputableLoopEvolution(L)) 832 InsertPt = L->getHeader()->getFirstNonPHI(); 833 while (isInsertedInstruction(InsertPt)) 834 InsertPt = next(BasicBlock::iterator(InsertPt)); 835 break; 836 } 837 838 // Check to see if we already expanded this here. 839 std::map<std::pair<const SCEV *, Instruction *>, 840 AssertingVH<Value> >::iterator I = 841 InsertedExpressions.find(std::make_pair(S, InsertPt)); 842 if (I != InsertedExpressions.end()) 843 return I->second; 844 845 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 846 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 847 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt); 848 849 // Expand the expression into instructions. 850 Value *V = visit(S); 851 852 // Remember the expanded value for this SCEV at this location. 853 InsertedExpressions[std::make_pair(S, InsertPt)] = V; 854 855 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt); 856 return V; 857} 858 859/// getOrInsertCanonicalInductionVariable - This method returns the 860/// canonical induction variable of the specified type for the specified 861/// loop (inserting one if there is none). A canonical induction variable 862/// starts at zero and steps by one on each iteration. 863Value * 864SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L, 865 const Type *Ty) { 866 assert(Ty->isInteger() && "Can only insert integer induction variables!"); 867 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty), 868 SE.getIntegerSCEV(1, Ty), L); 869 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 870 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 871 Value *V = expandCodeFor(H, 0, L->getHeader()->begin()); 872 if (SaveInsertBB) 873 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt); 874 return V; 875} 876