LLVM  mainline
ScalarEvolutionExpander.cpp
Go to the documentation of this file.
00001 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the implementation of the scalar evolution expander,
00011 // which is used to generate the code corresponding to a given scalar evolution
00012 // expression.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/Analysis/InstructionSimplify.h"
00020 #include "llvm/Analysis/LoopInfo.h"
00021 #include "llvm/Analysis/TargetTransformInfo.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/Dominators.h"
00024 #include "llvm/IR/IntrinsicInst.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Support/Debug.h"
00028 #include "llvm/Support/raw_ostream.h"
00029 
00030 using namespace llvm;
00031 
00032 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
00033 /// reusing an existing cast if a suitable one exists, moving an existing
00034 /// cast if a suitable one exists but isn't in the right place, or
00035 /// creating a new one.
00036 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
00037                                        Instruction::CastOps Op,
00038                                        BasicBlock::iterator IP) {
00039   // This function must be called with the builder having a valid insertion
00040   // point. It doesn't need to be the actual IP where the uses of the returned
00041   // cast will be added, but it must dominate such IP.
00042   // We use this precondition to produce a cast that will dominate all its
00043   // uses. In particular, this is crucial for the case where the builder's
00044   // insertion point *is* the point where we were asked to put the cast.
00045   // Since we don't know the builder's insertion point is actually
00046   // where the uses will be added (only that it dominates it), we are
00047   // not allowed to move it.
00048   BasicBlock::iterator BIP = Builder.GetInsertPoint();
00049 
00050   Instruction *Ret = nullptr;
00051 
00052   // Check to see if there is already a cast!
00053   for (User *U : V->users())
00054     if (U->getType() == Ty)
00055       if (CastInst *CI = dyn_cast<CastInst>(U))
00056         if (CI->getOpcode() == Op) {
00057           // If the cast isn't where we want it, create a new cast at IP.
00058           // Likewise, do not reuse a cast at BIP because it must dominate
00059           // instructions that might be inserted before BIP.
00060           if (BasicBlock::iterator(CI) != IP || BIP == IP) {
00061             // Create a new cast, and leave the old cast in place in case
00062             // it is being used as an insert point. Clear its operand
00063             // so that it doesn't hold anything live.
00064             Ret = CastInst::Create(Op, V, Ty, "", IP);
00065             Ret->takeName(CI);
00066             CI->replaceAllUsesWith(Ret);
00067             CI->setOperand(0, UndefValue::get(V->getType()));
00068             break;
00069           }
00070           Ret = CI;
00071           break;
00072         }
00073 
00074   // Create a new cast.
00075   if (!Ret)
00076     Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
00077 
00078   // We assert at the end of the function since IP might point to an
00079   // instruction with different dominance properties than a cast
00080   // (an invoke for example) and not dominate BIP (but the cast does).
00081   assert(SE.DT->dominates(Ret, BIP));
00082 
00083   rememberInstruction(Ret);
00084   return Ret;
00085 }
00086 
00087 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
00088 /// which must be possible with a noop cast, doing what we can to share
00089 /// the casts.
00090 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
00091   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
00092   assert((Op == Instruction::BitCast ||
00093           Op == Instruction::PtrToInt ||
00094           Op == Instruction::IntToPtr) &&
00095          "InsertNoopCastOfTo cannot perform non-noop casts!");
00096   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
00097          "InsertNoopCastOfTo cannot change sizes!");
00098 
00099   // Short-circuit unnecessary bitcasts.
00100   if (Op == Instruction::BitCast) {
00101     if (V->getType() == Ty)
00102       return V;
00103     if (CastInst *CI = dyn_cast<CastInst>(V)) {
00104       if (CI->getOperand(0)->getType() == Ty)
00105         return CI->getOperand(0);
00106     }
00107   }
00108   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
00109   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
00110       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
00111     if (CastInst *CI = dyn_cast<CastInst>(V))
00112       if ((CI->getOpcode() == Instruction::PtrToInt ||
00113            CI->getOpcode() == Instruction::IntToPtr) &&
00114           SE.getTypeSizeInBits(CI->getType()) ==
00115           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
00116         return CI->getOperand(0);
00117     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00118       if ((CE->getOpcode() == Instruction::PtrToInt ||
00119            CE->getOpcode() == Instruction::IntToPtr) &&
00120           SE.getTypeSizeInBits(CE->getType()) ==
00121           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
00122         return CE->getOperand(0);
00123   }
00124 
00125   // Fold a cast of a constant.
00126   if (Constant *C = dyn_cast<Constant>(V))
00127     return ConstantExpr::getCast(Op, C, Ty);
00128 
00129   // Cast the argument at the beginning of the entry block, after
00130   // any bitcasts of other arguments.
00131   if (Argument *A = dyn_cast<Argument>(V)) {
00132     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
00133     while ((isa<BitCastInst>(IP) &&
00134             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
00135             cast<BitCastInst>(IP)->getOperand(0) != A) ||
00136            isa<DbgInfoIntrinsic>(IP) ||
00137            isa<LandingPadInst>(IP))
00138       ++IP;
00139     return ReuseOrCreateCast(A, Ty, Op, IP);
00140   }
00141 
00142   // Cast the instruction immediately after the instruction.
00143   Instruction *I = cast<Instruction>(V);
00144   BasicBlock::iterator IP = I; ++IP;
00145   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
00146     IP = II->getNormalDest()->begin();
00147   while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
00148     ++IP;
00149   return ReuseOrCreateCast(I, Ty, Op, IP);
00150 }
00151 
00152 /// InsertBinop - Insert the specified binary operator, doing a small amount
00153 /// of work to avoid inserting an obviously redundant operation.
00154 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
00155                                  Value *LHS, Value *RHS) {
00156   // Fold a binop with constant operands.
00157   if (Constant *CLHS = dyn_cast<Constant>(LHS))
00158     if (Constant *CRHS = dyn_cast<Constant>(RHS))
00159       return ConstantExpr::get(Opcode, CLHS, CRHS);
00160 
00161   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
00162   unsigned ScanLimit = 6;
00163   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
00164   // Scanning starts from the last instruction before the insertion point.
00165   BasicBlock::iterator IP = Builder.GetInsertPoint();
00166   if (IP != BlockBegin) {
00167     --IP;
00168     for (; ScanLimit; --IP, --ScanLimit) {
00169       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
00170       // generated code.
00171       if (isa<DbgInfoIntrinsic>(IP))
00172         ScanLimit++;
00173       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
00174           IP->getOperand(1) == RHS)
00175         return IP;
00176       if (IP == BlockBegin) break;
00177     }
00178   }
00179 
00180   // Save the original insertion point so we can restore it when we're done.
00181   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
00182   BuilderType::InsertPointGuard Guard(Builder);
00183 
00184   // Move the insertion point out of as many loops as we can.
00185   while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
00186     if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
00187     BasicBlock *Preheader = L->getLoopPreheader();
00188     if (!Preheader) break;
00189 
00190     // Ok, move up a level.
00191     Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
00192   }
00193 
00194   // If we haven't found this binop, insert it.
00195   Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
00196   BO->setDebugLoc(Loc);
00197   rememberInstruction(BO);
00198 
00199   return BO;
00200 }
00201 
00202 /// FactorOutConstant - Test if S is divisible by Factor, using signed
00203 /// division. If so, update S with Factor divided out and return true.
00204 /// S need not be evenly divisible if a reasonable remainder can be
00205 /// computed.
00206 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
00207 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
00208 /// check to see if the divide was folded.
00209 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
00210                               const SCEV *Factor, ScalarEvolution &SE,
00211                               const DataLayout &DL) {
00212   // Everything is divisible by one.
00213   if (Factor->isOne())
00214     return true;
00215 
00216   // x/x == 1.
00217   if (S == Factor) {
00218     S = SE.getConstant(S->getType(), 1);
00219     return true;
00220   }
00221 
00222   // For a Constant, check for a multiple of the given factor.
00223   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
00224     // 0/x == 0.
00225     if (C->isZero())
00226       return true;
00227     // Check for divisibility.
00228     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
00229       ConstantInt *CI =
00230         ConstantInt::get(SE.getContext(),
00231                          C->getValue()->getValue().sdiv(
00232                                                    FC->getValue()->getValue()));
00233       // If the quotient is zero and the remainder is non-zero, reject
00234       // the value at this scale. It will be considered for subsequent
00235       // smaller scales.
00236       if (!CI->isZero()) {
00237         const SCEV *Div = SE.getConstant(CI);
00238         S = Div;
00239         Remainder =
00240           SE.getAddExpr(Remainder,
00241                         SE.getConstant(C->getValue()->getValue().srem(
00242                                                   FC->getValue()->getValue())));
00243         return true;
00244       }
00245     }
00246   }
00247 
00248   // In a Mul, check if there is a constant operand which is a multiple
00249   // of the given factor.
00250   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
00251     // Size is known, check if there is a constant operand which is a multiple
00252     // of the given factor. If so, we can factor it.
00253     const SCEVConstant *FC = cast<SCEVConstant>(Factor);
00254     if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
00255       if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
00256         SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
00257         NewMulOps[0] = SE.getConstant(
00258             C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
00259         S = SE.getMulExpr(NewMulOps);
00260         return true;
00261       }
00262   }
00263 
00264   // In an AddRec, check if both start and step are divisible.
00265   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
00266     const SCEV *Step = A->getStepRecurrence(SE);
00267     const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
00268     if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
00269       return false;
00270     if (!StepRem->isZero())
00271       return false;
00272     const SCEV *Start = A->getStart();
00273     if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
00274       return false;
00275     S = SE.getAddRecExpr(Start, Step, A->getLoop(),
00276                          A->getNoWrapFlags(SCEV::FlagNW));
00277     return true;
00278   }
00279 
00280   return false;
00281 }
00282 
00283 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
00284 /// is the number of SCEVAddRecExprs present, which are kept at the end of
00285 /// the list.
00286 ///
00287 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
00288                                 Type *Ty,
00289                                 ScalarEvolution &SE) {
00290   unsigned NumAddRecs = 0;
00291   for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
00292     ++NumAddRecs;
00293   // Group Ops into non-addrecs and addrecs.
00294   SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
00295   SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
00296   // Let ScalarEvolution sort and simplify the non-addrecs list.
00297   const SCEV *Sum = NoAddRecs.empty() ?
00298                     SE.getConstant(Ty, 0) :
00299                     SE.getAddExpr(NoAddRecs);
00300   // If it returned an add, use the operands. Otherwise it simplified
00301   // the sum into a single value, so just use that.
00302   Ops.clear();
00303   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
00304     Ops.append(Add->op_begin(), Add->op_end());
00305   else if (!Sum->isZero())
00306     Ops.push_back(Sum);
00307   // Then append the addrecs.
00308   Ops.append(AddRecs.begin(), AddRecs.end());
00309 }
00310 
00311 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
00312 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
00313 /// This helps expose more opportunities for folding parts of the expressions
00314 /// into GEP indices.
00315 ///
00316 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
00317                          Type *Ty,
00318                          ScalarEvolution &SE) {
00319   // Find the addrecs.
00320   SmallVector<const SCEV *, 8> AddRecs;
00321   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00322     while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
00323       const SCEV *Start = A->getStart();
00324       if (Start->isZero()) break;
00325       const SCEV *Zero = SE.getConstant(Ty, 0);
00326       AddRecs.push_back(SE.getAddRecExpr(Zero,
00327                                          A->getStepRecurrence(SE),
00328                                          A->getLoop(),
00329                                          A->getNoWrapFlags(SCEV::FlagNW)));
00330       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
00331         Ops[i] = Zero;
00332         Ops.append(Add->op_begin(), Add->op_end());
00333         e += Add->getNumOperands();
00334       } else {
00335         Ops[i] = Start;
00336       }
00337     }
00338   if (!AddRecs.empty()) {
00339     // Add the addrecs onto the end of the list.
00340     Ops.append(AddRecs.begin(), AddRecs.end());
00341     // Resort the operand list, moving any constants to the front.
00342     SimplifyAddOperands(Ops, Ty, SE);
00343   }
00344 }
00345 
00346 /// expandAddToGEP - Expand an addition expression with a pointer type into
00347 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
00348 /// BasicAliasAnalysis and other passes analyze the result. See the rules
00349 /// for getelementptr vs. inttoptr in
00350 /// http://llvm.org/docs/LangRef.html#pointeraliasing
00351 /// for details.
00352 ///
00353 /// Design note: The correctness of using getelementptr here depends on
00354 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
00355 /// they may introduce pointer arithmetic which may not be safely converted
00356 /// into getelementptr.
00357 ///
00358 /// Design note: It might seem desirable for this function to be more
00359 /// loop-aware. If some of the indices are loop-invariant while others
00360 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
00361 /// loop-invariant portions of the overall computation outside the loop.
00362 /// However, there are a few reasons this is not done here. Hoisting simple
00363 /// arithmetic is a low-level optimization that often isn't very
00364 /// important until late in the optimization process. In fact, passes
00365 /// like InstructionCombining will combine GEPs, even if it means
00366 /// pushing loop-invariant computation down into loops, so even if the
00367 /// GEPs were split here, the work would quickly be undone. The
00368 /// LoopStrengthReduction pass, which is usually run quite late (and
00369 /// after the last InstructionCombining pass), takes care of hoisting
00370 /// loop-invariant portions of expressions, after considering what
00371 /// can be folded using target addressing modes.
00372 ///
00373 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
00374                                     const SCEV *const *op_end,
00375                                     PointerType *PTy,
00376                                     Type *Ty,
00377                                     Value *V) {
00378   Type *OriginalElTy = PTy->getElementType();
00379   Type *ElTy = OriginalElTy;
00380   SmallVector<Value *, 4> GepIndices;
00381   SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
00382   bool AnyNonZeroIndices = false;
00383 
00384   // Split AddRecs up into parts as either of the parts may be usable
00385   // without the other.
00386   SplitAddRecs(Ops, Ty, SE);
00387 
00388   Type *IntPtrTy = DL.getIntPtrType(PTy);
00389 
00390   // Descend down the pointer's type and attempt to convert the other
00391   // operands into GEP indices, at each level. The first index in a GEP
00392   // indexes into the array implied by the pointer operand; the rest of
00393   // the indices index into the element or field type selected by the
00394   // preceding index.
00395   for (;;) {
00396     // If the scale size is not 0, attempt to factor out a scale for
00397     // array indexing.
00398     SmallVector<const SCEV *, 8> ScaledOps;
00399     if (ElTy->isSized()) {
00400       const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
00401       if (!ElSize->isZero()) {
00402         SmallVector<const SCEV *, 8> NewOps;
00403         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00404           const SCEV *Op = Ops[i];
00405           const SCEV *Remainder = SE.getConstant(Ty, 0);
00406           if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
00407             // Op now has ElSize factored out.
00408             ScaledOps.push_back(Op);
00409             if (!Remainder->isZero())
00410               NewOps.push_back(Remainder);
00411             AnyNonZeroIndices = true;
00412           } else {
00413             // The operand was not divisible, so add it to the list of operands
00414             // we'll scan next iteration.
00415             NewOps.push_back(Ops[i]);
00416           }
00417         }
00418         // If we made any changes, update Ops.
00419         if (!ScaledOps.empty()) {
00420           Ops = NewOps;
00421           SimplifyAddOperands(Ops, Ty, SE);
00422         }
00423       }
00424     }
00425 
00426     // Record the scaled array index for this level of the type. If
00427     // we didn't find any operands that could be factored, tentatively
00428     // assume that element zero was selected (since the zero offset
00429     // would obviously be folded away).
00430     Value *Scaled = ScaledOps.empty() ?
00431                     Constant::getNullValue(Ty) :
00432                     expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
00433     GepIndices.push_back(Scaled);
00434 
00435     // Collect struct field index operands.
00436     while (StructType *STy = dyn_cast<StructType>(ElTy)) {
00437       bool FoundFieldNo = false;
00438       // An empty struct has no fields.
00439       if (STy->getNumElements() == 0) break;
00440       // Field offsets are known. See if a constant offset falls within any of
00441       // the struct fields.
00442       if (Ops.empty())
00443         break;
00444       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
00445         if (SE.getTypeSizeInBits(C->getType()) <= 64) {
00446           const StructLayout &SL = *DL.getStructLayout(STy);
00447           uint64_t FullOffset = C->getValue()->getZExtValue();
00448           if (FullOffset < SL.getSizeInBytes()) {
00449             unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
00450             GepIndices.push_back(
00451                 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
00452             ElTy = STy->getTypeAtIndex(ElIdx);
00453             Ops[0] =
00454                 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
00455             AnyNonZeroIndices = true;
00456             FoundFieldNo = true;
00457           }
00458         }
00459       // If no struct field offsets were found, tentatively assume that
00460       // field zero was selected (since the zero offset would obviously
00461       // be folded away).
00462       if (!FoundFieldNo) {
00463         ElTy = STy->getTypeAtIndex(0u);
00464         GepIndices.push_back(
00465           Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
00466       }
00467     }
00468 
00469     if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
00470       ElTy = ATy->getElementType();
00471     else
00472       break;
00473   }
00474 
00475   // If none of the operands were convertible to proper GEP indices, cast
00476   // the base to i8* and do an ugly getelementptr with that. It's still
00477   // better than ptrtoint+arithmetic+inttoptr at least.
00478   if (!AnyNonZeroIndices) {
00479     // Cast the base to i8*.
00480     V = InsertNoopCastOfTo(V,
00481        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
00482 
00483     assert(!isa<Instruction>(V) ||
00484            SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
00485 
00486     // Expand the operands for a plain byte offset.
00487     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
00488 
00489     // Fold a GEP with constant operands.
00490     if (Constant *CLHS = dyn_cast<Constant>(V))
00491       if (Constant *CRHS = dyn_cast<Constant>(Idx))
00492         return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
00493                                               CLHS, CRHS);
00494 
00495     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
00496     unsigned ScanLimit = 6;
00497     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
00498     // Scanning starts from the last instruction before the insertion point.
00499     BasicBlock::iterator IP = Builder.GetInsertPoint();
00500     if (IP != BlockBegin) {
00501       --IP;
00502       for (; ScanLimit; --IP, --ScanLimit) {
00503         // Don't count dbg.value against the ScanLimit, to avoid perturbing the
00504         // generated code.
00505         if (isa<DbgInfoIntrinsic>(IP))
00506           ScanLimit++;
00507         if (IP->getOpcode() == Instruction::GetElementPtr &&
00508             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
00509           return IP;
00510         if (IP == BlockBegin) break;
00511       }
00512     }
00513 
00514     // Save the original insertion point so we can restore it when we're done.
00515     BuilderType::InsertPointGuard Guard(Builder);
00516 
00517     // Move the insertion point out of as many loops as we can.
00518     while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
00519       if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
00520       BasicBlock *Preheader = L->getLoopPreheader();
00521       if (!Preheader) break;
00522 
00523       // Ok, move up a level.
00524       Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
00525     }
00526 
00527     // Emit a GEP.
00528     Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
00529     rememberInstruction(GEP);
00530 
00531     return GEP;
00532   }
00533 
00534   // Save the original insertion point so we can restore it when we're done.
00535   BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
00536 
00537   // Move the insertion point out of as many loops as we can.
00538   while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
00539     if (!L->isLoopInvariant(V)) break;
00540 
00541     bool AnyIndexNotLoopInvariant = false;
00542     for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
00543          E = GepIndices.end(); I != E; ++I)
00544       if (!L->isLoopInvariant(*I)) {
00545         AnyIndexNotLoopInvariant = true;
00546         break;
00547       }
00548     if (AnyIndexNotLoopInvariant)
00549       break;
00550 
00551     BasicBlock *Preheader = L->getLoopPreheader();
00552     if (!Preheader) break;
00553 
00554     // Ok, move up a level.
00555     Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
00556   }
00557 
00558   // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
00559   // because ScalarEvolution may have changed the address arithmetic to
00560   // compute a value which is beyond the end of the allocated object.
00561   Value *Casted = V;
00562   if (V->getType() != PTy)
00563     Casted = InsertNoopCastOfTo(Casted, PTy);
00564   Value *GEP = Builder.CreateGEP(OriginalElTy, Casted,
00565                                  GepIndices,
00566                                  "scevgep");
00567   Ops.push_back(SE.getUnknown(GEP));
00568   rememberInstruction(GEP);
00569 
00570   // Restore the original insert point.
00571   Builder.restoreIP(SaveInsertPt);
00572 
00573   return expand(SE.getAddExpr(Ops));
00574 }
00575 
00576 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
00577 /// SCEV expansion. If they are nested, this is the most nested. If they are
00578 /// neighboring, pick the later.
00579 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
00580                                         DominatorTree &DT) {
00581   if (!A) return B;
00582   if (!B) return A;
00583   if (A->contains(B)) return B;
00584   if (B->contains(A)) return A;
00585   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
00586   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
00587   return A; // Arbitrarily break the tie.
00588 }
00589 
00590 /// getRelevantLoop - Get the most relevant loop associated with the given
00591 /// expression, according to PickMostRelevantLoop.
00592 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
00593   // Test whether we've already computed the most relevant loop for this SCEV.
00594   std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
00595     RelevantLoops.insert(std::make_pair(S, nullptr));
00596   if (!Pair.second)
00597     return Pair.first->second;
00598 
00599   if (isa<SCEVConstant>(S))
00600     // A constant has no relevant loops.
00601     return nullptr;
00602   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
00603     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
00604       return Pair.first->second = SE.LI->getLoopFor(I->getParent());
00605     // A non-instruction has no relevant loops.
00606     return nullptr;
00607   }
00608   if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
00609     const Loop *L = nullptr;
00610     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
00611       L = AR->getLoop();
00612     for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
00613          I != E; ++I)
00614       L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
00615     return RelevantLoops[N] = L;
00616   }
00617   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
00618     const Loop *Result = getRelevantLoop(C->getOperand());
00619     return RelevantLoops[C] = Result;
00620   }
00621   if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
00622     const Loop *Result =
00623       PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
00624                            getRelevantLoop(D->getRHS()),
00625                            *SE.DT);
00626     return RelevantLoops[D] = Result;
00627   }
00628   llvm_unreachable("Unexpected SCEV type!");
00629 }
00630 
00631 namespace {
00632 
00633 /// LoopCompare - Compare loops by PickMostRelevantLoop.
00634 class LoopCompare {
00635   DominatorTree &DT;
00636 public:
00637   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
00638 
00639   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
00640                   std::pair<const Loop *, const SCEV *> RHS) const {
00641     // Keep pointer operands sorted at the end.
00642     if (LHS.second->getType()->isPointerTy() !=
00643         RHS.second->getType()->isPointerTy())
00644       return LHS.second->getType()->isPointerTy();
00645 
00646     // Compare loops with PickMostRelevantLoop.
00647     if (LHS.first != RHS.first)
00648       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
00649 
00650     // If one operand is a non-constant negative and the other is not,
00651     // put the non-constant negative on the right so that a sub can
00652     // be used instead of a negate and add.
00653     if (LHS.second->isNonConstantNegative()) {
00654       if (!RHS.second->isNonConstantNegative())
00655         return false;
00656     } else if (RHS.second->isNonConstantNegative())
00657       return true;
00658 
00659     // Otherwise they are equivalent according to this comparison.
00660     return false;
00661   }
00662 };
00663 
00664 }
00665 
00666 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
00667   Type *Ty = SE.getEffectiveSCEVType(S->getType());
00668 
00669   // Collect all the add operands in a loop, along with their associated loops.
00670   // Iterate in reverse so that constants are emitted last, all else equal, and
00671   // so that pointer operands are inserted first, which the code below relies on
00672   // to form more involved GEPs.
00673   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
00674   for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
00675        E(S->op_begin()); I != E; ++I)
00676     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
00677 
00678   // Sort by loop. Use a stable sort so that constants follow non-constants and
00679   // pointer operands precede non-pointer operands.
00680   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
00681 
00682   // Emit instructions to add all the operands. Hoist as much as possible
00683   // out of loops, and form meaningful getelementptrs where possible.
00684   Value *Sum = nullptr;
00685   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
00686        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
00687     const Loop *CurLoop = I->first;
00688     const SCEV *Op = I->second;
00689     if (!Sum) {
00690       // This is the first operand. Just expand it.
00691       Sum = expand(Op);
00692       ++I;
00693     } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
00694       // The running sum expression is a pointer. Try to form a getelementptr
00695       // at this level with that as the base.
00696       SmallVector<const SCEV *, 4> NewOps;
00697       for (; I != E && I->first == CurLoop; ++I) {
00698         // If the operand is SCEVUnknown and not instructions, peek through
00699         // it, to enable more of it to be folded into the GEP.
00700         const SCEV *X = I->second;
00701         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
00702           if (!isa<Instruction>(U->getValue()))
00703             X = SE.getSCEV(U->getValue());
00704         NewOps.push_back(X);
00705       }
00706       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
00707     } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
00708       // The running sum is an integer, and there's a pointer at this level.
00709       // Try to form a getelementptr. If the running sum is instructions,
00710       // use a SCEVUnknown to avoid re-analyzing them.
00711       SmallVector<const SCEV *, 4> NewOps;
00712       NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
00713                                                SE.getSCEV(Sum));
00714       for (++I; I != E && I->first == CurLoop; ++I)
00715         NewOps.push_back(I->second);
00716       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
00717     } else if (Op->isNonConstantNegative()) {
00718       // Instead of doing a negate and add, just do a subtract.
00719       Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
00720       Sum = InsertNoopCastOfTo(Sum, Ty);
00721       Sum = InsertBinop(Instruction::Sub, Sum, W);
00722       ++I;
00723     } else {
00724       // A simple add.
00725       Value *W = expandCodeFor(Op, Ty);
00726       Sum = InsertNoopCastOfTo(Sum, Ty);
00727       // Canonicalize a constant to the RHS.
00728       if (isa<Constant>(Sum)) std::swap(Sum, W);
00729       Sum = InsertBinop(Instruction::Add, Sum, W);
00730       ++I;
00731     }
00732   }
00733 
00734   return Sum;
00735 }
00736 
00737 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
00738   Type *Ty = SE.getEffectiveSCEVType(S->getType());
00739 
00740   // Collect all the mul operands in a loop, along with their associated loops.
00741   // Iterate in reverse so that constants are emitted last, all else equal.
00742   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
00743   for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
00744        E(S->op_begin()); I != E; ++I)
00745     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
00746 
00747   // Sort by loop. Use a stable sort so that constants follow non-constants.
00748   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
00749 
00750   // Emit instructions to mul all the operands. Hoist as much as possible
00751   // out of loops.
00752   Value *Prod = nullptr;
00753   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
00754        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
00755     const SCEV *Op = I->second;
00756     if (!Prod) {
00757       // This is the first operand. Just expand it.
00758       Prod = expand(Op);
00759       ++I;
00760     } else if (Op->isAllOnesValue()) {
00761       // Instead of doing a multiply by negative one, just do a negate.
00762       Prod = InsertNoopCastOfTo(Prod, Ty);
00763       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
00764       ++I;
00765     } else {
00766       // A simple mul.
00767       Value *W = expandCodeFor(Op, Ty);
00768       Prod = InsertNoopCastOfTo(Prod, Ty);
00769       // Canonicalize a constant to the RHS.
00770       if (isa<Constant>(Prod)) std::swap(Prod, W);
00771       Prod = InsertBinop(Instruction::Mul, Prod, W);
00772       ++I;
00773     }
00774   }
00775 
00776   return Prod;
00777 }
00778 
00779 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
00780   Type *Ty = SE.getEffectiveSCEVType(S->getType());
00781 
00782   Value *LHS = expandCodeFor(S->getLHS(), Ty);
00783   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
00784     const APInt &RHS = SC->getValue()->getValue();
00785     if (RHS.isPowerOf2())
00786       return InsertBinop(Instruction::LShr, LHS,
00787                          ConstantInt::get(Ty, RHS.logBase2()));
00788   }
00789 
00790   Value *RHS = expandCodeFor(S->getRHS(), Ty);
00791   return InsertBinop(Instruction::UDiv, LHS, RHS);
00792 }
00793 
00794 /// Move parts of Base into Rest to leave Base with the minimal
00795 /// expression that provides a pointer operand suitable for a
00796 /// GEP expansion.
00797 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
00798                               ScalarEvolution &SE) {
00799   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
00800     Base = A->getStart();
00801     Rest = SE.getAddExpr(Rest,
00802                          SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
00803                                           A->getStepRecurrence(SE),
00804                                           A->getLoop(),
00805                                           A->getNoWrapFlags(SCEV::FlagNW)));
00806   }
00807   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
00808     Base = A->getOperand(A->getNumOperands()-1);
00809     SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
00810     NewAddOps.back() = Rest;
00811     Rest = SE.getAddExpr(NewAddOps);
00812     ExposePointerBase(Base, Rest, SE);
00813   }
00814 }
00815 
00816 /// Determine if this is a well-behaved chain of instructions leading back to
00817 /// the PHI. If so, it may be reused by expanded expressions.
00818 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
00819                                          const Loop *L) {
00820   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
00821       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
00822     return false;
00823   // If any of the operands don't dominate the insert position, bail.
00824   // Addrec operands are always loop-invariant, so this can only happen
00825   // if there are instructions which haven't been hoisted.
00826   if (L == IVIncInsertLoop) {
00827     for (User::op_iterator OI = IncV->op_begin()+1,
00828            OE = IncV->op_end(); OI != OE; ++OI)
00829       if (Instruction *OInst = dyn_cast<Instruction>(OI))
00830         if (!SE.DT->dominates(OInst, IVIncInsertPos))
00831           return false;
00832   }
00833   // Advance to the next instruction.
00834   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
00835   if (!IncV)
00836     return false;
00837 
00838   if (IncV->mayHaveSideEffects())
00839     return false;
00840 
00841   if (IncV != PN)
00842     return true;
00843 
00844   return isNormalAddRecExprPHI(PN, IncV, L);
00845 }
00846 
00847 /// getIVIncOperand returns an induction variable increment's induction
00848 /// variable operand.
00849 ///
00850 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
00851 /// operands dominate InsertPos.
00852 ///
00853 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
00854 /// simple patterns generated by getAddRecExprPHILiterally and
00855 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
00856 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
00857                                            Instruction *InsertPos,
00858                                            bool allowScale) {
00859   if (IncV == InsertPos)
00860     return nullptr;
00861 
00862   switch (IncV->getOpcode()) {
00863   default:
00864     return nullptr;
00865   // Check for a simple Add/Sub or GEP of a loop invariant step.
00866   case Instruction::Add:
00867   case Instruction::Sub: {
00868     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
00869     if (!OInst || SE.DT->dominates(OInst, InsertPos))
00870       return dyn_cast<Instruction>(IncV->getOperand(0));
00871     return nullptr;
00872   }
00873   case Instruction::BitCast:
00874     return dyn_cast<Instruction>(IncV->getOperand(0));
00875   case Instruction::GetElementPtr:
00876     for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
00877          I != E; ++I) {
00878       if (isa<Constant>(*I))
00879         continue;
00880       if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
00881         if (!SE.DT->dominates(OInst, InsertPos))
00882           return nullptr;
00883       }
00884       if (allowScale) {
00885         // allow any kind of GEP as long as it can be hoisted.
00886         continue;
00887       }
00888       // This must be a pointer addition of constants (pretty), which is already
00889       // handled, or some number of address-size elements (ugly). Ugly geps
00890       // have 2 operands. i1* is used by the expander to represent an
00891       // address-size element.
00892       if (IncV->getNumOperands() != 2)
00893         return nullptr;
00894       unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
00895       if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
00896           && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
00897         return nullptr;
00898       break;
00899     }
00900     return dyn_cast<Instruction>(IncV->getOperand(0));
00901   }
00902 }
00903 
00904 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
00905 /// it available to other uses in this loop. Recursively hoist any operands,
00906 /// until we reach a value that dominates InsertPos.
00907 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
00908   if (SE.DT->dominates(IncV, InsertPos))
00909       return true;
00910 
00911   // InsertPos must itself dominate IncV so that IncV's new position satisfies
00912   // its existing users.
00913   if (isa<PHINode>(InsertPos)
00914       || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
00915     return false;
00916 
00917   // Check that the chain of IV operands leading back to Phi can be hoisted.
00918   SmallVector<Instruction*, 4> IVIncs;
00919   for(;;) {
00920     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
00921     if (!Oper)
00922       return false;
00923     // IncV is safe to hoist.
00924     IVIncs.push_back(IncV);
00925     IncV = Oper;
00926     if (SE.DT->dominates(IncV, InsertPos))
00927       break;
00928   }
00929   for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
00930          E = IVIncs.rend(); I != E; ++I) {
00931     (*I)->moveBefore(InsertPos);
00932   }
00933   return true;
00934 }
00935 
00936 /// Determine if this cyclic phi is in a form that would have been generated by
00937 /// LSR. We don't care if the phi was actually expanded in this pass, as long
00938 /// as it is in a low-cost form, for example, no implied multiplication. This
00939 /// should match any patterns generated by getAddRecExprPHILiterally and
00940 /// expandAddtoGEP.
00941 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
00942                                            const Loop *L) {
00943   for(Instruction *IVOper = IncV;
00944       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
00945                                 /*allowScale=*/false));) {
00946     if (IVOper == PN)
00947       return true;
00948   }
00949   return false;
00950 }
00951 
00952 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
00953 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
00954 /// need to materialize IV increments elsewhere to handle difficult situations.
00955 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
00956                                  Type *ExpandTy, Type *IntTy,
00957                                  bool useSubtract) {
00958   Value *IncV;
00959   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
00960   if (ExpandTy->isPointerTy()) {
00961     PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
00962     // If the step isn't constant, don't use an implicitly scaled GEP, because
00963     // that would require a multiply inside the loop.
00964     if (!isa<ConstantInt>(StepV))
00965       GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
00966                                   GEPPtrTy->getAddressSpace());
00967     const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
00968     IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
00969     if (IncV->getType() != PN->getType()) {
00970       IncV = Builder.CreateBitCast(IncV, PN->getType());
00971       rememberInstruction(IncV);
00972     }
00973   } else {
00974     IncV = useSubtract ?
00975       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
00976       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
00977     rememberInstruction(IncV);
00978   }
00979   return IncV;
00980 }
00981 
00982 /// \brief Hoist the addrec instruction chain rooted in the loop phi above the
00983 /// position. This routine assumes that this is possible (has been checked).
00984 static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
00985                            Instruction *Pos, PHINode *LoopPhi) {
00986   do {
00987     if (DT->dominates(InstToHoist, Pos))
00988       break;
00989     // Make sure the increment is where we want it. But don't move it
00990     // down past a potential existing post-inc user.
00991     InstToHoist->moveBefore(Pos);
00992     Pos = InstToHoist;
00993     InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
00994   } while (InstToHoist != LoopPhi);
00995 }
00996 
00997 /// \brief Check whether we can cheaply express the requested SCEV in terms of
00998 /// the available PHI SCEV by truncation and/or invertion of the step.
00999 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
01000                                     const SCEVAddRecExpr *Phi,
01001                                     const SCEVAddRecExpr *Requested,
01002                                     bool &InvertStep) {
01003   Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
01004   Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
01005 
01006   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
01007     return false;
01008 
01009   // Try truncate it if necessary.
01010   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
01011   if (!Phi)
01012     return false;
01013 
01014   // Check whether truncation will help.
01015   if (Phi == Requested) {
01016     InvertStep = false;
01017     return true;
01018   }
01019 
01020   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
01021   if (SE.getAddExpr(Requested->getStart(),
01022                     SE.getNegativeSCEV(Requested)) == Phi) {
01023     InvertStep = true;
01024     return true;
01025   }
01026 
01027   return false;
01028 }
01029 
01030 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
01031   if (!isa<IntegerType>(AR->getType()))
01032     return false;
01033 
01034   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
01035   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
01036   const SCEV *Step = AR->getStepRecurrence(SE);
01037   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
01038                                             SE.getSignExtendExpr(AR, WideTy));
01039   const SCEV *ExtendAfterOp =
01040     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
01041   return ExtendAfterOp == OpAfterExtend;
01042 }
01043 
01044 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
01045   if (!isa<IntegerType>(AR->getType()))
01046     return false;
01047 
01048   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
01049   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
01050   const SCEV *Step = AR->getStepRecurrence(SE);
01051   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
01052                                             SE.getZeroExtendExpr(AR, WideTy));
01053   const SCEV *ExtendAfterOp =
01054     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
01055   return ExtendAfterOp == OpAfterExtend;
01056 }
01057 
01058 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
01059 /// the base addrec, which is the addrec without any non-loop-dominating
01060 /// values, and return the PHI.
01061 PHINode *
01062 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
01063                                         const Loop *L,
01064                                         Type *ExpandTy,
01065                                         Type *IntTy,
01066                                         Type *&TruncTy,
01067                                         bool &InvertStep) {
01068   assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
01069 
01070   // Reuse a previously-inserted PHI, if present.
01071   BasicBlock *LatchBlock = L->getLoopLatch();
01072   if (LatchBlock) {
01073     PHINode *AddRecPhiMatch = nullptr;
01074     Instruction *IncV = nullptr;
01075     TruncTy = nullptr;
01076     InvertStep = false;
01077 
01078     // Only try partially matching scevs that need truncation and/or
01079     // step-inversion if we know this loop is outside the current loop.
01080     bool TryNonMatchingSCEV = IVIncInsertLoop &&
01081       SE.DT->properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
01082 
01083     for (BasicBlock::iterator I = L->getHeader()->begin();
01084          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01085       if (!SE.isSCEVable(PN->getType()))
01086         continue;
01087 
01088       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
01089       if (!PhiSCEV)
01090         continue;
01091 
01092       bool IsMatchingSCEV = PhiSCEV == Normalized;
01093       // We only handle truncation and inversion of phi recurrences for the
01094       // expanded expression if the expanded expression's loop dominates the
01095       // loop we insert to. Check now, so we can bail out early.
01096       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
01097           continue;
01098 
01099       Instruction *TempIncV =
01100           cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
01101 
01102       // Check whether we can reuse this PHI node.
01103       if (LSRMode) {
01104         if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
01105           continue;
01106         if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
01107           continue;
01108       } else {
01109         if (!isNormalAddRecExprPHI(PN, TempIncV, L))
01110           continue;
01111       }
01112 
01113       // Stop if we have found an exact match SCEV.
01114       if (IsMatchingSCEV) {
01115         IncV = TempIncV;
01116         TruncTy = nullptr;
01117         InvertStep = false;
01118         AddRecPhiMatch = PN;
01119         break;
01120       }
01121 
01122       // Try whether the phi can be translated into the requested form
01123       // (truncated and/or offset by a constant).
01124       if ((!TruncTy || InvertStep) &&
01125           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
01126         // Record the phi node. But don't stop we might find an exact match
01127         // later.
01128         AddRecPhiMatch = PN;
01129         IncV = TempIncV;
01130         TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
01131       }
01132     }
01133 
01134     if (AddRecPhiMatch) {
01135       // Potentially, move the increment. We have made sure in
01136       // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
01137       if (L == IVIncInsertLoop)
01138         hoistBeforePos(SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
01139 
01140       // Ok, the add recurrence looks usable.
01141       // Remember this PHI, even in post-inc mode.
01142       InsertedValues.insert(AddRecPhiMatch);
01143       // Remember the increment.
01144       rememberInstruction(IncV);
01145       return AddRecPhiMatch;
01146     }
01147   }
01148 
01149   // Save the original insertion point so we can restore it when we're done.
01150   BuilderType::InsertPointGuard Guard(Builder);
01151 
01152   // Another AddRec may need to be recursively expanded below. For example, if
01153   // this AddRec is quadratic, the StepV may itself be an AddRec in this
01154   // loop. Remove this loop from the PostIncLoops set before expanding such
01155   // AddRecs. Otherwise, we cannot find a valid position for the step
01156   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
01157   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
01158   // so it's not worth implementing SmallPtrSet::swap.
01159   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
01160   PostIncLoops.clear();
01161 
01162   // Expand code for the start value.
01163   Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
01164                                 L->getHeader()->begin());
01165 
01166   // StartV must be hoisted into L's preheader to dominate the new phi.
01167   assert(!isa<Instruction>(StartV) ||
01168          SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
01169                                   L->getHeader()));
01170 
01171   // Expand code for the step value. Do this before creating the PHI so that PHI
01172   // reuse code doesn't see an incomplete PHI.
01173   const SCEV *Step = Normalized->getStepRecurrence(SE);
01174   // If the stride is negative, insert a sub instead of an add for the increment
01175   // (unless it's a constant, because subtracts of constants are canonicalized
01176   // to adds).
01177   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
01178   if (useSubtract)
01179     Step = SE.getNegativeSCEV(Step);
01180   // Expand the step somewhere that dominates the loop header.
01181   Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
01182 
01183   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
01184   // we actually do emit an addition.  It does not apply if we emit a
01185   // subtraction.
01186   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
01187   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
01188 
01189   // Create the PHI.
01190   BasicBlock *Header = L->getHeader();
01191   Builder.SetInsertPoint(Header, Header->begin());
01192   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
01193   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
01194                                   Twine(IVName) + ".iv");
01195   rememberInstruction(PN);
01196 
01197   // Create the step instructions and populate the PHI.
01198   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
01199     BasicBlock *Pred = *HPI;
01200 
01201     // Add a start value.
01202     if (!L->contains(Pred)) {
01203       PN->addIncoming(StartV, Pred);
01204       continue;
01205     }
01206 
01207     // Create a step value and add it to the PHI.
01208     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
01209     // instructions at IVIncInsertPos.
01210     Instruction *InsertPos = L == IVIncInsertLoop ?
01211       IVIncInsertPos : Pred->getTerminator();
01212     Builder.SetInsertPoint(InsertPos);
01213     Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
01214 
01215     if (isa<OverflowingBinaryOperator>(IncV)) {
01216       if (IncrementIsNUW)
01217         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
01218       if (IncrementIsNSW)
01219         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
01220     }
01221     PN->addIncoming(IncV, Pred);
01222   }
01223 
01224   // After expanding subexpressions, restore the PostIncLoops set so the caller
01225   // can ensure that IVIncrement dominates the current uses.
01226   PostIncLoops = SavedPostIncLoops;
01227 
01228   // Remember this PHI, even in post-inc mode.
01229   InsertedValues.insert(PN);
01230 
01231   return PN;
01232 }
01233 
01234 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
01235   Type *STy = S->getType();
01236   Type *IntTy = SE.getEffectiveSCEVType(STy);
01237   const Loop *L = S->getLoop();
01238 
01239   // Determine a normalized form of this expression, which is the expression
01240   // before any post-inc adjustment is made.
01241   const SCEVAddRecExpr *Normalized = S;
01242   if (PostIncLoops.count(L)) {
01243     PostIncLoopSet Loops;
01244     Loops.insert(L);
01245     Normalized =
01246       cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
01247                                                   nullptr, Loops, SE, *SE.DT));
01248   }
01249 
01250   // Strip off any non-loop-dominating component from the addrec start.
01251   const SCEV *Start = Normalized->getStart();
01252   const SCEV *PostLoopOffset = nullptr;
01253   if (!SE.properlyDominates(Start, L->getHeader())) {
01254     PostLoopOffset = Start;
01255     Start = SE.getConstant(Normalized->getType(), 0);
01256     Normalized = cast<SCEVAddRecExpr>(
01257       SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
01258                        Normalized->getLoop(),
01259                        Normalized->getNoWrapFlags(SCEV::FlagNW)));
01260   }
01261 
01262   // Strip off any non-loop-dominating component from the addrec step.
01263   const SCEV *Step = Normalized->getStepRecurrence(SE);
01264   const SCEV *PostLoopScale = nullptr;
01265   if (!SE.dominates(Step, L->getHeader())) {
01266     PostLoopScale = Step;
01267     Step = SE.getConstant(Normalized->getType(), 1);
01268     Normalized =
01269       cast<SCEVAddRecExpr>(SE.getAddRecExpr(
01270                              Start, Step, Normalized->getLoop(),
01271                              Normalized->getNoWrapFlags(SCEV::FlagNW)));
01272   }
01273 
01274   // Expand the core addrec. If we need post-loop scaling, force it to
01275   // expand to an integer type to avoid the need for additional casting.
01276   Type *ExpandTy = PostLoopScale ? IntTy : STy;
01277   // In some cases, we decide to reuse an existing phi node but need to truncate
01278   // it and/or invert the step.
01279   Type *TruncTy = nullptr;
01280   bool InvertStep = false;
01281   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
01282                                           TruncTy, InvertStep);
01283 
01284   // Accommodate post-inc mode, if necessary.
01285   Value *Result;
01286   if (!PostIncLoops.count(L))
01287     Result = PN;
01288   else {
01289     // In PostInc mode, use the post-incremented value.
01290     BasicBlock *LatchBlock = L->getLoopLatch();
01291     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
01292     Result = PN->getIncomingValueForBlock(LatchBlock);
01293 
01294     // For an expansion to use the postinc form, the client must call
01295     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
01296     // or dominated by IVIncInsertPos.
01297     if (isa<Instruction>(Result)
01298         && !SE.DT->dominates(cast<Instruction>(Result),
01299                              Builder.GetInsertPoint())) {
01300       // The induction variable's postinc expansion does not dominate this use.
01301       // IVUsers tries to prevent this case, so it is rare. However, it can
01302       // happen when an IVUser outside the loop is not dominated by the latch
01303       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
01304       // all cases. Consider a phi outide whose operand is replaced during
01305       // expansion with the value of the postinc user. Without fundamentally
01306       // changing the way postinc users are tracked, the only remedy is
01307       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
01308       // but hopefully expandCodeFor handles that.
01309       bool useSubtract =
01310         !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
01311       if (useSubtract)
01312         Step = SE.getNegativeSCEV(Step);
01313       Value *StepV;
01314       {
01315         // Expand the step somewhere that dominates the loop header.
01316         BuilderType::InsertPointGuard Guard(Builder);
01317         StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
01318       }
01319       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
01320     }
01321   }
01322 
01323   // We have decided to reuse an induction variable of a dominating loop. Apply
01324   // truncation and/or invertion of the step.
01325   if (TruncTy) {
01326     Type *ResTy = Result->getType();
01327     // Normalize the result type.
01328     if (ResTy != SE.getEffectiveSCEVType(ResTy))
01329       Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
01330     // Truncate the result.
01331     if (TruncTy != Result->getType()) {
01332       Result = Builder.CreateTrunc(Result, TruncTy);
01333       rememberInstruction(Result);
01334     }
01335     // Invert the result.
01336     if (InvertStep) {
01337       Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
01338                                  Result);
01339       rememberInstruction(Result);
01340     }
01341   }
01342 
01343   // Re-apply any non-loop-dominating scale.
01344   if (PostLoopScale) {
01345     assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
01346     Result = InsertNoopCastOfTo(Result, IntTy);
01347     Result = Builder.CreateMul(Result,
01348                                expandCodeFor(PostLoopScale, IntTy));
01349     rememberInstruction(Result);
01350   }
01351 
01352   // Re-apply any non-loop-dominating offset.
01353   if (PostLoopOffset) {
01354     if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
01355       const SCEV *const OffsetArray[1] = { PostLoopOffset };
01356       Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
01357     } else {
01358       Result = InsertNoopCastOfTo(Result, IntTy);
01359       Result = Builder.CreateAdd(Result,
01360                                  expandCodeFor(PostLoopOffset, IntTy));
01361       rememberInstruction(Result);
01362     }
01363   }
01364 
01365   return Result;
01366 }
01367 
01368 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
01369   if (!CanonicalMode) return expandAddRecExprLiterally(S);
01370 
01371   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01372   const Loop *L = S->getLoop();
01373 
01374   // First check for an existing canonical IV in a suitable type.
01375   PHINode *CanonicalIV = nullptr;
01376   if (PHINode *PN = L->getCanonicalInductionVariable())
01377     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
01378       CanonicalIV = PN;
01379 
01380   // Rewrite an AddRec in terms of the canonical induction variable, if
01381   // its type is more narrow.
01382   if (CanonicalIV &&
01383       SE.getTypeSizeInBits(CanonicalIV->getType()) >
01384       SE.getTypeSizeInBits(Ty)) {
01385     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
01386     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
01387       NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
01388     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
01389                                        S->getNoWrapFlags(SCEV::FlagNW)));
01390     BasicBlock::iterator NewInsertPt =
01391       std::next(BasicBlock::iterator(cast<Instruction>(V)));
01392     BuilderType::InsertPointGuard Guard(Builder);
01393     while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
01394            isa<LandingPadInst>(NewInsertPt))
01395       ++NewInsertPt;
01396     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
01397                       NewInsertPt);
01398     return V;
01399   }
01400 
01401   // {X,+,F} --> X + {0,+,F}
01402   if (!S->getStart()->isZero()) {
01403     SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
01404     NewOps[0] = SE.getConstant(Ty, 0);
01405     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
01406                                         S->getNoWrapFlags(SCEV::FlagNW));
01407 
01408     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
01409     // comments on expandAddToGEP for details.
01410     const SCEV *Base = S->getStart();
01411     const SCEV *RestArray[1] = { Rest };
01412     // Dig into the expression to find the pointer base for a GEP.
01413     ExposePointerBase(Base, RestArray[0], SE);
01414     // If we found a pointer, expand the AddRec with a GEP.
01415     if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
01416       // Make sure the Base isn't something exotic, such as a multiplied
01417       // or divided pointer value. In those cases, the result type isn't
01418       // actually a pointer type.
01419       if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
01420         Value *StartV = expand(Base);
01421         assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
01422         return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
01423       }
01424     }
01425 
01426     // Just do a normal add. Pre-expand the operands to suppress folding.
01427     return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
01428                                 SE.getUnknown(expand(Rest))));
01429   }
01430 
01431   // If we don't yet have a canonical IV, create one.
01432   if (!CanonicalIV) {
01433     // Create and insert the PHI node for the induction variable in the
01434     // specified loop.
01435     BasicBlock *Header = L->getHeader();
01436     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
01437     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
01438                                   Header->begin());
01439     rememberInstruction(CanonicalIV);
01440 
01441     SmallSet<BasicBlock *, 4> PredSeen;
01442     Constant *One = ConstantInt::get(Ty, 1);
01443     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
01444       BasicBlock *HP = *HPI;
01445       if (!PredSeen.insert(HP).second) {
01446         // There must be an incoming value for each predecessor, even the
01447         // duplicates!
01448         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
01449         continue;
01450       }
01451 
01452       if (L->contains(HP)) {
01453         // Insert a unit add instruction right before the terminator
01454         // corresponding to the back-edge.
01455         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
01456                                                      "indvar.next",
01457                                                      HP->getTerminator());
01458         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
01459         rememberInstruction(Add);
01460         CanonicalIV->addIncoming(Add, HP);
01461       } else {
01462         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
01463       }
01464     }
01465   }
01466 
01467   // {0,+,1} --> Insert a canonical induction variable into the loop!
01468   if (S->isAffine() && S->getOperand(1)->isOne()) {
01469     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
01470            "IVs with types different from the canonical IV should "
01471            "already have been handled!");
01472     return CanonicalIV;
01473   }
01474 
01475   // {0,+,F} --> {0,+,1} * F
01476 
01477   // If this is a simple linear addrec, emit it now as a special case.
01478   if (S->isAffine())    // {0,+,F} --> i*F
01479     return
01480       expand(SE.getTruncateOrNoop(
01481         SE.getMulExpr(SE.getUnknown(CanonicalIV),
01482                       SE.getNoopOrAnyExtend(S->getOperand(1),
01483                                             CanonicalIV->getType())),
01484         Ty));
01485 
01486   // If this is a chain of recurrences, turn it into a closed form, using the
01487   // folders, then expandCodeFor the closed form.  This allows the folders to
01488   // simplify the expression without having to build a bunch of special code
01489   // into this folder.
01490   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
01491 
01492   // Promote S up to the canonical IV type, if the cast is foldable.
01493   const SCEV *NewS = S;
01494   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
01495   if (isa<SCEVAddRecExpr>(Ext))
01496     NewS = Ext;
01497 
01498   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
01499   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
01500 
01501   // Truncate the result down to the original type, if needed.
01502   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
01503   return expand(T);
01504 }
01505 
01506 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
01507   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01508   Value *V = expandCodeFor(S->getOperand(),
01509                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
01510   Value *I = Builder.CreateTrunc(V, Ty);
01511   rememberInstruction(I);
01512   return I;
01513 }
01514 
01515 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
01516   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01517   Value *V = expandCodeFor(S->getOperand(),
01518                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
01519   Value *I = Builder.CreateZExt(V, Ty);
01520   rememberInstruction(I);
01521   return I;
01522 }
01523 
01524 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
01525   Type *Ty = SE.getEffectiveSCEVType(S->getType());
01526   Value *V = expandCodeFor(S->getOperand(),
01527                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
01528   Value *I = Builder.CreateSExt(V, Ty);
01529   rememberInstruction(I);
01530   return I;
01531 }
01532 
01533 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
01534   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
01535   Type *Ty = LHS->getType();
01536   for (int i = S->getNumOperands()-2; i >= 0; --i) {
01537     // In the case of mixed integer and pointer types, do the
01538     // rest of the comparisons as integer.
01539     if (S->getOperand(i)->getType() != Ty) {
01540       Ty = SE.getEffectiveSCEVType(Ty);
01541       LHS = InsertNoopCastOfTo(LHS, Ty);
01542     }
01543     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
01544     Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
01545     rememberInstruction(ICmp);
01546     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
01547     rememberInstruction(Sel);
01548     LHS = Sel;
01549   }
01550   // In the case of mixed integer and pointer types, cast the
01551   // final result back to the pointer type.
01552   if (LHS->getType() != S->getType())
01553     LHS = InsertNoopCastOfTo(LHS, S->getType());
01554   return LHS;
01555 }
01556 
01557 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
01558   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
01559   Type *Ty = LHS->getType();
01560   for (int i = S->getNumOperands()-2; i >= 0; --i) {
01561     // In the case of mixed integer and pointer types, do the
01562     // rest of the comparisons as integer.
01563     if (S->getOperand(i)->getType() != Ty) {
01564       Ty = SE.getEffectiveSCEVType(Ty);
01565       LHS = InsertNoopCastOfTo(LHS, Ty);
01566     }
01567     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
01568     Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
01569     rememberInstruction(ICmp);
01570     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
01571     rememberInstruction(Sel);
01572     LHS = Sel;
01573   }
01574   // In the case of mixed integer and pointer types, cast the
01575   // final result back to the pointer type.
01576   if (LHS->getType() != S->getType())
01577     LHS = InsertNoopCastOfTo(LHS, S->getType());
01578   return LHS;
01579 }
01580 
01581 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
01582                                    Instruction *IP) {
01583   Builder.SetInsertPoint(IP->getParent(), IP);
01584   return expandCodeFor(SH, Ty);
01585 }
01586 
01587 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
01588   // Expand the code for this SCEV.
01589   Value *V = expand(SH);
01590   if (Ty) {
01591     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
01592            "non-trivial casts should be done with the SCEVs directly!");
01593     V = InsertNoopCastOfTo(V, Ty);
01594   }
01595   return V;
01596 }
01597 
01598 Value *SCEVExpander::expand(const SCEV *S) {
01599   // Compute an insertion point for this SCEV object. Hoist the instructions
01600   // as far out in the loop nest as possible.
01601   Instruction *InsertPt = Builder.GetInsertPoint();
01602   for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
01603        L = L->getParentLoop())
01604     if (SE.isLoopInvariant(S, L)) {
01605       if (!L) break;
01606       if (BasicBlock *Preheader = L->getLoopPreheader())
01607         InsertPt = Preheader->getTerminator();
01608       else {
01609         // LSR sets the insertion point for AddRec start/step values to the
01610         // block start to simplify value reuse, even though it's an invalid
01611         // position. SCEVExpander must correct for this in all cases.
01612         InsertPt = L->getHeader()->getFirstInsertionPt();
01613       }
01614     } else {
01615       // If the SCEV is computable at this level, insert it into the header
01616       // after the PHIs (and after any other instructions that we've inserted
01617       // there) so that it is guaranteed to dominate any user inside the loop.
01618       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
01619         InsertPt = L->getHeader()->getFirstInsertionPt();
01620       while (InsertPt != Builder.GetInsertPoint()
01621              && (isInsertedInstruction(InsertPt)
01622                  || isa<DbgInfoIntrinsic>(InsertPt))) {
01623         InsertPt = std::next(BasicBlock::iterator(InsertPt));
01624       }
01625       break;
01626     }
01627 
01628   // Check to see if we already expanded this here.
01629   std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
01630     I = InsertedExpressions.find(std::make_pair(S, InsertPt));
01631   if (I != InsertedExpressions.end())
01632     return I->second;
01633 
01634   BuilderType::InsertPointGuard Guard(Builder);
01635   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
01636 
01637   // Expand the expression into instructions.
01638   Value *V = visit(S);
01639 
01640   // Remember the expanded value for this SCEV at this location.
01641   //
01642   // This is independent of PostIncLoops. The mapped value simply materializes
01643   // the expression at this insertion point. If the mapped value happened to be
01644   // a postinc expansion, it could be reused by a non-postinc user, but only if
01645   // its insertion point was already at the head of the loop.
01646   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
01647   return V;
01648 }
01649 
01650 void SCEVExpander::rememberInstruction(Value *I) {
01651   if (!PostIncLoops.empty())
01652     InsertedPostIncValues.insert(I);
01653   else
01654     InsertedValues.insert(I);
01655 }
01656 
01657 /// getOrInsertCanonicalInductionVariable - This method returns the
01658 /// canonical induction variable of the specified type for the specified
01659 /// loop (inserting one if there is none).  A canonical induction variable
01660 /// starts at zero and steps by one on each iteration.
01661 PHINode *
01662 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
01663                                                     Type *Ty) {
01664   assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
01665 
01666   // Build a SCEV for {0,+,1}<L>.
01667   // Conservatively use FlagAnyWrap for now.
01668   const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
01669                                    SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
01670 
01671   // Emit code for it.
01672   BuilderType::InsertPointGuard Guard(Builder);
01673   PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
01674                                            L->getHeader()->begin()));
01675 
01676   return V;
01677 }
01678 
01679 /// replaceCongruentIVs - Check for congruent phis in this loop header and
01680 /// replace them with their most canonical representative. Return the number of
01681 /// phis eliminated.
01682 ///
01683 /// This does not depend on any SCEVExpander state but should be used in
01684 /// the same context that SCEVExpander is used.
01685 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
01686                                            SmallVectorImpl<WeakVH> &DeadInsts,
01687                                            const TargetTransformInfo *TTI) {
01688   // Find integer phis in order of increasing width.
01689   SmallVector<PHINode*, 8> Phis;
01690   for (BasicBlock::iterator I = L->getHeader()->begin();
01691        PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
01692     Phis.push_back(Phi);
01693   }
01694   if (TTI)
01695     std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
01696       // Put pointers at the back and make sure pointer < pointer = false.
01697       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
01698         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
01699       return RHS->getType()->getPrimitiveSizeInBits() <
01700              LHS->getType()->getPrimitiveSizeInBits();
01701     });
01702 
01703   unsigned NumElim = 0;
01704   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
01705   // Process phis from wide to narrow. Mapping wide phis to the their truncation
01706   // so narrow phis can reuse them.
01707   for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
01708          PEnd = Phis.end(); PIter != PEnd; ++PIter) {
01709     PHINode *Phi = *PIter;
01710 
01711     // Fold constant phis. They may be congruent to other constant phis and
01712     // would confuse the logic below that expects proper IVs.
01713     if (Value *V = SimplifyInstruction(Phi, DL, SE.TLI, SE.DT, SE.AC)) {
01714       Phi->replaceAllUsesWith(V);
01715       DeadInsts.push_back(Phi);
01716       ++NumElim;
01717       DEBUG_WITH_TYPE(DebugType, dbgs()
01718                       << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
01719       continue;
01720     }
01721 
01722     if (!SE.isSCEVable(Phi->getType()))
01723       continue;
01724 
01725     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
01726     if (!OrigPhiRef) {
01727       OrigPhiRef = Phi;
01728       if (Phi->getType()->isIntegerTy() && TTI
01729           && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
01730         // This phi can be freely truncated to the narrowest phi type. Map the
01731         // truncated expression to it so it will be reused for narrow types.
01732         const SCEV *TruncExpr =
01733           SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
01734         ExprToIVMap[TruncExpr] = Phi;
01735       }
01736       continue;
01737     }
01738 
01739     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
01740     // sense.
01741     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
01742       continue;
01743 
01744     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
01745       Instruction *OrigInc =
01746         cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
01747       Instruction *IsomorphicInc =
01748         cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
01749 
01750       // If this phi has the same width but is more canonical, replace the
01751       // original with it. As part of the "more canonical" determination,
01752       // respect a prior decision to use an IV chain.
01753       if (OrigPhiRef->getType() == Phi->getType()
01754           && !(ChainedPhis.count(Phi)
01755                || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
01756           && (ChainedPhis.count(Phi)
01757               || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
01758         std::swap(OrigPhiRef, Phi);
01759         std::swap(OrigInc, IsomorphicInc);
01760       }
01761       // Replacing the congruent phi is sufficient because acyclic redundancy
01762       // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
01763       // that a phi is congruent, it's often the head of an IV user cycle that
01764       // is isomorphic with the original phi. It's worth eagerly cleaning up the
01765       // common case of a single IV increment so that DeleteDeadPHIs can remove
01766       // cycles that had postinc uses.
01767       const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
01768                                                    IsomorphicInc->getType());
01769       if (OrigInc != IsomorphicInc
01770           && TruncExpr == SE.getSCEV(IsomorphicInc)
01771           && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
01772               || hoistIVInc(OrigInc, IsomorphicInc))) {
01773         DEBUG_WITH_TYPE(DebugType, dbgs()
01774                         << "INDVARS: Eliminated congruent iv.inc: "
01775                         << *IsomorphicInc << '\n');
01776         Value *NewInc = OrigInc;
01777         if (OrigInc->getType() != IsomorphicInc->getType()) {
01778           Instruction *IP = nullptr;
01779           if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
01780             IP = PN->getParent()->getFirstInsertionPt();
01781           else
01782             IP = OrigInc->getNextNode();
01783 
01784           IRBuilder<> Builder(IP);
01785           Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
01786           NewInc = Builder.
01787             CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
01788         }
01789         IsomorphicInc->replaceAllUsesWith(NewInc);
01790         DeadInsts.push_back(IsomorphicInc);
01791       }
01792     }
01793     DEBUG_WITH_TYPE(DebugType, dbgs()
01794                     << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
01795     ++NumElim;
01796     Value *NewIV = OrigPhiRef;
01797     if (OrigPhiRef->getType() != Phi->getType()) {
01798       IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
01799       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
01800       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
01801     }
01802     Phi->replaceAllUsesWith(NewIV);
01803     DeadInsts.push_back(Phi);
01804   }
01805   return NumElim;
01806 }
01807 
01808 bool SCEVExpander::isHighCostExpansionHelper(
01809     const SCEV *S, Loop *L, SmallPtrSetImpl<const SCEV *> &Processed) {
01810   if (!Processed.insert(S).second)
01811     return false;
01812 
01813   if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
01814     // If the divisor is a power of two and the SCEV type fits in a native
01815     // integer, consider the divison cheap irrespective of whether it occurs in
01816     // the user code since it can be lowered into a right shift.
01817     if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
01818       if (SC->getValue()->getValue().isPowerOf2()) {
01819         const DataLayout &DL =
01820             L->getHeader()->getParent()->getParent()->getDataLayout();
01821         unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
01822         return DL.isIllegalInteger(Width);
01823       }
01824 
01825     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
01826     // HowManyLessThans produced to compute a precise expression, rather than a
01827     // UDiv from the user's code. If we can't find a UDiv in the code with some
01828     // simple searching, assume the former consider UDivExpr expensive to
01829     // compute.
01830     BasicBlock *ExitingBB = L->getExitingBlock();
01831     if (!ExitingBB)
01832       return true;
01833 
01834     BranchInst *ExitingBI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
01835     if (!ExitingBI || !ExitingBI->isConditional())
01836       return true;
01837 
01838     ICmpInst *OrigCond = dyn_cast<ICmpInst>(ExitingBI->getCondition());
01839     if (!OrigCond)
01840       return true;
01841 
01842     const SCEV *RHS = SE.getSCEV(OrigCond->getOperand(1));
01843     RHS = SE.getMinusSCEV(RHS, SE.getConstant(RHS->getType(), 1));
01844     if (RHS != S) {
01845       const SCEV *LHS = SE.getSCEV(OrigCond->getOperand(0));
01846       LHS = SE.getMinusSCEV(LHS, SE.getConstant(LHS->getType(), 1));
01847       if (LHS != S)
01848         return true;
01849     }
01850   }
01851 
01852   // Recurse past add expressions, which commonly occur in the
01853   // BackedgeTakenCount. They may already exist in program code, and if not,
01854   // they are not too expensive rematerialize.
01855   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
01856     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
01857          I != E; ++I) {
01858       if (isHighCostExpansionHelper(*I, L, Processed))
01859         return true;
01860     }
01861     return false;
01862   }
01863 
01864   // HowManyLessThans uses a Max expression whenever the loop is not guarded by
01865   // the exit condition.
01866   if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
01867     return true;
01868 
01869   // If we haven't recognized an expensive SCEV pattern, assume it's an
01870   // expression produced by program code.
01871   return false;
01872 }
01873 
01874 namespace {
01875 // Search for a SCEV subexpression that is not safe to expand.  Any expression
01876 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
01877 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
01878 // instruction, but the important thing is that we prove the denominator is
01879 // nonzero before expansion.
01880 //
01881 // IVUsers already checks that IV-derived expressions are safe. So this check is
01882 // only needed when the expression includes some subexpression that is not IV
01883 // derived.
01884 //
01885 // Currently, we only allow division by a nonzero constant here. If this is
01886 // inadequate, we could easily allow division by SCEVUnknown by using
01887 // ValueTracking to check isKnownNonZero().
01888 //
01889 // We cannot generally expand recurrences unless the step dominates the loop
01890 // header. The expander handles the special case of affine recurrences by
01891 // scaling the recurrence outside the loop, but this technique isn't generally
01892 // applicable. Expanding a nested recurrence outside a loop requires computing
01893 // binomial coefficients. This could be done, but the recurrence has to be in a
01894 // perfectly reduced form, which can't be guaranteed.
01895 struct SCEVFindUnsafe {
01896   ScalarEvolution &SE;
01897   bool IsUnsafe;
01898 
01899   SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
01900 
01901   bool follow(const SCEV *S) {
01902     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
01903       const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
01904       if (!SC || SC->getValue()->isZero()) {
01905         IsUnsafe = true;
01906         return false;
01907       }
01908     }
01909     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
01910       const SCEV *Step = AR->getStepRecurrence(SE);
01911       if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
01912         IsUnsafe = true;
01913         return false;
01914       }
01915     }
01916     return true;
01917   }
01918   bool isDone() const { return IsUnsafe; }
01919 };
01920 }
01921 
01922 namespace llvm {
01923 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
01924   SCEVFindUnsafe Search(SE);
01925   visitAll(S, Search);
01926   return !Search.IsUnsafe;
01927 }
01928 }