LLVM  mainline
IndVarSimplify.cpp
Go to the documentation of this file.
00001 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
00011 // computations derived from them) into simpler forms suitable for subsequent
00012 // analysis and transformation.
00013 //
00014 // If the trip count of a loop is computable, this pass also makes the following
00015 // changes:
00016 //   1. The exit condition for the loop is canonicalized to compare the
00017 //      induction value against the exit value.  This turns loops like:
00018 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
00019 //   2. Any use outside of the loop of an expression derived from the indvar
00020 //      is changed to compute the derived value outside of the loop, eliminating
00021 //      the dependence on the exit value of the induction variable.  If the only
00022 //      purpose of the loop is to compute the exit value of some derived
00023 //      expression, this transformation will make the loop dead.
00024 //
00025 //===----------------------------------------------------------------------===//
00026 
00027 #include "llvm/Transforms/Scalar.h"
00028 #include "llvm/ADT/DenseMap.h"
00029 #include "llvm/ADT/SmallVector.h"
00030 #include "llvm/ADT/Statistic.h"
00031 #include "llvm/Analysis/LoopInfo.h"
00032 #include "llvm/Analysis/LoopPass.h"
00033 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00034 #include "llvm/Analysis/TargetLibraryInfo.h"
00035 #include "llvm/Analysis/TargetTransformInfo.h"
00036 #include "llvm/IR/BasicBlock.h"
00037 #include "llvm/IR/CFG.h"
00038 #include "llvm/IR/Constants.h"
00039 #include "llvm/IR/DataLayout.h"
00040 #include "llvm/IR/Dominators.h"
00041 #include "llvm/IR/Instructions.h"
00042 #include "llvm/IR/IntrinsicInst.h"
00043 #include "llvm/IR/LLVMContext.h"
00044 #include "llvm/IR/Type.h"
00045 #include "llvm/Support/CommandLine.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00049 #include "llvm/Transforms/Utils/Local.h"
00050 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00051 using namespace llvm;
00052 
00053 #define DEBUG_TYPE "indvars"
00054 
00055 STATISTIC(NumWidened     , "Number of indvars widened");
00056 STATISTIC(NumReplaced    , "Number of exit values replaced");
00057 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
00058 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
00059 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
00060 
00061 // Trip count verification can be enabled by default under NDEBUG if we
00062 // implement a strong expression equivalence checker in SCEV. Until then, we
00063 // use the verify-indvars flag, which may assert in some cases.
00064 static cl::opt<bool> VerifyIndvars(
00065   "verify-indvars", cl::Hidden,
00066   cl::desc("Verify the ScalarEvolution result after running indvars"));
00067 
00068 static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden,
00069   cl::desc("Reduce live induction variables."));
00070 
00071 namespace {
00072   class IndVarSimplify : public LoopPass {
00073     LoopInfo                  *LI;
00074     ScalarEvolution           *SE;
00075     DominatorTree             *DT;
00076     TargetLibraryInfo         *TLI;
00077     const TargetTransformInfo *TTI;
00078 
00079     SmallVector<WeakVH, 16> DeadInsts;
00080     bool Changed;
00081   public:
00082 
00083     static char ID; // Pass identification, replacement for typeid
00084     IndVarSimplify()
00085         : LoopPass(ID), LI(nullptr), SE(nullptr), DT(nullptr), Changed(false) {
00086       initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
00087     }
00088 
00089     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00090 
00091     void getAnalysisUsage(AnalysisUsage &AU) const override {
00092       AU.addRequired<DominatorTreeWrapperPass>();
00093       AU.addRequired<LoopInfoWrapperPass>();
00094       AU.addRequired<ScalarEvolution>();
00095       AU.addRequiredID(LoopSimplifyID);
00096       AU.addRequiredID(LCSSAID);
00097       AU.addPreserved<ScalarEvolution>();
00098       AU.addPreservedID(LoopSimplifyID);
00099       AU.addPreservedID(LCSSAID);
00100       AU.setPreservesCFG();
00101     }
00102 
00103   private:
00104     void releaseMemory() override {
00105       DeadInsts.clear();
00106     }
00107 
00108     bool isValidRewrite(Value *FromVal, Value *ToVal);
00109 
00110     void HandleFloatingPointIV(Loop *L, PHINode *PH);
00111     void RewriteNonIntegerIVs(Loop *L);
00112 
00113     void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
00114 
00115     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
00116 
00117     Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
00118                                      PHINode *IndVar, SCEVExpander &Rewriter);
00119 
00120     void SinkUnusedInvariants(Loop *L);
00121   };
00122 }
00123 
00124 char IndVarSimplify::ID = 0;
00125 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
00126                 "Induction Variable Simplification", false, false)
00127 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00128 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00129 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
00130 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00131 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00132 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
00133                 "Induction Variable Simplification", false, false)
00134 
00135 Pass *llvm::createIndVarSimplifyPass() {
00136   return new IndVarSimplify();
00137 }
00138 
00139 /// isValidRewrite - Return true if the SCEV expansion generated by the
00140 /// rewriter can replace the original value. SCEV guarantees that it
00141 /// produces the same value, but the way it is produced may be illegal IR.
00142 /// Ideally, this function will only be called for verification.
00143 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
00144   // If an SCEV expression subsumed multiple pointers, its expansion could
00145   // reassociate the GEP changing the base pointer. This is illegal because the
00146   // final address produced by a GEP chain must be inbounds relative to its
00147   // underlying object. Otherwise basic alias analysis, among other things,
00148   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
00149   // producing an expression involving multiple pointers. Until then, we must
00150   // bail out here.
00151   //
00152   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
00153   // because it understands lcssa phis while SCEV does not.
00154   Value *FromPtr = FromVal;
00155   Value *ToPtr = ToVal;
00156   if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
00157     FromPtr = GEP->getPointerOperand();
00158   }
00159   if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
00160     ToPtr = GEP->getPointerOperand();
00161   }
00162   if (FromPtr != FromVal || ToPtr != ToVal) {
00163     // Quickly check the common case
00164     if (FromPtr == ToPtr)
00165       return true;
00166 
00167     // SCEV may have rewritten an expression that produces the GEP's pointer
00168     // operand. That's ok as long as the pointer operand has the same base
00169     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
00170     // base of a recurrence. This handles the case in which SCEV expansion
00171     // converts a pointer type recurrence into a nonrecurrent pointer base
00172     // indexed by an integer recurrence.
00173 
00174     // If the GEP base pointer is a vector of pointers, abort.
00175     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
00176       return false;
00177 
00178     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
00179     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
00180     if (FromBase == ToBase)
00181       return true;
00182 
00183     DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
00184           << *FromBase << " != " << *ToBase << "\n");
00185 
00186     return false;
00187   }
00188   return true;
00189 }
00190 
00191 /// Determine the insertion point for this user. By default, insert immediately
00192 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
00193 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
00194 /// common dominator for the incoming blocks.
00195 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
00196                                           DominatorTree *DT) {
00197   PHINode *PHI = dyn_cast<PHINode>(User);
00198   if (!PHI)
00199     return User;
00200 
00201   Instruction *InsertPt = nullptr;
00202   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
00203     if (PHI->getIncomingValue(i) != Def)
00204       continue;
00205 
00206     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
00207     if (!InsertPt) {
00208       InsertPt = InsertBB->getTerminator();
00209       continue;
00210     }
00211     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
00212     InsertPt = InsertBB->getTerminator();
00213   }
00214   assert(InsertPt && "Missing phi operand");
00215   assert((!isa<Instruction>(Def) ||
00216           DT->dominates(cast<Instruction>(Def), InsertPt)) &&
00217          "def does not dominate all uses");
00218   return InsertPt;
00219 }
00220 
00221 //===----------------------------------------------------------------------===//
00222 // RewriteNonIntegerIVs and helpers. Prefer integer IVs.
00223 //===----------------------------------------------------------------------===//
00224 
00225 /// ConvertToSInt - Convert APF to an integer, if possible.
00226 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
00227   bool isExact = false;
00228   // See if we can convert this to an int64_t
00229   uint64_t UIntVal;
00230   if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
00231                            &isExact) != APFloat::opOK || !isExact)
00232     return false;
00233   IntVal = UIntVal;
00234   return true;
00235 }
00236 
00237 /// HandleFloatingPointIV - If the loop has floating induction variable
00238 /// then insert corresponding integer induction variable if possible.
00239 /// For example,
00240 /// for(double i = 0; i < 10000; ++i)
00241 ///   bar(i)
00242 /// is converted into
00243 /// for(int i = 0; i < 10000; ++i)
00244 ///   bar((double)i);
00245 ///
00246 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
00247   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
00248   unsigned BackEdge     = IncomingEdge^1;
00249 
00250   // Check incoming value.
00251   ConstantFP *InitValueVal =
00252     dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
00253 
00254   int64_t InitValue;
00255   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
00256     return;
00257 
00258   // Check IV increment. Reject this PN if increment operation is not
00259   // an add or increment value can not be represented by an integer.
00260   BinaryOperator *Incr =
00261     dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
00262   if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
00263 
00264   // If this is not an add of the PHI with a constantfp, or if the constant fp
00265   // is not an integer, bail out.
00266   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
00267   int64_t IncValue;
00268   if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
00269       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
00270     return;
00271 
00272   // Check Incr uses. One user is PN and the other user is an exit condition
00273   // used by the conditional terminator.
00274   Value::user_iterator IncrUse = Incr->user_begin();
00275   Instruction *U1 = cast<Instruction>(*IncrUse++);
00276   if (IncrUse == Incr->user_end()) return;
00277   Instruction *U2 = cast<Instruction>(*IncrUse++);
00278   if (IncrUse != Incr->user_end()) return;
00279 
00280   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
00281   // only used by a branch, we can't transform it.
00282   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
00283   if (!Compare)
00284     Compare = dyn_cast<FCmpInst>(U2);
00285   if (!Compare || !Compare->hasOneUse() ||
00286       !isa<BranchInst>(Compare->user_back()))
00287     return;
00288 
00289   BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
00290 
00291   // We need to verify that the branch actually controls the iteration count
00292   // of the loop.  If not, the new IV can overflow and no one will notice.
00293   // The branch block must be in the loop and one of the successors must be out
00294   // of the loop.
00295   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
00296   if (!L->contains(TheBr->getParent()) ||
00297       (L->contains(TheBr->getSuccessor(0)) &&
00298        L->contains(TheBr->getSuccessor(1))))
00299     return;
00300 
00301 
00302   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
00303   // transform it.
00304   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
00305   int64_t ExitValue;
00306   if (ExitValueVal == nullptr ||
00307       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
00308     return;
00309 
00310   // Find new predicate for integer comparison.
00311   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
00312   switch (Compare->getPredicate()) {
00313   default: return;  // Unknown comparison.
00314   case CmpInst::FCMP_OEQ:
00315   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
00316   case CmpInst::FCMP_ONE:
00317   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
00318   case CmpInst::FCMP_OGT:
00319   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
00320   case CmpInst::FCMP_OGE:
00321   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
00322   case CmpInst::FCMP_OLT:
00323   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
00324   case CmpInst::FCMP_OLE:
00325   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
00326   }
00327 
00328   // We convert the floating point induction variable to a signed i32 value if
00329   // we can.  This is only safe if the comparison will not overflow in a way
00330   // that won't be trapped by the integer equivalent operations.  Check for this
00331   // now.
00332   // TODO: We could use i64 if it is native and the range requires it.
00333 
00334   // The start/stride/exit values must all fit in signed i32.
00335   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
00336     return;
00337 
00338   // If not actually striding (add x, 0.0), avoid touching the code.
00339   if (IncValue == 0)
00340     return;
00341 
00342   // Positive and negative strides have different safety conditions.
00343   if (IncValue > 0) {
00344     // If we have a positive stride, we require the init to be less than the
00345     // exit value.
00346     if (InitValue >= ExitValue)
00347       return;
00348 
00349     uint32_t Range = uint32_t(ExitValue-InitValue);
00350     // Check for infinite loop, either:
00351     // while (i <= Exit) or until (i > Exit)
00352     if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
00353       if (++Range == 0) return;  // Range overflows.
00354     }
00355 
00356     unsigned Leftover = Range % uint32_t(IncValue);
00357 
00358     // If this is an equality comparison, we require that the strided value
00359     // exactly land on the exit value, otherwise the IV condition will wrap
00360     // around and do things the fp IV wouldn't.
00361     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
00362         Leftover != 0)
00363       return;
00364 
00365     // If the stride would wrap around the i32 before exiting, we can't
00366     // transform the IV.
00367     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
00368       return;
00369 
00370   } else {
00371     // If we have a negative stride, we require the init to be greater than the
00372     // exit value.
00373     if (InitValue <= ExitValue)
00374       return;
00375 
00376     uint32_t Range = uint32_t(InitValue-ExitValue);
00377     // Check for infinite loop, either:
00378     // while (i >= Exit) or until (i < Exit)
00379     if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
00380       if (++Range == 0) return;  // Range overflows.
00381     }
00382 
00383     unsigned Leftover = Range % uint32_t(-IncValue);
00384 
00385     // If this is an equality comparison, we require that the strided value
00386     // exactly land on the exit value, otherwise the IV condition will wrap
00387     // around and do things the fp IV wouldn't.
00388     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
00389         Leftover != 0)
00390       return;
00391 
00392     // If the stride would wrap around the i32 before exiting, we can't
00393     // transform the IV.
00394     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
00395       return;
00396   }
00397 
00398   IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
00399 
00400   // Insert new integer induction variable.
00401   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
00402   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
00403                       PN->getIncomingBlock(IncomingEdge));
00404 
00405   Value *NewAdd =
00406     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
00407                               Incr->getName()+".int", Incr);
00408   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
00409 
00410   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
00411                                       ConstantInt::get(Int32Ty, ExitValue),
00412                                       Compare->getName());
00413 
00414   // In the following deletions, PN may become dead and may be deleted.
00415   // Use a WeakVH to observe whether this happens.
00416   WeakVH WeakPH = PN;
00417 
00418   // Delete the old floating point exit comparison.  The branch starts using the
00419   // new comparison.
00420   NewCompare->takeName(Compare);
00421   Compare->replaceAllUsesWith(NewCompare);
00422   RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
00423 
00424   // Delete the old floating point increment.
00425   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
00426   RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
00427 
00428   // If the FP induction variable still has uses, this is because something else
00429   // in the loop uses its value.  In order to canonicalize the induction
00430   // variable, we chose to eliminate the IV and rewrite it in terms of an
00431   // int->fp cast.
00432   //
00433   // We give preference to sitofp over uitofp because it is faster on most
00434   // platforms.
00435   if (WeakPH) {
00436     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
00437                                  PN->getParent()->getFirstInsertionPt());
00438     PN->replaceAllUsesWith(Conv);
00439     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
00440   }
00441   Changed = true;
00442 }
00443 
00444 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
00445   // First step.  Check to see if there are any floating-point recurrences.
00446   // If there are, change them into integer recurrences, permitting analysis by
00447   // the SCEV routines.
00448   //
00449   BasicBlock *Header = L->getHeader();
00450 
00451   SmallVector<WeakVH, 8> PHIs;
00452   for (BasicBlock::iterator I = Header->begin();
00453        PHINode *PN = dyn_cast<PHINode>(I); ++I)
00454     PHIs.push_back(PN);
00455 
00456   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
00457     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
00458       HandleFloatingPointIV(L, PN);
00459 
00460   // If the loop previously had floating-point IV, ScalarEvolution
00461   // may not have been able to compute a trip count. Now that we've done some
00462   // re-writing, the trip count may be computable.
00463   if (Changed)
00464     SE->forgetLoop(L);
00465 }
00466 
00467 //===----------------------------------------------------------------------===//
00468 // RewriteLoopExitValues - Optimize IV users outside the loop.
00469 // As a side effect, reduces the amount of IV processing within the loop.
00470 //===----------------------------------------------------------------------===//
00471 
00472 /// RewriteLoopExitValues - Check to see if this loop has a computable
00473 /// loop-invariant execution count.  If so, this means that we can compute the
00474 /// final value of any expressions that are recurrent in the loop, and
00475 /// substitute the exit values from the loop into any instructions outside of
00476 /// the loop that use the final values of the current expressions.
00477 ///
00478 /// This is mostly redundant with the regular IndVarSimplify activities that
00479 /// happen later, except that it's more powerful in some cases, because it's
00480 /// able to brute-force evaluate arbitrary instructions as long as they have
00481 /// constant operands at the beginning of the loop.
00482 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
00483   // Verify the input to the pass in already in LCSSA form.
00484   assert(L->isLCSSAForm(*DT));
00485 
00486   SmallVector<BasicBlock*, 8> ExitBlocks;
00487   L->getUniqueExitBlocks(ExitBlocks);
00488 
00489   // Find all values that are computed inside the loop, but used outside of it.
00490   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
00491   // the exit blocks of the loop to find them.
00492   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00493     BasicBlock *ExitBB = ExitBlocks[i];
00494 
00495     // If there are no PHI nodes in this exit block, then no values defined
00496     // inside the loop are used on this path, skip it.
00497     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
00498     if (!PN) continue;
00499 
00500     unsigned NumPreds = PN->getNumIncomingValues();
00501 
00502     // We would like to be able to RAUW single-incoming value PHI nodes. We
00503     // have to be certain this is safe even when this is an LCSSA PHI node.
00504     // While the computed exit value is no longer varying in *this* loop, the
00505     // exit block may be an exit block for an outer containing loop as well,
00506     // the exit value may be varying in the outer loop, and thus it may still
00507     // require an LCSSA PHI node. The safe case is when this is
00508     // single-predecessor PHI node (LCSSA) and the exit block containing it is
00509     // part of the enclosing loop, or this is the outer most loop of the nest.
00510     // In either case the exit value could (at most) be varying in the same
00511     // loop body as the phi node itself. Thus if it is in turn used outside of
00512     // an enclosing loop it will only be via a separate LCSSA node.
00513     bool LCSSASafePhiForRAUW =
00514         NumPreds == 1 &&
00515         (!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB));
00516 
00517     // Iterate over all of the PHI nodes.
00518     BasicBlock::iterator BBI = ExitBB->begin();
00519     while ((PN = dyn_cast<PHINode>(BBI++))) {
00520       if (PN->use_empty())
00521         continue; // dead use, don't replace it
00522 
00523       // SCEV only supports integer expressions for now.
00524       if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
00525         continue;
00526 
00527       // It's necessary to tell ScalarEvolution about this explicitly so that
00528       // it can walk the def-use list and forget all SCEVs, as it may not be
00529       // watching the PHI itself. Once the new exit value is in place, there
00530       // may not be a def-use connection between the loop and every instruction
00531       // which got a SCEVAddRecExpr for that loop.
00532       SE->forgetValue(PN);
00533 
00534       // Iterate over all of the values in all the PHI nodes.
00535       for (unsigned i = 0; i != NumPreds; ++i) {
00536         // If the value being merged in is not integer or is not defined
00537         // in the loop, skip it.
00538         Value *InVal = PN->getIncomingValue(i);
00539         if (!isa<Instruction>(InVal))
00540           continue;
00541 
00542         // If this pred is for a subloop, not L itself, skip it.
00543         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
00544           continue; // The Block is in a subloop, skip it.
00545 
00546         // Check that InVal is defined in the loop.
00547         Instruction *Inst = cast<Instruction>(InVal);
00548         if (!L->contains(Inst))
00549           continue;
00550 
00551         // Okay, this instruction has a user outside of the current loop
00552         // and varies predictably *inside* the loop.  Evaluate the value it
00553         // contains when the loop exits, if possible.
00554         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
00555         if (!SE->isLoopInvariant(ExitValue, L) ||
00556             !isSafeToExpand(ExitValue, *SE))
00557           continue;
00558 
00559         // Computing the value outside of the loop brings no benefit if :
00560         //  - it is definitely used inside the loop in a way which can not be
00561         //    optimized away.
00562         //  - no use outside of the loop can take advantage of hoisting the
00563         //    computation out of the loop
00564         if (ExitValue->getSCEVType()>=scMulExpr) {
00565           unsigned NumHardInternalUses = 0;
00566           unsigned NumSoftExternalUses = 0;
00567           unsigned NumUses = 0;
00568           for (auto IB = Inst->user_begin(), IE = Inst->user_end();
00569                IB != IE && NumUses <= 6; ++IB) {
00570             Instruction *UseInstr = cast<Instruction>(*IB);
00571             unsigned Opc = UseInstr->getOpcode();
00572             NumUses++;
00573             if (L->contains(UseInstr)) {
00574               if (Opc == Instruction::Call || Opc == Instruction::Ret)
00575                 NumHardInternalUses++;
00576             } else {
00577               if (Opc == Instruction::PHI) {
00578                 // Do not count the Phi as a use. LCSSA may have inserted
00579                 // plenty of trivial ones.
00580                 NumUses--;
00581                 for (auto PB = UseInstr->user_begin(),
00582                           PE = UseInstr->user_end();
00583                      PB != PE && NumUses <= 6; ++PB, ++NumUses) {
00584                   unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
00585                   if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
00586                     NumSoftExternalUses++;
00587                 }
00588                 continue;
00589               }
00590               if (Opc != Instruction::Call && Opc != Instruction::Ret)
00591                 NumSoftExternalUses++;
00592             }
00593           }
00594           if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
00595             continue;
00596         }
00597 
00598         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
00599 
00600         DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
00601                      << "  LoopVal = " << *Inst << "\n");
00602 
00603         if (!isValidRewrite(Inst, ExitVal)) {
00604           DeadInsts.push_back(ExitVal);
00605           continue;
00606         }
00607         Changed = true;
00608         ++NumReplaced;
00609 
00610         PN->setIncomingValue(i, ExitVal);
00611 
00612         // If this instruction is dead now, delete it. Don't do it now to avoid
00613         // invalidating iterators.
00614         if (isInstructionTriviallyDead(Inst, TLI))
00615           DeadInsts.push_back(Inst);
00616 
00617         // If we determined that this PHI is safe to replace even if an LCSSA
00618         // PHI, do so.
00619         if (LCSSASafePhiForRAUW) {
00620           PN->replaceAllUsesWith(ExitVal);
00621           PN->eraseFromParent();
00622         }
00623       }
00624     }
00625   }
00626 
00627   // The insertion point instruction may have been deleted; clear it out
00628   // so that the rewriter doesn't trip over it later.
00629   Rewriter.clearInsertPoint();
00630 }
00631 
00632 //===----------------------------------------------------------------------===//
00633 //  IV Widening - Extend the width of an IV to cover its widest uses.
00634 //===----------------------------------------------------------------------===//
00635 
00636 namespace {
00637   // Collect information about induction variables that are used by sign/zero
00638   // extend operations. This information is recorded by CollectExtend and
00639   // provides the input to WidenIV.
00640   struct WideIVInfo {
00641     PHINode *NarrowIV;
00642     Type *WidestNativeType; // Widest integer type created [sz]ext
00643     bool IsSigned;          // Was a sext user seen before a zext?
00644 
00645     WideIVInfo() : NarrowIV(nullptr), WidestNativeType(nullptr),
00646                    IsSigned(false) {}
00647   };
00648 }
00649 
00650 /// visitCast - Update information about the induction variable that is
00651 /// extended by this sign or zero extend operation. This is used to determine
00652 /// the final width of the IV before actually widening it.
00653 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
00654                         const TargetTransformInfo *TTI) {
00655   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
00656   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
00657     return;
00658 
00659   Type *Ty = Cast->getType();
00660   uint64_t Width = SE->getTypeSizeInBits(Ty);
00661   if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
00662     return;
00663 
00664   // Cast is either an sext or zext up to this point.
00665   // We should not widen an indvar if arithmetics on the wider indvar are more
00666   // expensive than those on the narrower indvar. We check only the cost of ADD
00667   // because at least an ADD is required to increment the induction variable. We
00668   // could compute more comprehensively the cost of all instructions on the
00669   // induction variable when necessary.
00670   if (TTI &&
00671       TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
00672           TTI->getArithmeticInstrCost(Instruction::Add,
00673                                       Cast->getOperand(0)->getType())) {
00674     return;
00675   }
00676 
00677   if (!WI.WidestNativeType) {
00678     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
00679     WI.IsSigned = IsSigned;
00680     return;
00681   }
00682 
00683   // We extend the IV to satisfy the sign of its first user, arbitrarily.
00684   if (WI.IsSigned != IsSigned)
00685     return;
00686 
00687   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
00688     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
00689 }
00690 
00691 namespace {
00692 
00693 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
00694 /// WideIV that computes the same value as the Narrow IV def.  This avoids
00695 /// caching Use* pointers.
00696 struct NarrowIVDefUse {
00697   Instruction *NarrowDef;
00698   Instruction *NarrowUse;
00699   Instruction *WideDef;
00700 
00701   NarrowIVDefUse(): NarrowDef(nullptr), NarrowUse(nullptr), WideDef(nullptr) {}
00702 
00703   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
00704     NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
00705 };
00706 
00707 /// WidenIV - The goal of this transform is to remove sign and zero extends
00708 /// without creating any new induction variables. To do this, it creates a new
00709 /// phi of the wider type and redirects all users, either removing extends or
00710 /// inserting truncs whenever we stop propagating the type.
00711 ///
00712 class WidenIV {
00713   // Parameters
00714   PHINode *OrigPhi;
00715   Type *WideType;
00716   bool IsSigned;
00717 
00718   // Context
00719   LoopInfo        *LI;
00720   Loop            *L;
00721   ScalarEvolution *SE;
00722   DominatorTree   *DT;
00723 
00724   // Result
00725   PHINode *WidePhi;
00726   Instruction *WideInc;
00727   const SCEV *WideIncExpr;
00728   SmallVectorImpl<WeakVH> &DeadInsts;
00729 
00730   SmallPtrSet<Instruction*,16> Widened;
00731   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
00732 
00733 public:
00734   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
00735           ScalarEvolution *SEv, DominatorTree *DTree,
00736           SmallVectorImpl<WeakVH> &DI) :
00737     OrigPhi(WI.NarrowIV),
00738     WideType(WI.WidestNativeType),
00739     IsSigned(WI.IsSigned),
00740     LI(LInfo),
00741     L(LI->getLoopFor(OrigPhi->getParent())),
00742     SE(SEv),
00743     DT(DTree),
00744     WidePhi(nullptr),
00745     WideInc(nullptr),
00746     WideIncExpr(nullptr),
00747     DeadInsts(DI) {
00748     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
00749   }
00750 
00751   PHINode *CreateWideIV(SCEVExpander &Rewriter);
00752 
00753 protected:
00754   Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
00755                    Instruction *Use);
00756 
00757   Instruction *CloneIVUser(NarrowIVDefUse DU);
00758 
00759   const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
00760 
00761   const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
00762 
00763   const SCEV *GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
00764                               unsigned OpCode) const;
00765 
00766   Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
00767 
00768   bool WidenLoopCompare(NarrowIVDefUse DU);
00769 
00770   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
00771 };
00772 } // anonymous namespace
00773 
00774 /// isLoopInvariant - Perform a quick domtree based check for loop invariance
00775 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
00776 /// gratuitous for this purpose.
00777 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
00778   Instruction *Inst = dyn_cast<Instruction>(V);
00779   if (!Inst)
00780     return true;
00781 
00782   return DT->properlyDominates(Inst->getParent(), L->getHeader());
00783 }
00784 
00785 Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
00786                           Instruction *Use) {
00787   // Set the debug location and conservative insertion point.
00788   IRBuilder<> Builder(Use);
00789   // Hoist the insertion point into loop preheaders as far as possible.
00790   for (const Loop *L = LI->getLoopFor(Use->getParent());
00791        L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
00792        L = L->getParentLoop())
00793     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
00794 
00795   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
00796                     Builder.CreateZExt(NarrowOper, WideType);
00797 }
00798 
00799 /// CloneIVUser - Instantiate a wide operation to replace a narrow
00800 /// operation. This only needs to handle operations that can evaluation to
00801 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
00802 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
00803   unsigned Opcode = DU.NarrowUse->getOpcode();
00804   switch (Opcode) {
00805   default:
00806     return nullptr;
00807   case Instruction::Add:
00808   case Instruction::Mul:
00809   case Instruction::UDiv:
00810   case Instruction::Sub:
00811   case Instruction::And:
00812   case Instruction::Or:
00813   case Instruction::Xor:
00814   case Instruction::Shl:
00815   case Instruction::LShr:
00816   case Instruction::AShr:
00817     DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
00818 
00819     // Replace NarrowDef operands with WideDef. Otherwise, we don't know
00820     // anything about the narrow operand yet so must insert a [sz]ext. It is
00821     // probably loop invariant and will be folded or hoisted. If it actually
00822     // comes from a widened IV, it should be removed during a future call to
00823     // WidenIVUse.
00824     Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
00825       getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
00826     Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
00827       getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
00828 
00829     BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
00830     BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
00831                                                     LHS, RHS,
00832                                                     NarrowBO->getName());
00833     IRBuilder<> Builder(DU.NarrowUse);
00834     Builder.Insert(WideBO);
00835     if (const OverflowingBinaryOperator *OBO =
00836         dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
00837       if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
00838       if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
00839     }
00840     return WideBO;
00841   }
00842 }
00843 
00844 const SCEV *WidenIV::GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
00845                                      unsigned OpCode) const {
00846   if (OpCode == Instruction::Add)
00847     return SE->getAddExpr(LHS, RHS);
00848   if (OpCode == Instruction::Sub)
00849     return SE->getMinusSCEV(LHS, RHS);
00850   if (OpCode == Instruction::Mul)
00851     return SE->getMulExpr(LHS, RHS);
00852 
00853   llvm_unreachable("Unsupported opcode.");
00854 }
00855 
00856 /// No-wrap operations can transfer sign extension of their result to their
00857 /// operands. Generate the SCEV value for the widened operation without
00858 /// actually modifying the IR yet. If the expression after extending the
00859 /// operands is an AddRec for this loop, return it.
00860 const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
00861 
00862   // Handle the common case of add<nsw/nuw>
00863   const unsigned OpCode = DU.NarrowUse->getOpcode();
00864   // Only Add/Sub/Mul instructions supported yet.
00865   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
00866       OpCode != Instruction::Mul)
00867     return nullptr;
00868 
00869   // One operand (NarrowDef) has already been extended to WideDef. Now determine
00870   // if extending the other will lead to a recurrence.
00871   const unsigned ExtendOperIdx =
00872       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
00873   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
00874 
00875   const SCEV *ExtendOperExpr = nullptr;
00876   const OverflowingBinaryOperator *OBO =
00877     cast<OverflowingBinaryOperator>(DU.NarrowUse);
00878   if (IsSigned && OBO->hasNoSignedWrap())
00879     ExtendOperExpr = SE->getSignExtendExpr(
00880       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
00881   else if(!IsSigned && OBO->hasNoUnsignedWrap())
00882     ExtendOperExpr = SE->getZeroExtendExpr(
00883       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
00884   else
00885     return nullptr;
00886 
00887   // When creating this SCEV expr, don't apply the current operations NSW or NUW
00888   // flags. This instruction may be guarded by control flow that the no-wrap
00889   // behavior depends on. Non-control-equivalent instructions can be mapped to
00890   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
00891   // semantics to those operations.
00892   const SCEV *lhs = SE->getSCEV(DU.WideDef);
00893   const SCEV *rhs = ExtendOperExpr;
00894 
00895   // Let's swap operands to the initial order for the case of non-commutative
00896   // operations, like SUB. See PR21014.
00897   if (ExtendOperIdx == 0)
00898     std::swap(lhs, rhs);
00899   const SCEVAddRecExpr *AddRec =
00900       dyn_cast<SCEVAddRecExpr>(GetSCEVByOpCode(lhs, rhs, OpCode));
00901 
00902   if (!AddRec || AddRec->getLoop() != L)
00903     return nullptr;
00904   return AddRec;
00905 }
00906 
00907 /// GetWideRecurrence - Is this instruction potentially interesting for further
00908 /// simplification after widening it's type? In other words, can the
00909 /// extend be safely hoisted out of the loop with SCEV reducing the value to a
00910 /// recurrence on the same loop. If so, return the sign or zero extended
00911 /// recurrence. Otherwise return NULL.
00912 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
00913   if (!SE->isSCEVable(NarrowUse->getType()))
00914     return nullptr;
00915 
00916   const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
00917   if (SE->getTypeSizeInBits(NarrowExpr->getType())
00918       >= SE->getTypeSizeInBits(WideType)) {
00919     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
00920     // index. So don't follow this use.
00921     return nullptr;
00922   }
00923 
00924   const SCEV *WideExpr = IsSigned ?
00925     SE->getSignExtendExpr(NarrowExpr, WideType) :
00926     SE->getZeroExtendExpr(NarrowExpr, WideType);
00927   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
00928   if (!AddRec || AddRec->getLoop() != L)
00929     return nullptr;
00930   return AddRec;
00931 }
00932 
00933 /// This IV user cannot be widen. Replace this use of the original narrow IV
00934 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
00935 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) {
00936   DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
00937         << " for user " << *DU.NarrowUse << "\n");
00938   IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
00939   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
00940   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
00941 }
00942 
00943 /// If the narrow use is a compare instruction, then widen the compare
00944 //  (and possibly the other operand).  The extend operation is hoisted into the
00945 // loop preheader as far as possible.
00946 bool WidenIV::WidenLoopCompare(NarrowIVDefUse DU) {
00947   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
00948   if (!Cmp)
00949     return false;
00950 
00951   // Sign of IV user and compare must match.
00952   if (IsSigned != CmpInst::isSigned(Cmp->getPredicate()))
00953     return false;
00954 
00955   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
00956   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
00957   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
00958   assert (CastWidth <= IVWidth && "Unexpected width while widening compare.");
00959 
00960   // Widen the compare instruction.
00961   IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
00962   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
00963 
00964   // Widen the other operand of the compare, if necessary.
00965   if (CastWidth < IVWidth) {
00966     Value *ExtOp = getExtend(Op, WideType, IsSigned, Cmp);
00967     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
00968   }
00969   return true;
00970 }
00971 
00972 /// WidenIVUse - Determine whether an individual user of the narrow IV can be
00973 /// widened. If so, return the wide clone of the user.
00974 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
00975 
00976   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
00977   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
00978     if (LI->getLoopFor(UsePhi->getParent()) != L) {
00979       // For LCSSA phis, sink the truncate outside the loop.
00980       // After SimplifyCFG most loop exit targets have a single predecessor.
00981       // Otherwise fall back to a truncate within the loop.
00982       if (UsePhi->getNumOperands() != 1)
00983         truncateIVUse(DU, DT);
00984       else {
00985         PHINode *WidePhi =
00986           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
00987                           UsePhi);
00988         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
00989         IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
00990         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
00991         UsePhi->replaceAllUsesWith(Trunc);
00992         DeadInsts.push_back(UsePhi);
00993         DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
00994               << " to " << *WidePhi << "\n");
00995       }
00996       return nullptr;
00997     }
00998   }
00999   // Our raison d'etre! Eliminate sign and zero extension.
01000   if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
01001     Value *NewDef = DU.WideDef;
01002     if (DU.NarrowUse->getType() != WideType) {
01003       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
01004       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
01005       if (CastWidth < IVWidth) {
01006         // The cast isn't as wide as the IV, so insert a Trunc.
01007         IRBuilder<> Builder(DU.NarrowUse);
01008         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
01009       }
01010       else {
01011         // A wider extend was hidden behind a narrower one. This may induce
01012         // another round of IV widening in which the intermediate IV becomes
01013         // dead. It should be very rare.
01014         DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
01015               << " not wide enough to subsume " << *DU.NarrowUse << "\n");
01016         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
01017         NewDef = DU.NarrowUse;
01018       }
01019     }
01020     if (NewDef != DU.NarrowUse) {
01021       DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
01022             << " replaced by " << *DU.WideDef << "\n");
01023       ++NumElimExt;
01024       DU.NarrowUse->replaceAllUsesWith(NewDef);
01025       DeadInsts.push_back(DU.NarrowUse);
01026     }
01027     // Now that the extend is gone, we want to expose it's uses for potential
01028     // further simplification. We don't need to directly inform SimplifyIVUsers
01029     // of the new users, because their parent IV will be processed later as a
01030     // new loop phi. If we preserved IVUsers analysis, we would also want to
01031     // push the uses of WideDef here.
01032 
01033     // No further widening is needed. The deceased [sz]ext had done it for us.
01034     return nullptr;
01035   }
01036 
01037   // Does this user itself evaluate to a recurrence after widening?
01038   const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
01039   if (!WideAddRec)
01040     WideAddRec = GetExtendedOperandRecurrence(DU);
01041 
01042   if (!WideAddRec) {
01043     // If use is a loop condition, try to promote the condition instead of
01044     // truncating the IV first.
01045     if (WidenLoopCompare(DU))
01046       return nullptr;
01047 
01048     // This user does not evaluate to a recurence after widening, so don't
01049     // follow it. Instead insert a Trunc to kill off the original use,
01050     // eventually isolating the original narrow IV so it can be removed.
01051     truncateIVUse(DU, DT);
01052     return nullptr;
01053   }
01054   // Assume block terminators cannot evaluate to a recurrence. We can't to
01055   // insert a Trunc after a terminator if there happens to be a critical edge.
01056   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
01057          "SCEV is not expected to evaluate a block terminator");
01058 
01059   // Reuse the IV increment that SCEVExpander created as long as it dominates
01060   // NarrowUse.
01061   Instruction *WideUse = nullptr;
01062   if (WideAddRec == WideIncExpr
01063       && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
01064     WideUse = WideInc;
01065   else {
01066     WideUse = CloneIVUser(DU);
01067     if (!WideUse)
01068       return nullptr;
01069   }
01070   // Evaluation of WideAddRec ensured that the narrow expression could be
01071   // extended outside the loop without overflow. This suggests that the wide use
01072   // evaluates to the same expression as the extended narrow use, but doesn't
01073   // absolutely guarantee it. Hence the following failsafe check. In rare cases
01074   // where it fails, we simply throw away the newly created wide use.
01075   if (WideAddRec != SE->getSCEV(WideUse)) {
01076     DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
01077           << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
01078     DeadInsts.push_back(WideUse);
01079     return nullptr;
01080   }
01081 
01082   // Returning WideUse pushes it on the worklist.
01083   return WideUse;
01084 }
01085 
01086 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
01087 ///
01088 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
01089   for (User *U : NarrowDef->users()) {
01090     Instruction *NarrowUser = cast<Instruction>(U);
01091 
01092     // Handle data flow merges and bizarre phi cycles.
01093     if (!Widened.insert(NarrowUser).second)
01094       continue;
01095 
01096     NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUser, WideDef));
01097   }
01098 }
01099 
01100 /// CreateWideIV - Process a single induction variable. First use the
01101 /// SCEVExpander to create a wide induction variable that evaluates to the same
01102 /// recurrence as the original narrow IV. Then use a worklist to forward
01103 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
01104 /// interesting IV users, the narrow IV will be isolated for removal by
01105 /// DeleteDeadPHIs.
01106 ///
01107 /// It would be simpler to delete uses as they are processed, but we must avoid
01108 /// invalidating SCEV expressions.
01109 ///
01110 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
01111   // Is this phi an induction variable?
01112   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
01113   if (!AddRec)
01114     return nullptr;
01115 
01116   // Widen the induction variable expression.
01117   const SCEV *WideIVExpr = IsSigned ?
01118     SE->getSignExtendExpr(AddRec, WideType) :
01119     SE->getZeroExtendExpr(AddRec, WideType);
01120 
01121   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
01122          "Expect the new IV expression to preserve its type");
01123 
01124   // Can the IV be extended outside the loop without overflow?
01125   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
01126   if (!AddRec || AddRec->getLoop() != L)
01127     return nullptr;
01128 
01129   // An AddRec must have loop-invariant operands. Since this AddRec is
01130   // materialized by a loop header phi, the expression cannot have any post-loop
01131   // operands, so they must dominate the loop header.
01132   assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
01133          SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
01134          && "Loop header phi recurrence inputs do not dominate the loop");
01135 
01136   // The rewriter provides a value for the desired IV expression. This may
01137   // either find an existing phi or materialize a new one. Either way, we
01138   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
01139   // of the phi-SCC dominates the loop entry.
01140   Instruction *InsertPt = L->getHeader()->begin();
01141   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
01142 
01143   // Remembering the WideIV increment generated by SCEVExpander allows
01144   // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
01145   // employ a general reuse mechanism because the call above is the only call to
01146   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
01147   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
01148     WideInc =
01149       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
01150     WideIncExpr = SE->getSCEV(WideInc);
01151   }
01152 
01153   DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
01154   ++NumWidened;
01155 
01156   // Traverse the def-use chain using a worklist starting at the original IV.
01157   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
01158 
01159   Widened.insert(OrigPhi);
01160   pushNarrowIVUsers(OrigPhi, WidePhi);
01161 
01162   while (!NarrowIVUsers.empty()) {
01163     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
01164 
01165     // Process a def-use edge. This may replace the use, so don't hold a
01166     // use_iterator across it.
01167     Instruction *WideUse = WidenIVUse(DU, Rewriter);
01168 
01169     // Follow all def-use edges from the previous narrow use.
01170     if (WideUse)
01171       pushNarrowIVUsers(DU.NarrowUse, WideUse);
01172 
01173     // WidenIVUse may have removed the def-use edge.
01174     if (DU.NarrowDef->use_empty())
01175       DeadInsts.push_back(DU.NarrowDef);
01176   }
01177   return WidePhi;
01178 }
01179 
01180 //===----------------------------------------------------------------------===//
01181 //  Live IV Reduction - Minimize IVs live across the loop.
01182 //===----------------------------------------------------------------------===//
01183 
01184 
01185 //===----------------------------------------------------------------------===//
01186 //  Simplification of IV users based on SCEV evaluation.
01187 //===----------------------------------------------------------------------===//
01188 
01189 namespace {
01190   class IndVarSimplifyVisitor : public IVVisitor {
01191     ScalarEvolution *SE;
01192     const TargetTransformInfo *TTI;
01193     PHINode *IVPhi;
01194 
01195   public:
01196     WideIVInfo WI;
01197 
01198     IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
01199                           const TargetTransformInfo *TTI,
01200                           const DominatorTree *DTree)
01201         : SE(SCEV), TTI(TTI), IVPhi(IV) {
01202       DT = DTree;
01203       WI.NarrowIV = IVPhi;
01204       if (ReduceLiveIVs)
01205         setSplitOverflowIntrinsics();
01206     }
01207 
01208     // Implement the interface used by simplifyUsersOfIV.
01209     void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
01210   };
01211 }
01212 
01213 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
01214 /// users. Each successive simplification may push more users which may
01215 /// themselves be candidates for simplification.
01216 ///
01217 /// Sign/Zero extend elimination is interleaved with IV simplification.
01218 ///
01219 void IndVarSimplify::SimplifyAndExtend(Loop *L,
01220                                        SCEVExpander &Rewriter,
01221                                        LPPassManager &LPM) {
01222   SmallVector<WideIVInfo, 8> WideIVs;
01223 
01224   SmallVector<PHINode*, 8> LoopPhis;
01225   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
01226     LoopPhis.push_back(cast<PHINode>(I));
01227   }
01228   // Each round of simplification iterates through the SimplifyIVUsers worklist
01229   // for all current phis, then determines whether any IVs can be
01230   // widened. Widening adds new phis to LoopPhis, inducing another round of
01231   // simplification on the wide IVs.
01232   while (!LoopPhis.empty()) {
01233     // Evaluate as many IV expressions as possible before widening any IVs. This
01234     // forces SCEV to set no-wrap flags before evaluating sign/zero
01235     // extension. The first time SCEV attempts to normalize sign/zero extension,
01236     // the result becomes final. So for the most predictable results, we delay
01237     // evaluation of sign/zero extend evaluation until needed, and avoid running
01238     // other SCEV based analysis prior to SimplifyAndExtend.
01239     do {
01240       PHINode *CurrIV = LoopPhis.pop_back_val();
01241 
01242       // Information about sign/zero extensions of CurrIV.
01243       IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
01244 
01245       Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor);
01246 
01247       if (Visitor.WI.WidestNativeType) {
01248         WideIVs.push_back(Visitor.WI);
01249       }
01250     } while(!LoopPhis.empty());
01251 
01252     for (; !WideIVs.empty(); WideIVs.pop_back()) {
01253       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
01254       if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
01255         Changed = true;
01256         LoopPhis.push_back(WidePhi);
01257       }
01258     }
01259   }
01260 }
01261 
01262 //===----------------------------------------------------------------------===//
01263 //  LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
01264 //===----------------------------------------------------------------------===//
01265 
01266 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
01267 /// count expression can be safely and cheaply expanded into an instruction
01268 /// sequence that can be used by LinearFunctionTestReplace.
01269 ///
01270 /// TODO: This fails for pointer-type loop counters with greater than one byte
01271 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
01272 /// we could skip this check in the case that the LFTR loop counter (chosen by
01273 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
01274 /// the loop test to an inequality test by checking the target data's alignment
01275 /// of element types (given that the initial pointer value originates from or is
01276 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
01277 /// However, we don't yet have a strong motivation for converting loop tests
01278 /// into inequality tests.
01279 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
01280                                         SCEVExpander &Rewriter) {
01281   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
01282   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
01283       BackedgeTakenCount->isZero())
01284     return false;
01285 
01286   if (!L->getExitingBlock())
01287     return false;
01288 
01289   // Can't rewrite non-branch yet.
01290   if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
01291     return false;
01292 
01293   if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
01294     return false;
01295 
01296   return true;
01297 }
01298 
01299 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
01300 /// invariant value to the phi.
01301 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
01302   Instruction *IncI = dyn_cast<Instruction>(IncV);
01303   if (!IncI)
01304     return nullptr;
01305 
01306   switch (IncI->getOpcode()) {
01307   case Instruction::Add:
01308   case Instruction::Sub:
01309     break;
01310   case Instruction::GetElementPtr:
01311     // An IV counter must preserve its type.
01312     if (IncI->getNumOperands() == 2)
01313       break;
01314   default:
01315     return nullptr;
01316   }
01317 
01318   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
01319   if (Phi && Phi->getParent() == L->getHeader()) {
01320     if (isLoopInvariant(IncI->getOperand(1), L, DT))
01321       return Phi;
01322     return nullptr;
01323   }
01324   if (IncI->getOpcode() == Instruction::GetElementPtr)
01325     return nullptr;
01326 
01327   // Allow add/sub to be commuted.
01328   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
01329   if (Phi && Phi->getParent() == L->getHeader()) {
01330     if (isLoopInvariant(IncI->getOperand(0), L, DT))
01331       return Phi;
01332   }
01333   return nullptr;
01334 }
01335 
01336 /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
01337 static ICmpInst *getLoopTest(Loop *L) {
01338   assert(L->getExitingBlock() && "expected loop exit");
01339 
01340   BasicBlock *LatchBlock = L->getLoopLatch();
01341   // Don't bother with LFTR if the loop is not properly simplified.
01342   if (!LatchBlock)
01343     return nullptr;
01344 
01345   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
01346   assert(BI && "expected exit branch");
01347 
01348   return dyn_cast<ICmpInst>(BI->getCondition());
01349 }
01350 
01351 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
01352 /// that the current exit test is already sufficiently canonical.
01353 static bool needsLFTR(Loop *L, DominatorTree *DT) {
01354   // Do LFTR to simplify the exit condition to an ICMP.
01355   ICmpInst *Cond = getLoopTest(L);
01356   if (!Cond)
01357     return true;
01358 
01359   // Do LFTR to simplify the exit ICMP to EQ/NE
01360   ICmpInst::Predicate Pred = Cond->getPredicate();
01361   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
01362     return true;
01363 
01364   // Look for a loop invariant RHS
01365   Value *LHS = Cond->getOperand(0);
01366   Value *RHS = Cond->getOperand(1);
01367   if (!isLoopInvariant(RHS, L, DT)) {
01368     if (!isLoopInvariant(LHS, L, DT))
01369       return true;
01370     std::swap(LHS, RHS);
01371   }
01372   // Look for a simple IV counter LHS
01373   PHINode *Phi = dyn_cast<PHINode>(LHS);
01374   if (!Phi)
01375     Phi = getLoopPhiForCounter(LHS, L, DT);
01376 
01377   if (!Phi)
01378     return true;
01379 
01380   // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
01381   int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
01382   if (Idx < 0)
01383     return true;
01384 
01385   // Do LFTR if the exit condition's IV is *not* a simple counter.
01386   Value *IncV = Phi->getIncomingValue(Idx);
01387   return Phi != getLoopPhiForCounter(IncV, L, DT);
01388 }
01389 
01390 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
01391 /// down to checking that all operands are constant and listing instructions
01392 /// that may hide undef.
01393 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
01394                                unsigned Depth) {
01395   if (isa<Constant>(V))
01396     return !isa<UndefValue>(V);
01397 
01398   if (Depth >= 6)
01399     return false;
01400 
01401   // Conservatively handle non-constant non-instructions. For example, Arguments
01402   // may be undef.
01403   Instruction *I = dyn_cast<Instruction>(V);
01404   if (!I)
01405     return false;
01406 
01407   // Load and return values may be undef.
01408   if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
01409     return false;
01410 
01411   // Optimistically handle other instructions.
01412   for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
01413     if (!Visited.insert(*OI).second)
01414       continue;
01415     if (!hasConcreteDefImpl(*OI, Visited, Depth+1))
01416       return false;
01417   }
01418   return true;
01419 }
01420 
01421 /// Return true if the given value is concrete. We must prove that undef can
01422 /// never reach it.
01423 ///
01424 /// TODO: If we decide that this is a good approach to checking for undef, we
01425 /// may factor it into a common location.
01426 static bool hasConcreteDef(Value *V) {
01427   SmallPtrSet<Value*, 8> Visited;
01428   Visited.insert(V);
01429   return hasConcreteDefImpl(V, Visited, 0);
01430 }
01431 
01432 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
01433 /// be rewritten) loop exit test.
01434 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
01435   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
01436   Value *IncV = Phi->getIncomingValue(LatchIdx);
01437 
01438   for (User *U : Phi->users())
01439     if (U != Cond && U != IncV) return false;
01440 
01441   for (User *U : IncV->users())
01442     if (U != Cond && U != Phi) return false;
01443   return true;
01444 }
01445 
01446 /// FindLoopCounter - Find an affine IV in canonical form.
01447 ///
01448 /// BECount may be an i8* pointer type. The pointer difference is already
01449 /// valid count without scaling the address stride, so it remains a pointer
01450 /// expression as far as SCEV is concerned.
01451 ///
01452 /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
01453 ///
01454 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
01455 ///
01456 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
01457 /// This is difficult in general for SCEV because of potential overflow. But we
01458 /// could at least handle constant BECounts.
01459 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
01460                                 ScalarEvolution *SE, DominatorTree *DT) {
01461   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
01462 
01463   Value *Cond =
01464     cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
01465 
01466   // Loop over all of the PHI nodes, looking for a simple counter.
01467   PHINode *BestPhi = nullptr;
01468   const SCEV *BestInit = nullptr;
01469   BasicBlock *LatchBlock = L->getLoopLatch();
01470   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
01471 
01472   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
01473     PHINode *Phi = cast<PHINode>(I);
01474     if (!SE->isSCEVable(Phi->getType()))
01475       continue;
01476 
01477     // Avoid comparing an integer IV against a pointer Limit.
01478     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
01479       continue;
01480 
01481     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
01482     if (!AR || AR->getLoop() != L || !AR->isAffine())
01483       continue;
01484 
01485     // AR may be a pointer type, while BECount is an integer type.
01486     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
01487     // AR may not be a narrower type, or we may never exit.
01488     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
01489     if (PhiWidth < BCWidth ||
01490         !L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth))
01491       continue;
01492 
01493     const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
01494     if (!Step || !Step->isOne())
01495       continue;
01496 
01497     int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
01498     Value *IncV = Phi->getIncomingValue(LatchIdx);
01499     if (getLoopPhiForCounter(IncV, L, DT) != Phi)
01500       continue;
01501 
01502     // Avoid reusing a potentially undef value to compute other values that may
01503     // have originally had a concrete definition.
01504     if (!hasConcreteDef(Phi)) {
01505       // We explicitly allow unknown phis as long as they are already used by
01506       // the loop test. In this case we assume that performing LFTR could not
01507       // increase the number of undef users.
01508       if (ICmpInst *Cond = getLoopTest(L)) {
01509         if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT)
01510             && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
01511           continue;
01512         }
01513       }
01514     }
01515     const SCEV *Init = AR->getStart();
01516 
01517     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
01518       // Don't force a live loop counter if another IV can be used.
01519       if (AlmostDeadIV(Phi, LatchBlock, Cond))
01520         continue;
01521 
01522       // Prefer to count-from-zero. This is a more "canonical" counter form. It
01523       // also prefers integer to pointer IVs.
01524       if (BestInit->isZero() != Init->isZero()) {
01525         if (BestInit->isZero())
01526           continue;
01527       }
01528       // If two IVs both count from zero or both count from nonzero then the
01529       // narrower is likely a dead phi that has been widened. Use the wider phi
01530       // to allow the other to be eliminated.
01531       else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
01532         continue;
01533     }
01534     BestPhi = Phi;
01535     BestInit = Init;
01536   }
01537   return BestPhi;
01538 }
01539 
01540 /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that
01541 /// holds the RHS of the new loop test.
01542 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
01543                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
01544   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
01545   assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
01546   const SCEV *IVInit = AR->getStart();
01547 
01548   // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
01549   // finds a valid pointer IV. Sign extend BECount in order to materialize a
01550   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
01551   // the existing GEPs whenever possible.
01552   if (IndVar->getType()->isPointerTy()
01553       && !IVCount->getType()->isPointerTy()) {
01554 
01555     // IVOffset will be the new GEP offset that is interpreted by GEP as a
01556     // signed value. IVCount on the other hand represents the loop trip count,
01557     // which is an unsigned value. FindLoopCounter only allows induction
01558     // variables that have a positive unit stride of one. This means we don't
01559     // have to handle the case of negative offsets (yet) and just need to zero
01560     // extend IVCount.
01561     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
01562     const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
01563 
01564     // Expand the code for the iteration count.
01565     assert(SE->isLoopInvariant(IVOffset, L) &&
01566            "Computed iteration count is not loop invariant!");
01567     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01568     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
01569 
01570     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
01571     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
01572     // We could handle pointer IVs other than i8*, but we need to compensate for
01573     // gep index scaling. See canExpandBackedgeTakenCount comments.
01574     assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
01575              cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
01576            && "unit stride pointer IV must be i8*");
01577 
01578     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
01579     return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
01580   }
01581   else {
01582     // In any other case, convert both IVInit and IVCount to integers before
01583     // comparing. This may result in SCEV expension of pointers, but in practice
01584     // SCEV will fold the pointer arithmetic away as such:
01585     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
01586     //
01587     // Valid Cases: (1) both integers is most common; (2) both may be pointers
01588     // for simple memset-style loops.
01589     //
01590     // IVInit integer and IVCount pointer would only occur if a canonical IV
01591     // were generated on top of case #2, which is not expected.
01592 
01593     const SCEV *IVLimit = nullptr;
01594     // For unit stride, IVCount = Start + BECount with 2's complement overflow.
01595     // For non-zero Start, compute IVCount here.
01596     if (AR->getStart()->isZero())
01597       IVLimit = IVCount;
01598     else {
01599       assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
01600       const SCEV *IVInit = AR->getStart();
01601 
01602       // For integer IVs, truncate the IV before computing IVInit + BECount.
01603       if (SE->getTypeSizeInBits(IVInit->getType())
01604           > SE->getTypeSizeInBits(IVCount->getType()))
01605         IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
01606 
01607       IVLimit = SE->getAddExpr(IVInit, IVCount);
01608     }
01609     // Expand the code for the iteration count.
01610     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01611     IRBuilder<> Builder(BI);
01612     assert(SE->isLoopInvariant(IVLimit, L) &&
01613            "Computed iteration count is not loop invariant!");
01614     // Ensure that we generate the same type as IndVar, or a smaller integer
01615     // type. In the presence of null pointer values, we have an integer type
01616     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
01617     Type *LimitTy = IVCount->getType()->isPointerTy() ?
01618       IndVar->getType() : IVCount->getType();
01619     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
01620   }
01621 }
01622 
01623 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
01624 /// loop to be a canonical != comparison against the incremented loop induction
01625 /// variable.  This pass is able to rewrite the exit tests of any loop where the
01626 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
01627 /// is actually a much broader range than just linear tests.
01628 Value *IndVarSimplify::
01629 LinearFunctionTestReplace(Loop *L,
01630                           const SCEV *BackedgeTakenCount,
01631                           PHINode *IndVar,
01632                           SCEVExpander &Rewriter) {
01633   assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
01634 
01635   // Initialize CmpIndVar and IVCount to their preincremented values.
01636   Value *CmpIndVar = IndVar;
01637   const SCEV *IVCount = BackedgeTakenCount;
01638 
01639   // If the exiting block is the same as the backedge block, we prefer to
01640   // compare against the post-incremented value, otherwise we must compare
01641   // against the preincremented value.
01642   if (L->getExitingBlock() == L->getLoopLatch()) {
01643     // Add one to the "backedge-taken" count to get the trip count.
01644     // This addition may overflow, which is valid as long as the comparison is
01645     // truncated to BackedgeTakenCount->getType().
01646     IVCount = SE->getAddExpr(BackedgeTakenCount,
01647                              SE->getConstant(BackedgeTakenCount->getType(), 1));
01648     // The BackedgeTaken expression contains the number of times that the
01649     // backedge branches to the loop header.  This is one less than the
01650     // number of times the loop executes, so use the incremented indvar.
01651     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
01652   }
01653 
01654   Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
01655   assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
01656          && "genLoopLimit missed a cast");
01657 
01658   // Insert a new icmp_ne or icmp_eq instruction before the branch.
01659   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01660   ICmpInst::Predicate P;
01661   if (L->contains(BI->getSuccessor(0)))
01662     P = ICmpInst::ICMP_NE;
01663   else
01664     P = ICmpInst::ICMP_EQ;
01665 
01666   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
01667                << "      LHS:" << *CmpIndVar << '\n'
01668                << "       op:\t"
01669                << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
01670                << "      RHS:\t" << *ExitCnt << "\n"
01671                << "  IVCount:\t" << *IVCount << "\n");
01672 
01673   IRBuilder<> Builder(BI);
01674 
01675   // LFTR can ignore IV overflow and truncate to the width of
01676   // BECount. This avoids materializing the add(zext(add)) expression.
01677   unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
01678   unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
01679   if (CmpIndVarSize > ExitCntSize) {
01680     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
01681     const SCEV *ARStart = AR->getStart();
01682     const SCEV *ARStep = AR->getStepRecurrence(*SE);
01683     // For constant IVCount, avoid truncation.
01684     if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
01685       const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue();
01686       APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue();
01687       // Note that the post-inc value of BackedgeTakenCount may have overflowed
01688       // above such that IVCount is now zero.
01689       if (IVCount != BackedgeTakenCount && Count == 0) {
01690         Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
01691         ++Count;
01692       }
01693       else
01694         Count = Count.zext(CmpIndVarSize);
01695       APInt NewLimit;
01696       if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
01697         NewLimit = Start - Count;
01698       else
01699         NewLimit = Start + Count;
01700       ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
01701 
01702       DEBUG(dbgs() << "  Widen RHS:\t" << *ExitCnt << "\n");
01703     } else {
01704       CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
01705                                       "lftr.wideiv");
01706     }
01707   }
01708   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
01709   Value *OrigCond = BI->getCondition();
01710   // It's tempting to use replaceAllUsesWith here to fully replace the old
01711   // comparison, but that's not immediately safe, since users of the old
01712   // comparison may not be dominated by the new comparison. Instead, just
01713   // update the branch to use the new comparison; in the common case this
01714   // will make old comparison dead.
01715   BI->setCondition(Cond);
01716   DeadInsts.push_back(OrigCond);
01717 
01718   ++NumLFTR;
01719   Changed = true;
01720   return Cond;
01721 }
01722 
01723 //===----------------------------------------------------------------------===//
01724 //  SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
01725 //===----------------------------------------------------------------------===//
01726 
01727 /// If there's a single exit block, sink any loop-invariant values that
01728 /// were defined in the preheader but not used inside the loop into the
01729 /// exit block to reduce register pressure in the loop.
01730 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
01731   BasicBlock *ExitBlock = L->getExitBlock();
01732   if (!ExitBlock) return;
01733 
01734   BasicBlock *Preheader = L->getLoopPreheader();
01735   if (!Preheader) return;
01736 
01737   Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
01738   BasicBlock::iterator I = Preheader->getTerminator();
01739   while (I != Preheader->begin()) {
01740     --I;
01741     // New instructions were inserted at the end of the preheader.
01742     if (isa<PHINode>(I))
01743       break;
01744 
01745     // Don't move instructions which might have side effects, since the side
01746     // effects need to complete before instructions inside the loop.  Also don't
01747     // move instructions which might read memory, since the loop may modify
01748     // memory. Note that it's okay if the instruction might have undefined
01749     // behavior: LoopSimplify guarantees that the preheader dominates the exit
01750     // block.
01751     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
01752       continue;
01753 
01754     // Skip debug info intrinsics.
01755     if (isa<DbgInfoIntrinsic>(I))
01756       continue;
01757 
01758     // Skip landingpad instructions.
01759     if (isa<LandingPadInst>(I))
01760       continue;
01761 
01762     // Don't sink alloca: we never want to sink static alloca's out of the
01763     // entry block, and correctly sinking dynamic alloca's requires
01764     // checks for stacksave/stackrestore intrinsics.
01765     // FIXME: Refactor this check somehow?
01766     if (isa<AllocaInst>(I))
01767       continue;
01768 
01769     // Determine if there is a use in or before the loop (direct or
01770     // otherwise).
01771     bool UsedInLoop = false;
01772     for (Use &U : I->uses()) {
01773       Instruction *User = cast<Instruction>(U.getUser());
01774       BasicBlock *UseBB = User->getParent();
01775       if (PHINode *P = dyn_cast<PHINode>(User)) {
01776         unsigned i =
01777           PHINode::getIncomingValueNumForOperand(U.getOperandNo());
01778         UseBB = P->getIncomingBlock(i);
01779       }
01780       if (UseBB == Preheader || L->contains(UseBB)) {
01781         UsedInLoop = true;
01782         break;
01783       }
01784     }
01785 
01786     // If there is, the def must remain in the preheader.
01787     if (UsedInLoop)
01788       continue;
01789 
01790     // Otherwise, sink it to the exit block.
01791     Instruction *ToMove = I;
01792     bool Done = false;
01793 
01794     if (I != Preheader->begin()) {
01795       // Skip debug info intrinsics.
01796       do {
01797         --I;
01798       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
01799 
01800       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
01801         Done = true;
01802     } else {
01803       Done = true;
01804     }
01805 
01806     ToMove->moveBefore(InsertPt);
01807     if (Done) break;
01808     InsertPt = ToMove;
01809   }
01810 }
01811 
01812 //===----------------------------------------------------------------------===//
01813 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
01814 //===----------------------------------------------------------------------===//
01815 
01816 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
01817   if (skipOptnoneFunction(L))
01818     return false;
01819 
01820   // If LoopSimplify form is not available, stay out of trouble. Some notes:
01821   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
01822   //    canonicalization can be a pessimization without LSR to "clean up"
01823   //    afterwards.
01824   //  - We depend on having a preheader; in particular,
01825   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
01826   //    and we're in trouble if we can't find the induction variable even when
01827   //    we've manually inserted one.
01828   if (!L->isLoopSimplifyForm())
01829     return false;
01830 
01831   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
01832   SE = &getAnalysis<ScalarEvolution>();
01833   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01834   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
01835   TLI = TLIP ? &TLIP->getTLI() : nullptr;
01836   auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
01837   TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
01838   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
01839 
01840   DeadInsts.clear();
01841   Changed = false;
01842 
01843   // If there are any floating-point recurrences, attempt to
01844   // transform them to use integer recurrences.
01845   RewriteNonIntegerIVs(L);
01846 
01847   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
01848 
01849   // Create a rewriter object which we'll use to transform the code with.
01850   SCEVExpander Rewriter(*SE, DL, "indvars");
01851 #ifndef NDEBUG
01852   Rewriter.setDebugType(DEBUG_TYPE);
01853 #endif
01854 
01855   // Eliminate redundant IV users.
01856   //
01857   // Simplification works best when run before other consumers of SCEV. We
01858   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
01859   // other expressions involving loop IVs have been evaluated. This helps SCEV
01860   // set no-wrap flags before normalizing sign/zero extension.
01861   Rewriter.disableCanonicalMode();
01862   SimplifyAndExtend(L, Rewriter, LPM);
01863 
01864   // Check to see if this loop has a computable loop-invariant execution count.
01865   // If so, this means that we can compute the final value of any expressions
01866   // that are recurrent in the loop, and substitute the exit values from the
01867   // loop into any instructions outside of the loop that use the final values of
01868   // the current expressions.
01869   //
01870   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
01871     RewriteLoopExitValues(L, Rewriter);
01872 
01873   // Eliminate redundant IV cycles.
01874   NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
01875 
01876   // If we have a trip count expression, rewrite the loop's exit condition
01877   // using it.  We can currently only handle loops with a single exit.
01878   if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) {
01879     PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
01880     if (IndVar) {
01881       // Check preconditions for proper SCEVExpander operation. SCEV does not
01882       // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
01883       // pass that uses the SCEVExpander must do it. This does not work well for
01884       // loop passes because SCEVExpander makes assumptions about all loops,
01885       // while LoopPassManager only forces the current loop to be simplified.
01886       //
01887       // FIXME: SCEV expansion has no way to bail out, so the caller must
01888       // explicitly check any assumptions made by SCEV. Brittle.
01889       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
01890       if (!AR || AR->getLoop()->getLoopPreheader())
01891         (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
01892                                         Rewriter);
01893     }
01894   }
01895   // Clear the rewriter cache, because values that are in the rewriter's cache
01896   // can be deleted in the loop below, causing the AssertingVH in the cache to
01897   // trigger.
01898   Rewriter.clear();
01899 
01900   // Now that we're done iterating through lists, clean up any instructions
01901   // which are now dead.
01902   while (!DeadInsts.empty())
01903     if (Instruction *Inst =
01904           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
01905       RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
01906 
01907   // The Rewriter may not be used from this point on.
01908 
01909   // Loop-invariant instructions in the preheader that aren't used in the
01910   // loop may be sunk below the loop to reduce register pressure.
01911   SinkUnusedInvariants(L);
01912 
01913   // Clean up dead instructions.
01914   Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
01915   // Check a post-condition.
01916   assert(L->isLCSSAForm(*DT) &&
01917          "Indvars did not leave the loop in lcssa form!");
01918 
01919   // Verify that LFTR, and any other change have not interfered with SCEV's
01920   // ability to compute trip count.
01921 #ifndef NDEBUG
01922   if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
01923     SE->forgetLoop(L);
01924     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
01925     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
01926         SE->getTypeSizeInBits(NewBECount->getType()))
01927       NewBECount = SE->getTruncateOrNoop(NewBECount,
01928                                          BackedgeTakenCount->getType());
01929     else
01930       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
01931                                                  NewBECount->getType());
01932     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
01933   }
01934 #endif
01935 
01936   return Changed;
01937 }