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       // If we were unable to completely replace the PHI node, clone the PHI
00626       // and delete the original one. This lets IVUsers and any other maps
00627       // purge the original user from their records.
00628       if (!LCSSASafePhiForRAUW) {
00629         PHINode *NewPN = cast<PHINode>(PN->clone());
00630         NewPN->takeName(PN);
00631         NewPN->insertBefore(PN);
00632         PN->replaceAllUsesWith(NewPN);
00633         PN->eraseFromParent();
00634       }
00635     }
00636   }
00637 
00638   // The insertion point instruction may have been deleted; clear it out
00639   // so that the rewriter doesn't trip over it later.
00640   Rewriter.clearInsertPoint();
00641 }
00642 
00643 //===----------------------------------------------------------------------===//
00644 //  IV Widening - Extend the width of an IV to cover its widest uses.
00645 //===----------------------------------------------------------------------===//
00646 
00647 namespace {
00648   // Collect information about induction variables that are used by sign/zero
00649   // extend operations. This information is recorded by CollectExtend and
00650   // provides the input to WidenIV.
00651   struct WideIVInfo {
00652     PHINode *NarrowIV;
00653     Type *WidestNativeType; // Widest integer type created [sz]ext
00654     bool IsSigned;          // Was a sext user seen before a zext?
00655 
00656     WideIVInfo() : NarrowIV(nullptr), WidestNativeType(nullptr),
00657                    IsSigned(false) {}
00658   };
00659 }
00660 
00661 /// visitCast - Update information about the induction variable that is
00662 /// extended by this sign or zero extend operation. This is used to determine
00663 /// the final width of the IV before actually widening it.
00664 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
00665                         const TargetTransformInfo *TTI) {
00666   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
00667   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
00668     return;
00669 
00670   Type *Ty = Cast->getType();
00671   uint64_t Width = SE->getTypeSizeInBits(Ty);
00672   if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
00673     return;
00674 
00675   // Cast is either an sext or zext up to this point.
00676   // We should not widen an indvar if arithmetics on the wider indvar are more
00677   // expensive than those on the narrower indvar. We check only the cost of ADD
00678   // because at least an ADD is required to increment the induction variable. We
00679   // could compute more comprehensively the cost of all instructions on the
00680   // induction variable when necessary.
00681   if (TTI &&
00682       TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
00683           TTI->getArithmeticInstrCost(Instruction::Add,
00684                                       Cast->getOperand(0)->getType())) {
00685     return;
00686   }
00687 
00688   if (!WI.WidestNativeType) {
00689     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
00690     WI.IsSigned = IsSigned;
00691     return;
00692   }
00693 
00694   // We extend the IV to satisfy the sign of its first user, arbitrarily.
00695   if (WI.IsSigned != IsSigned)
00696     return;
00697 
00698   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
00699     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
00700 }
00701 
00702 namespace {
00703 
00704 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
00705 /// WideIV that computes the same value as the Narrow IV def.  This avoids
00706 /// caching Use* pointers.
00707 struct NarrowIVDefUse {
00708   Instruction *NarrowDef;
00709   Instruction *NarrowUse;
00710   Instruction *WideDef;
00711 
00712   NarrowIVDefUse(): NarrowDef(nullptr), NarrowUse(nullptr), WideDef(nullptr) {}
00713 
00714   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
00715     NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
00716 };
00717 
00718 /// WidenIV - The goal of this transform is to remove sign and zero extends
00719 /// without creating any new induction variables. To do this, it creates a new
00720 /// phi of the wider type and redirects all users, either removing extends or
00721 /// inserting truncs whenever we stop propagating the type.
00722 ///
00723 class WidenIV {
00724   // Parameters
00725   PHINode *OrigPhi;
00726   Type *WideType;
00727   bool IsSigned;
00728 
00729   // Context
00730   LoopInfo        *LI;
00731   Loop            *L;
00732   ScalarEvolution *SE;
00733   DominatorTree   *DT;
00734 
00735   // Result
00736   PHINode *WidePhi;
00737   Instruction *WideInc;
00738   const SCEV *WideIncExpr;
00739   SmallVectorImpl<WeakVH> &DeadInsts;
00740 
00741   SmallPtrSet<Instruction*,16> Widened;
00742   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
00743 
00744 public:
00745   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
00746           ScalarEvolution *SEv, DominatorTree *DTree,
00747           SmallVectorImpl<WeakVH> &DI) :
00748     OrigPhi(WI.NarrowIV),
00749     WideType(WI.WidestNativeType),
00750     IsSigned(WI.IsSigned),
00751     LI(LInfo),
00752     L(LI->getLoopFor(OrigPhi->getParent())),
00753     SE(SEv),
00754     DT(DTree),
00755     WidePhi(nullptr),
00756     WideInc(nullptr),
00757     WideIncExpr(nullptr),
00758     DeadInsts(DI) {
00759     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
00760   }
00761 
00762   PHINode *CreateWideIV(SCEVExpander &Rewriter);
00763 
00764 protected:
00765   Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
00766                    Instruction *Use);
00767 
00768   Instruction *CloneIVUser(NarrowIVDefUse DU);
00769 
00770   const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
00771 
00772   const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
00773 
00774   const SCEV *GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
00775                               unsigned OpCode) const;
00776 
00777   Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
00778 
00779   bool WidenLoopCompare(NarrowIVDefUse DU);
00780 
00781   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
00782 };
00783 } // anonymous namespace
00784 
00785 /// isLoopInvariant - Perform a quick domtree based check for loop invariance
00786 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
00787 /// gratuitous for this purpose.
00788 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
00789   Instruction *Inst = dyn_cast<Instruction>(V);
00790   if (!Inst)
00791     return true;
00792 
00793   return DT->properlyDominates(Inst->getParent(), L->getHeader());
00794 }
00795 
00796 Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
00797                           Instruction *Use) {
00798   // Set the debug location and conservative insertion point.
00799   IRBuilder<> Builder(Use);
00800   // Hoist the insertion point into loop preheaders as far as possible.
00801   for (const Loop *L = LI->getLoopFor(Use->getParent());
00802        L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
00803        L = L->getParentLoop())
00804     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
00805 
00806   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
00807                     Builder.CreateZExt(NarrowOper, WideType);
00808 }
00809 
00810 /// CloneIVUser - Instantiate a wide operation to replace a narrow
00811 /// operation. This only needs to handle operations that can evaluation to
00812 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
00813 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
00814   unsigned Opcode = DU.NarrowUse->getOpcode();
00815   switch (Opcode) {
00816   default:
00817     return nullptr;
00818   case Instruction::Add:
00819   case Instruction::Mul:
00820   case Instruction::UDiv:
00821   case Instruction::Sub:
00822   case Instruction::And:
00823   case Instruction::Or:
00824   case Instruction::Xor:
00825   case Instruction::Shl:
00826   case Instruction::LShr:
00827   case Instruction::AShr:
00828     DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
00829 
00830     // Replace NarrowDef operands with WideDef. Otherwise, we don't know
00831     // anything about the narrow operand yet so must insert a [sz]ext. It is
00832     // probably loop invariant and will be folded or hoisted. If it actually
00833     // comes from a widened IV, it should be removed during a future call to
00834     // WidenIVUse.
00835     Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
00836       getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
00837     Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
00838       getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
00839 
00840     BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
00841     BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
00842                                                     LHS, RHS,
00843                                                     NarrowBO->getName());
00844     IRBuilder<> Builder(DU.NarrowUse);
00845     Builder.Insert(WideBO);
00846     if (const OverflowingBinaryOperator *OBO =
00847         dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
00848       if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
00849       if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
00850     }
00851     return WideBO;
00852   }
00853 }
00854 
00855 const SCEV *WidenIV::GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
00856                                      unsigned OpCode) const {
00857   if (OpCode == Instruction::Add)
00858     return SE->getAddExpr(LHS, RHS);
00859   if (OpCode == Instruction::Sub)
00860     return SE->getMinusSCEV(LHS, RHS);
00861   if (OpCode == Instruction::Mul)
00862     return SE->getMulExpr(LHS, RHS);
00863 
00864   llvm_unreachable("Unsupported opcode.");
00865 }
00866 
00867 /// No-wrap operations can transfer sign extension of their result to their
00868 /// operands. Generate the SCEV value for the widened operation without
00869 /// actually modifying the IR yet. If the expression after extending the
00870 /// operands is an AddRec for this loop, return it.
00871 const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
00872 
00873   // Handle the common case of add<nsw/nuw>
00874   const unsigned OpCode = DU.NarrowUse->getOpcode();
00875   // Only Add/Sub/Mul instructions supported yet.
00876   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
00877       OpCode != Instruction::Mul)
00878     return nullptr;
00879 
00880   // One operand (NarrowDef) has already been extended to WideDef. Now determine
00881   // if extending the other will lead to a recurrence.
00882   const unsigned ExtendOperIdx =
00883       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
00884   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
00885 
00886   const SCEV *ExtendOperExpr = nullptr;
00887   const OverflowingBinaryOperator *OBO =
00888     cast<OverflowingBinaryOperator>(DU.NarrowUse);
00889   if (IsSigned && OBO->hasNoSignedWrap())
00890     ExtendOperExpr = SE->getSignExtendExpr(
00891       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
00892   else if(!IsSigned && OBO->hasNoUnsignedWrap())
00893     ExtendOperExpr = SE->getZeroExtendExpr(
00894       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
00895   else
00896     return nullptr;
00897 
00898   // When creating this SCEV expr, don't apply the current operations NSW or NUW
00899   // flags. This instruction may be guarded by control flow that the no-wrap
00900   // behavior depends on. Non-control-equivalent instructions can be mapped to
00901   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
00902   // semantics to those operations.
00903   const SCEV *lhs = SE->getSCEV(DU.WideDef);
00904   const SCEV *rhs = ExtendOperExpr;
00905 
00906   // Let's swap operands to the initial order for the case of non-commutative
00907   // operations, like SUB. See PR21014.
00908   if (ExtendOperIdx == 0)
00909     std::swap(lhs, rhs);
00910   const SCEVAddRecExpr *AddRec =
00911       dyn_cast<SCEVAddRecExpr>(GetSCEVByOpCode(lhs, rhs, OpCode));
00912 
00913   if (!AddRec || AddRec->getLoop() != L)
00914     return nullptr;
00915   return AddRec;
00916 }
00917 
00918 /// GetWideRecurrence - Is this instruction potentially interesting from
00919 /// IVUsers' perspective after widening it's type? In other words, can the
00920 /// extend be safely hoisted out of the loop with SCEV reducing the value to a
00921 /// recurrence on the same loop. If so, return the sign or zero extended
00922 /// recurrence. Otherwise return NULL.
00923 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
00924   if (!SE->isSCEVable(NarrowUse->getType()))
00925     return nullptr;
00926 
00927   const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
00928   if (SE->getTypeSizeInBits(NarrowExpr->getType())
00929       >= SE->getTypeSizeInBits(WideType)) {
00930     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
00931     // index. So don't follow this use.
00932     return nullptr;
00933   }
00934 
00935   const SCEV *WideExpr = IsSigned ?
00936     SE->getSignExtendExpr(NarrowExpr, WideType) :
00937     SE->getZeroExtendExpr(NarrowExpr, WideType);
00938   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
00939   if (!AddRec || AddRec->getLoop() != L)
00940     return nullptr;
00941   return AddRec;
00942 }
00943 
00944 /// This IV user cannot be widen. Replace this use of the original narrow IV
00945 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
00946 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) {
00947   DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
00948         << " for user " << *DU.NarrowUse << "\n");
00949   IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
00950   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
00951   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
00952 }
00953 
00954 /// If the narrow use is a compare instruction, then widen the compare
00955 //  (and possibly the other operand).  The extend operation is hoisted into the
00956 // loop preheader as far as possible.
00957 bool WidenIV::WidenLoopCompare(NarrowIVDefUse DU) {
00958   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
00959   if (!Cmp)
00960     return false;
00961 
00962   // Sign of IV user and compare must match.
00963   if (IsSigned != CmpInst::isSigned(Cmp->getPredicate()))
00964     return false;
00965 
00966   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
00967   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
00968   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
00969   assert (CastWidth <= IVWidth && "Unexpected width while widening compare.");
00970 
00971   // Widen the compare instruction.
00972   IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
00973   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
00974 
00975   // Widen the other operand of the compare, if necessary.
00976   if (CastWidth < IVWidth) {
00977     Value *ExtOp = getExtend(Op, WideType, IsSigned, Cmp);
00978     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
00979   }
00980   return true;
00981 }
00982 
00983 /// WidenIVUse - Determine whether an individual user of the narrow IV can be
00984 /// widened. If so, return the wide clone of the user.
00985 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
00986 
00987   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
00988   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
00989     if (LI->getLoopFor(UsePhi->getParent()) != L) {
00990       // For LCSSA phis, sink the truncate outside the loop.
00991       // After SimplifyCFG most loop exit targets have a single predecessor.
00992       // Otherwise fall back to a truncate within the loop.
00993       if (UsePhi->getNumOperands() != 1)
00994         truncateIVUse(DU, DT);
00995       else {
00996         PHINode *WidePhi =
00997           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
00998                           UsePhi);
00999         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
01000         IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
01001         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
01002         UsePhi->replaceAllUsesWith(Trunc);
01003         DeadInsts.push_back(UsePhi);
01004         DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
01005               << " to " << *WidePhi << "\n");
01006       }
01007       return nullptr;
01008     }
01009   }
01010   // Our raison d'etre! Eliminate sign and zero extension.
01011   if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
01012     Value *NewDef = DU.WideDef;
01013     if (DU.NarrowUse->getType() != WideType) {
01014       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
01015       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
01016       if (CastWidth < IVWidth) {
01017         // The cast isn't as wide as the IV, so insert a Trunc.
01018         IRBuilder<> Builder(DU.NarrowUse);
01019         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
01020       }
01021       else {
01022         // A wider extend was hidden behind a narrower one. This may induce
01023         // another round of IV widening in which the intermediate IV becomes
01024         // dead. It should be very rare.
01025         DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
01026               << " not wide enough to subsume " << *DU.NarrowUse << "\n");
01027         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
01028         NewDef = DU.NarrowUse;
01029       }
01030     }
01031     if (NewDef != DU.NarrowUse) {
01032       DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
01033             << " replaced by " << *DU.WideDef << "\n");
01034       ++NumElimExt;
01035       DU.NarrowUse->replaceAllUsesWith(NewDef);
01036       DeadInsts.push_back(DU.NarrowUse);
01037     }
01038     // Now that the extend is gone, we want to expose it's uses for potential
01039     // further simplification. We don't need to directly inform SimplifyIVUsers
01040     // of the new users, because their parent IV will be processed later as a
01041     // new loop phi. If we preserved IVUsers analysis, we would also want to
01042     // push the uses of WideDef here.
01043 
01044     // No further widening is needed. The deceased [sz]ext had done it for us.
01045     return nullptr;
01046   }
01047 
01048   // Does this user itself evaluate to a recurrence after widening?
01049   const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
01050   if (!WideAddRec)
01051     WideAddRec = GetExtendedOperandRecurrence(DU);
01052 
01053   if (!WideAddRec) {
01054     // If use is a loop condition, try to promote the condition instead of
01055     // truncating the IV first.
01056     if (WidenLoopCompare(DU))
01057       return nullptr;
01058 
01059     // This user does not evaluate to a recurence after widening, so don't
01060     // follow it. Instead insert a Trunc to kill off the original use,
01061     // eventually isolating the original narrow IV so it can be removed.
01062     truncateIVUse(DU, DT);
01063     return nullptr;
01064   }
01065   // Assume block terminators cannot evaluate to a recurrence. We can't to
01066   // insert a Trunc after a terminator if there happens to be a critical edge.
01067   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
01068          "SCEV is not expected to evaluate a block terminator");
01069 
01070   // Reuse the IV increment that SCEVExpander created as long as it dominates
01071   // NarrowUse.
01072   Instruction *WideUse = nullptr;
01073   if (WideAddRec == WideIncExpr
01074       && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
01075     WideUse = WideInc;
01076   else {
01077     WideUse = CloneIVUser(DU);
01078     if (!WideUse)
01079       return nullptr;
01080   }
01081   // Evaluation of WideAddRec ensured that the narrow expression could be
01082   // extended outside the loop without overflow. This suggests that the wide use
01083   // evaluates to the same expression as the extended narrow use, but doesn't
01084   // absolutely guarantee it. Hence the following failsafe check. In rare cases
01085   // where it fails, we simply throw away the newly created wide use.
01086   if (WideAddRec != SE->getSCEV(WideUse)) {
01087     DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
01088           << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
01089     DeadInsts.push_back(WideUse);
01090     return nullptr;
01091   }
01092 
01093   // Returning WideUse pushes it on the worklist.
01094   return WideUse;
01095 }
01096 
01097 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
01098 ///
01099 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
01100   for (User *U : NarrowDef->users()) {
01101     Instruction *NarrowUser = cast<Instruction>(U);
01102 
01103     // Handle data flow merges and bizarre phi cycles.
01104     if (!Widened.insert(NarrowUser).second)
01105       continue;
01106 
01107     NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUser, WideDef));
01108   }
01109 }
01110 
01111 /// CreateWideIV - Process a single induction variable. First use the
01112 /// SCEVExpander to create a wide induction variable that evaluates to the same
01113 /// recurrence as the original narrow IV. Then use a worklist to forward
01114 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
01115 /// interesting IV users, the narrow IV will be isolated for removal by
01116 /// DeleteDeadPHIs.
01117 ///
01118 /// It would be simpler to delete uses as they are processed, but we must avoid
01119 /// invalidating SCEV expressions.
01120 ///
01121 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
01122   // Is this phi an induction variable?
01123   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
01124   if (!AddRec)
01125     return nullptr;
01126 
01127   // Widen the induction variable expression.
01128   const SCEV *WideIVExpr = IsSigned ?
01129     SE->getSignExtendExpr(AddRec, WideType) :
01130     SE->getZeroExtendExpr(AddRec, WideType);
01131 
01132   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
01133          "Expect the new IV expression to preserve its type");
01134 
01135   // Can the IV be extended outside the loop without overflow?
01136   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
01137   if (!AddRec || AddRec->getLoop() != L)
01138     return nullptr;
01139 
01140   // An AddRec must have loop-invariant operands. Since this AddRec is
01141   // materialized by a loop header phi, the expression cannot have any post-loop
01142   // operands, so they must dominate the loop header.
01143   assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
01144          SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
01145          && "Loop header phi recurrence inputs do not dominate the loop");
01146 
01147   // The rewriter provides a value for the desired IV expression. This may
01148   // either find an existing phi or materialize a new one. Either way, we
01149   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
01150   // of the phi-SCC dominates the loop entry.
01151   Instruction *InsertPt = L->getHeader()->begin();
01152   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
01153 
01154   // Remembering the WideIV increment generated by SCEVExpander allows
01155   // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
01156   // employ a general reuse mechanism because the call above is the only call to
01157   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
01158   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
01159     WideInc =
01160       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
01161     WideIncExpr = SE->getSCEV(WideInc);
01162   }
01163 
01164   DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
01165   ++NumWidened;
01166 
01167   // Traverse the def-use chain using a worklist starting at the original IV.
01168   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
01169 
01170   Widened.insert(OrigPhi);
01171   pushNarrowIVUsers(OrigPhi, WidePhi);
01172 
01173   while (!NarrowIVUsers.empty()) {
01174     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
01175 
01176     // Process a def-use edge. This may replace the use, so don't hold a
01177     // use_iterator across it.
01178     Instruction *WideUse = WidenIVUse(DU, Rewriter);
01179 
01180     // Follow all def-use edges from the previous narrow use.
01181     if (WideUse)
01182       pushNarrowIVUsers(DU.NarrowUse, WideUse);
01183 
01184     // WidenIVUse may have removed the def-use edge.
01185     if (DU.NarrowDef->use_empty())
01186       DeadInsts.push_back(DU.NarrowDef);
01187   }
01188   return WidePhi;
01189 }
01190 
01191 //===----------------------------------------------------------------------===//
01192 //  Live IV Reduction - Minimize IVs live across the loop.
01193 //===----------------------------------------------------------------------===//
01194 
01195 
01196 //===----------------------------------------------------------------------===//
01197 //  Simplification of IV users based on SCEV evaluation.
01198 //===----------------------------------------------------------------------===//
01199 
01200 namespace {
01201   class IndVarSimplifyVisitor : public IVVisitor {
01202     ScalarEvolution *SE;
01203     const TargetTransformInfo *TTI;
01204     PHINode *IVPhi;
01205 
01206   public:
01207     WideIVInfo WI;
01208 
01209     IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
01210                           const TargetTransformInfo *TTI,
01211                           const DominatorTree *DTree)
01212         : SE(SCEV), TTI(TTI), IVPhi(IV) {
01213       DT = DTree;
01214       WI.NarrowIV = IVPhi;
01215       if (ReduceLiveIVs)
01216         setSplitOverflowIntrinsics();
01217     }
01218 
01219     // Implement the interface used by simplifyUsersOfIV.
01220     void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
01221   };
01222 }
01223 
01224 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
01225 /// users. Each successive simplification may push more users which may
01226 /// themselves be candidates for simplification.
01227 ///
01228 /// Sign/Zero extend elimination is interleaved with IV simplification.
01229 ///
01230 void IndVarSimplify::SimplifyAndExtend(Loop *L,
01231                                        SCEVExpander &Rewriter,
01232                                        LPPassManager &LPM) {
01233   SmallVector<WideIVInfo, 8> WideIVs;
01234 
01235   SmallVector<PHINode*, 8> LoopPhis;
01236   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
01237     LoopPhis.push_back(cast<PHINode>(I));
01238   }
01239   // Each round of simplification iterates through the SimplifyIVUsers worklist
01240   // for all current phis, then determines whether any IVs can be
01241   // widened. Widening adds new phis to LoopPhis, inducing another round of
01242   // simplification on the wide IVs.
01243   while (!LoopPhis.empty()) {
01244     // Evaluate as many IV expressions as possible before widening any IVs. This
01245     // forces SCEV to set no-wrap flags before evaluating sign/zero
01246     // extension. The first time SCEV attempts to normalize sign/zero extension,
01247     // the result becomes final. So for the most predictable results, we delay
01248     // evaluation of sign/zero extend evaluation until needed, and avoid running
01249     // other SCEV based analysis prior to SimplifyAndExtend.
01250     do {
01251       PHINode *CurrIV = LoopPhis.pop_back_val();
01252 
01253       // Information about sign/zero extensions of CurrIV.
01254       IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
01255 
01256       Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor);
01257 
01258       if (Visitor.WI.WidestNativeType) {
01259         WideIVs.push_back(Visitor.WI);
01260       }
01261     } while(!LoopPhis.empty());
01262 
01263     for (; !WideIVs.empty(); WideIVs.pop_back()) {
01264       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
01265       if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
01266         Changed = true;
01267         LoopPhis.push_back(WidePhi);
01268       }
01269     }
01270   }
01271 }
01272 
01273 //===----------------------------------------------------------------------===//
01274 //  LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
01275 //===----------------------------------------------------------------------===//
01276 
01277 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
01278 /// count expression can be safely and cheaply expanded into an instruction
01279 /// sequence that can be used by LinearFunctionTestReplace.
01280 ///
01281 /// TODO: This fails for pointer-type loop counters with greater than one byte
01282 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
01283 /// we could skip this check in the case that the LFTR loop counter (chosen by
01284 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
01285 /// the loop test to an inequality test by checking the target data's alignment
01286 /// of element types (given that the initial pointer value originates from or is
01287 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
01288 /// However, we don't yet have a strong motivation for converting loop tests
01289 /// into inequality tests.
01290 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
01291                                         SCEVExpander &Rewriter) {
01292   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
01293   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
01294       BackedgeTakenCount->isZero())
01295     return false;
01296 
01297   if (!L->getExitingBlock())
01298     return false;
01299 
01300   // Can't rewrite non-branch yet.
01301   if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
01302     return false;
01303 
01304   if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
01305     return false;
01306 
01307   return true;
01308 }
01309 
01310 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
01311 /// invariant value to the phi.
01312 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
01313   Instruction *IncI = dyn_cast<Instruction>(IncV);
01314   if (!IncI)
01315     return nullptr;
01316 
01317   switch (IncI->getOpcode()) {
01318   case Instruction::Add:
01319   case Instruction::Sub:
01320     break;
01321   case Instruction::GetElementPtr:
01322     // An IV counter must preserve its type.
01323     if (IncI->getNumOperands() == 2)
01324       break;
01325   default:
01326     return nullptr;
01327   }
01328 
01329   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
01330   if (Phi && Phi->getParent() == L->getHeader()) {
01331     if (isLoopInvariant(IncI->getOperand(1), L, DT))
01332       return Phi;
01333     return nullptr;
01334   }
01335   if (IncI->getOpcode() == Instruction::GetElementPtr)
01336     return nullptr;
01337 
01338   // Allow add/sub to be commuted.
01339   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
01340   if (Phi && Phi->getParent() == L->getHeader()) {
01341     if (isLoopInvariant(IncI->getOperand(0), L, DT))
01342       return Phi;
01343   }
01344   return nullptr;
01345 }
01346 
01347 /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
01348 static ICmpInst *getLoopTest(Loop *L) {
01349   assert(L->getExitingBlock() && "expected loop exit");
01350 
01351   BasicBlock *LatchBlock = L->getLoopLatch();
01352   // Don't bother with LFTR if the loop is not properly simplified.
01353   if (!LatchBlock)
01354     return nullptr;
01355 
01356   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
01357   assert(BI && "expected exit branch");
01358 
01359   return dyn_cast<ICmpInst>(BI->getCondition());
01360 }
01361 
01362 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
01363 /// that the current exit test is already sufficiently canonical.
01364 static bool needsLFTR(Loop *L, DominatorTree *DT) {
01365   // Do LFTR to simplify the exit condition to an ICMP.
01366   ICmpInst *Cond = getLoopTest(L);
01367   if (!Cond)
01368     return true;
01369 
01370   // Do LFTR to simplify the exit ICMP to EQ/NE
01371   ICmpInst::Predicate Pred = Cond->getPredicate();
01372   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
01373     return true;
01374 
01375   // Look for a loop invariant RHS
01376   Value *LHS = Cond->getOperand(0);
01377   Value *RHS = Cond->getOperand(1);
01378   if (!isLoopInvariant(RHS, L, DT)) {
01379     if (!isLoopInvariant(LHS, L, DT))
01380       return true;
01381     std::swap(LHS, RHS);
01382   }
01383   // Look for a simple IV counter LHS
01384   PHINode *Phi = dyn_cast<PHINode>(LHS);
01385   if (!Phi)
01386     Phi = getLoopPhiForCounter(LHS, L, DT);
01387 
01388   if (!Phi)
01389     return true;
01390 
01391   // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
01392   int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
01393   if (Idx < 0)
01394     return true;
01395 
01396   // Do LFTR if the exit condition's IV is *not* a simple counter.
01397   Value *IncV = Phi->getIncomingValue(Idx);
01398   return Phi != getLoopPhiForCounter(IncV, L, DT);
01399 }
01400 
01401 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
01402 /// down to checking that all operands are constant and listing instructions
01403 /// that may hide undef.
01404 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
01405                                unsigned Depth) {
01406   if (isa<Constant>(V))
01407     return !isa<UndefValue>(V);
01408 
01409   if (Depth >= 6)
01410     return false;
01411 
01412   // Conservatively handle non-constant non-instructions. For example, Arguments
01413   // may be undef.
01414   Instruction *I = dyn_cast<Instruction>(V);
01415   if (!I)
01416     return false;
01417 
01418   // Load and return values may be undef.
01419   if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
01420     return false;
01421 
01422   // Optimistically handle other instructions.
01423   for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
01424     if (!Visited.insert(*OI).second)
01425       continue;
01426     if (!hasConcreteDefImpl(*OI, Visited, Depth+1))
01427       return false;
01428   }
01429   return true;
01430 }
01431 
01432 /// Return true if the given value is concrete. We must prove that undef can
01433 /// never reach it.
01434 ///
01435 /// TODO: If we decide that this is a good approach to checking for undef, we
01436 /// may factor it into a common location.
01437 static bool hasConcreteDef(Value *V) {
01438   SmallPtrSet<Value*, 8> Visited;
01439   Visited.insert(V);
01440   return hasConcreteDefImpl(V, Visited, 0);
01441 }
01442 
01443 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
01444 /// be rewritten) loop exit test.
01445 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
01446   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
01447   Value *IncV = Phi->getIncomingValue(LatchIdx);
01448 
01449   for (User *U : Phi->users())
01450     if (U != Cond && U != IncV) return false;
01451 
01452   for (User *U : IncV->users())
01453     if (U != Cond && U != Phi) return false;
01454   return true;
01455 }
01456 
01457 /// FindLoopCounter - Find an affine IV in canonical form.
01458 ///
01459 /// BECount may be an i8* pointer type. The pointer difference is already
01460 /// valid count without scaling the address stride, so it remains a pointer
01461 /// expression as far as SCEV is concerned.
01462 ///
01463 /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
01464 ///
01465 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
01466 ///
01467 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
01468 /// This is difficult in general for SCEV because of potential overflow. But we
01469 /// could at least handle constant BECounts.
01470 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
01471                                 ScalarEvolution *SE, DominatorTree *DT) {
01472   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
01473 
01474   Value *Cond =
01475     cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
01476 
01477   // Loop over all of the PHI nodes, looking for a simple counter.
01478   PHINode *BestPhi = nullptr;
01479   const SCEV *BestInit = nullptr;
01480   BasicBlock *LatchBlock = L->getLoopLatch();
01481   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
01482 
01483   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
01484     PHINode *Phi = cast<PHINode>(I);
01485     if (!SE->isSCEVable(Phi->getType()))
01486       continue;
01487 
01488     // Avoid comparing an integer IV against a pointer Limit.
01489     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
01490       continue;
01491 
01492     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
01493     if (!AR || AR->getLoop() != L || !AR->isAffine())
01494       continue;
01495 
01496     // AR may be a pointer type, while BECount is an integer type.
01497     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
01498     // AR may not be a narrower type, or we may never exit.
01499     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
01500     if (PhiWidth < BCWidth ||
01501         !L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth))
01502       continue;
01503 
01504     const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
01505     if (!Step || !Step->isOne())
01506       continue;
01507 
01508     int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
01509     Value *IncV = Phi->getIncomingValue(LatchIdx);
01510     if (getLoopPhiForCounter(IncV, L, DT) != Phi)
01511       continue;
01512 
01513     // Avoid reusing a potentially undef value to compute other values that may
01514     // have originally had a concrete definition.
01515     if (!hasConcreteDef(Phi)) {
01516       // We explicitly allow unknown phis as long as they are already used by
01517       // the loop test. In this case we assume that performing LFTR could not
01518       // increase the number of undef users.
01519       if (ICmpInst *Cond = getLoopTest(L)) {
01520         if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT)
01521             && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
01522           continue;
01523         }
01524       }
01525     }
01526     const SCEV *Init = AR->getStart();
01527 
01528     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
01529       // Don't force a live loop counter if another IV can be used.
01530       if (AlmostDeadIV(Phi, LatchBlock, Cond))
01531         continue;
01532 
01533       // Prefer to count-from-zero. This is a more "canonical" counter form. It
01534       // also prefers integer to pointer IVs.
01535       if (BestInit->isZero() != Init->isZero()) {
01536         if (BestInit->isZero())
01537           continue;
01538       }
01539       // If two IVs both count from zero or both count from nonzero then the
01540       // narrower is likely a dead phi that has been widened. Use the wider phi
01541       // to allow the other to be eliminated.
01542       else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
01543         continue;
01544     }
01545     BestPhi = Phi;
01546     BestInit = Init;
01547   }
01548   return BestPhi;
01549 }
01550 
01551 /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that
01552 /// holds the RHS of the new loop test.
01553 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
01554                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
01555   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
01556   assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
01557   const SCEV *IVInit = AR->getStart();
01558 
01559   // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
01560   // finds a valid pointer IV. Sign extend BECount in order to materialize a
01561   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
01562   // the existing GEPs whenever possible.
01563   if (IndVar->getType()->isPointerTy()
01564       && !IVCount->getType()->isPointerTy()) {
01565 
01566     // IVOffset will be the new GEP offset that is interpreted by GEP as a
01567     // signed value. IVCount on the other hand represents the loop trip count,
01568     // which is an unsigned value. FindLoopCounter only allows induction
01569     // variables that have a positive unit stride of one. This means we don't
01570     // have to handle the case of negative offsets (yet) and just need to zero
01571     // extend IVCount.
01572     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
01573     const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
01574 
01575     // Expand the code for the iteration count.
01576     assert(SE->isLoopInvariant(IVOffset, L) &&
01577            "Computed iteration count is not loop invariant!");
01578     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01579     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
01580 
01581     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
01582     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
01583     // We could handle pointer IVs other than i8*, but we need to compensate for
01584     // gep index scaling. See canExpandBackedgeTakenCount comments.
01585     assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
01586              cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
01587            && "unit stride pointer IV must be i8*");
01588 
01589     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
01590     return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
01591   }
01592   else {
01593     // In any other case, convert both IVInit and IVCount to integers before
01594     // comparing. This may result in SCEV expension of pointers, but in practice
01595     // SCEV will fold the pointer arithmetic away as such:
01596     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
01597     //
01598     // Valid Cases: (1) both integers is most common; (2) both may be pointers
01599     // for simple memset-style loops.
01600     //
01601     // IVInit integer and IVCount pointer would only occur if a canonical IV
01602     // were generated on top of case #2, which is not expected.
01603 
01604     const SCEV *IVLimit = nullptr;
01605     // For unit stride, IVCount = Start + BECount with 2's complement overflow.
01606     // For non-zero Start, compute IVCount here.
01607     if (AR->getStart()->isZero())
01608       IVLimit = IVCount;
01609     else {
01610       assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
01611       const SCEV *IVInit = AR->getStart();
01612 
01613       // For integer IVs, truncate the IV before computing IVInit + BECount.
01614       if (SE->getTypeSizeInBits(IVInit->getType())
01615           > SE->getTypeSizeInBits(IVCount->getType()))
01616         IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
01617 
01618       IVLimit = SE->getAddExpr(IVInit, IVCount);
01619     }
01620     // Expand the code for the iteration count.
01621     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01622     IRBuilder<> Builder(BI);
01623     assert(SE->isLoopInvariant(IVLimit, L) &&
01624            "Computed iteration count is not loop invariant!");
01625     // Ensure that we generate the same type as IndVar, or a smaller integer
01626     // type. In the presence of null pointer values, we have an integer type
01627     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
01628     Type *LimitTy = IVCount->getType()->isPointerTy() ?
01629       IndVar->getType() : IVCount->getType();
01630     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
01631   }
01632 }
01633 
01634 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
01635 /// loop to be a canonical != comparison against the incremented loop induction
01636 /// variable.  This pass is able to rewrite the exit tests of any loop where the
01637 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
01638 /// is actually a much broader range than just linear tests.
01639 Value *IndVarSimplify::
01640 LinearFunctionTestReplace(Loop *L,
01641                           const SCEV *BackedgeTakenCount,
01642                           PHINode *IndVar,
01643                           SCEVExpander &Rewriter) {
01644   assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
01645 
01646   // Initialize CmpIndVar and IVCount to their preincremented values.
01647   Value *CmpIndVar = IndVar;
01648   const SCEV *IVCount = BackedgeTakenCount;
01649 
01650   // If the exiting block is the same as the backedge block, we prefer to
01651   // compare against the post-incremented value, otherwise we must compare
01652   // against the preincremented value.
01653   if (L->getExitingBlock() == L->getLoopLatch()) {
01654     // Add one to the "backedge-taken" count to get the trip count.
01655     // This addition may overflow, which is valid as long as the comparison is
01656     // truncated to BackedgeTakenCount->getType().
01657     IVCount = SE->getAddExpr(BackedgeTakenCount,
01658                              SE->getConstant(BackedgeTakenCount->getType(), 1));
01659     // The BackedgeTaken expression contains the number of times that the
01660     // backedge branches to the loop header.  This is one less than the
01661     // number of times the loop executes, so use the incremented indvar.
01662     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
01663   }
01664 
01665   Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
01666   assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
01667          && "genLoopLimit missed a cast");
01668 
01669   // Insert a new icmp_ne or icmp_eq instruction before the branch.
01670   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01671   ICmpInst::Predicate P;
01672   if (L->contains(BI->getSuccessor(0)))
01673     P = ICmpInst::ICMP_NE;
01674   else
01675     P = ICmpInst::ICMP_EQ;
01676 
01677   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
01678                << "      LHS:" << *CmpIndVar << '\n'
01679                << "       op:\t"
01680                << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
01681                << "      RHS:\t" << *ExitCnt << "\n"
01682                << "  IVCount:\t" << *IVCount << "\n");
01683 
01684   IRBuilder<> Builder(BI);
01685 
01686   // LFTR can ignore IV overflow and truncate to the width of
01687   // BECount. This avoids materializing the add(zext(add)) expression.
01688   unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
01689   unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
01690   if (CmpIndVarSize > ExitCntSize) {
01691     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
01692     const SCEV *ARStart = AR->getStart();
01693     const SCEV *ARStep = AR->getStepRecurrence(*SE);
01694     // For constant IVCount, avoid truncation.
01695     if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
01696       const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue();
01697       APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue();
01698       // Note that the post-inc value of BackedgeTakenCount may have overflowed
01699       // above such that IVCount is now zero.
01700       if (IVCount != BackedgeTakenCount && Count == 0) {
01701         Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
01702         ++Count;
01703       }
01704       else
01705         Count = Count.zext(CmpIndVarSize);
01706       APInt NewLimit;
01707       if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
01708         NewLimit = Start - Count;
01709       else
01710         NewLimit = Start + Count;
01711       ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
01712 
01713       DEBUG(dbgs() << "  Widen RHS:\t" << *ExitCnt << "\n");
01714     } else {
01715       CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
01716                                       "lftr.wideiv");
01717     }
01718   }
01719   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
01720   Value *OrigCond = BI->getCondition();
01721   // It's tempting to use replaceAllUsesWith here to fully replace the old
01722   // comparison, but that's not immediately safe, since users of the old
01723   // comparison may not be dominated by the new comparison. Instead, just
01724   // update the branch to use the new comparison; in the common case this
01725   // will make old comparison dead.
01726   BI->setCondition(Cond);
01727   DeadInsts.push_back(OrigCond);
01728 
01729   ++NumLFTR;
01730   Changed = true;
01731   return Cond;
01732 }
01733 
01734 //===----------------------------------------------------------------------===//
01735 //  SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
01736 //===----------------------------------------------------------------------===//
01737 
01738 /// If there's a single exit block, sink any loop-invariant values that
01739 /// were defined in the preheader but not used inside the loop into the
01740 /// exit block to reduce register pressure in the loop.
01741 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
01742   BasicBlock *ExitBlock = L->getExitBlock();
01743   if (!ExitBlock) return;
01744 
01745   BasicBlock *Preheader = L->getLoopPreheader();
01746   if (!Preheader) return;
01747 
01748   Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
01749   BasicBlock::iterator I = Preheader->getTerminator();
01750   while (I != Preheader->begin()) {
01751     --I;
01752     // New instructions were inserted at the end of the preheader.
01753     if (isa<PHINode>(I))
01754       break;
01755 
01756     // Don't move instructions which might have side effects, since the side
01757     // effects need to complete before instructions inside the loop.  Also don't
01758     // move instructions which might read memory, since the loop may modify
01759     // memory. Note that it's okay if the instruction might have undefined
01760     // behavior: LoopSimplify guarantees that the preheader dominates the exit
01761     // block.
01762     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
01763       continue;
01764 
01765     // Skip debug info intrinsics.
01766     if (isa<DbgInfoIntrinsic>(I))
01767       continue;
01768 
01769     // Skip landingpad instructions.
01770     if (isa<LandingPadInst>(I))
01771       continue;
01772 
01773     // Don't sink alloca: we never want to sink static alloca's out of the
01774     // entry block, and correctly sinking dynamic alloca's requires
01775     // checks for stacksave/stackrestore intrinsics.
01776     // FIXME: Refactor this check somehow?
01777     if (isa<AllocaInst>(I))
01778       continue;
01779 
01780     // Determine if there is a use in or before the loop (direct or
01781     // otherwise).
01782     bool UsedInLoop = false;
01783     for (Use &U : I->uses()) {
01784       Instruction *User = cast<Instruction>(U.getUser());
01785       BasicBlock *UseBB = User->getParent();
01786       if (PHINode *P = dyn_cast<PHINode>(User)) {
01787         unsigned i =
01788           PHINode::getIncomingValueNumForOperand(U.getOperandNo());
01789         UseBB = P->getIncomingBlock(i);
01790       }
01791       if (UseBB == Preheader || L->contains(UseBB)) {
01792         UsedInLoop = true;
01793         break;
01794       }
01795     }
01796 
01797     // If there is, the def must remain in the preheader.
01798     if (UsedInLoop)
01799       continue;
01800 
01801     // Otherwise, sink it to the exit block.
01802     Instruction *ToMove = I;
01803     bool Done = false;
01804 
01805     if (I != Preheader->begin()) {
01806       // Skip debug info intrinsics.
01807       do {
01808         --I;
01809       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
01810 
01811       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
01812         Done = true;
01813     } else {
01814       Done = true;
01815     }
01816 
01817     ToMove->moveBefore(InsertPt);
01818     if (Done) break;
01819     InsertPt = ToMove;
01820   }
01821 }
01822 
01823 //===----------------------------------------------------------------------===//
01824 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
01825 //===----------------------------------------------------------------------===//
01826 
01827 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
01828   if (skipOptnoneFunction(L))
01829     return false;
01830 
01831   // If LoopSimplify form is not available, stay out of trouble. Some notes:
01832   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
01833   //    canonicalization can be a pessimization without LSR to "clean up"
01834   //    afterwards.
01835   //  - We depend on having a preheader; in particular,
01836   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
01837   //    and we're in trouble if we can't find the induction variable even when
01838   //    we've manually inserted one.
01839   if (!L->isLoopSimplifyForm())
01840     return false;
01841 
01842   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
01843   SE = &getAnalysis<ScalarEvolution>();
01844   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01845   auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
01846   TLI = TLIP ? &TLIP->getTLI() : nullptr;
01847   auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
01848   TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
01849   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
01850 
01851   DeadInsts.clear();
01852   Changed = false;
01853 
01854   // If there are any floating-point recurrences, attempt to
01855   // transform them to use integer recurrences.
01856   RewriteNonIntegerIVs(L);
01857 
01858   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
01859 
01860   // Create a rewriter object which we'll use to transform the code with.
01861   SCEVExpander Rewriter(*SE, DL, "indvars");
01862 #ifndef NDEBUG
01863   Rewriter.setDebugType(DEBUG_TYPE);
01864 #endif
01865 
01866   // Eliminate redundant IV users.
01867   //
01868   // Simplification works best when run before other consumers of SCEV. We
01869   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
01870   // other expressions involving loop IVs have been evaluated. This helps SCEV
01871   // set no-wrap flags before normalizing sign/zero extension.
01872   Rewriter.disableCanonicalMode();
01873   SimplifyAndExtend(L, Rewriter, LPM);
01874 
01875   // Check to see if this loop has a computable loop-invariant execution count.
01876   // If so, this means that we can compute the final value of any expressions
01877   // that are recurrent in the loop, and substitute the exit values from the
01878   // loop into any instructions outside of the loop that use the final values of
01879   // the current expressions.
01880   //
01881   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
01882     RewriteLoopExitValues(L, Rewriter);
01883 
01884   // Eliminate redundant IV cycles.
01885   NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
01886 
01887   // If we have a trip count expression, rewrite the loop's exit condition
01888   // using it.  We can currently only handle loops with a single exit.
01889   if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) {
01890     PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
01891     if (IndVar) {
01892       // Check preconditions for proper SCEVExpander operation. SCEV does not
01893       // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
01894       // pass that uses the SCEVExpander must do it. This does not work well for
01895       // loop passes because SCEVExpander makes assumptions about all loops,
01896       // while LoopPassManager only forces the current loop to be simplified.
01897       //
01898       // FIXME: SCEV expansion has no way to bail out, so the caller must
01899       // explicitly check any assumptions made by SCEV. Brittle.
01900       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
01901       if (!AR || AR->getLoop()->getLoopPreheader())
01902         (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
01903                                         Rewriter);
01904     }
01905   }
01906   // Clear the rewriter cache, because values that are in the rewriter's cache
01907   // can be deleted in the loop below, causing the AssertingVH in the cache to
01908   // trigger.
01909   Rewriter.clear();
01910 
01911   // Now that we're done iterating through lists, clean up any instructions
01912   // which are now dead.
01913   while (!DeadInsts.empty())
01914     if (Instruction *Inst =
01915           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
01916       RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
01917 
01918   // The Rewriter may not be used from this point on.
01919 
01920   // Loop-invariant instructions in the preheader that aren't used in the
01921   // loop may be sunk below the loop to reduce register pressure.
01922   SinkUnusedInvariants(L);
01923 
01924   // Clean up dead instructions.
01925   Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
01926   // Check a post-condition.
01927   assert(L->isLCSSAForm(*DT) &&
01928          "Indvars did not leave the loop in lcssa form!");
01929 
01930   // Verify that LFTR, and any other change have not interfered with SCEV's
01931   // ability to compute trip count.
01932 #ifndef NDEBUG
01933   if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
01934     SE->forgetLoop(L);
01935     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
01936     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
01937         SE->getTypeSizeInBits(NewBECount->getType()))
01938       NewBECount = SE->getTruncateOrNoop(NewBECount,
01939                                          BackedgeTakenCount->getType());
01940     else
01941       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
01942                                                  NewBECount->getType());
01943     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
01944   }
01945 #endif
01946 
01947   return Changed;
01948 }