1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
13 //
14 // If the trip count of a loop is computable, this pass also makes the following
15 // changes:
16 //   1. The exit condition for the loop is canonicalized to compare the
17 //      induction value against the exit value.  This turns loops like:
18 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19 //   2. Any use outside of the loop of an expression derived from the indvar
20 //      is changed to compute the derived value outside of the loop, eliminating
21 //      the dependence on the exit value of the induction variable.  If the only
22 //      purpose of the loop is to compute the exit value of some derived
23 //      expression, this transformation will make the loop dead.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/None.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/iterator_range.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/LoopPass.h"
42 #include "llvm/Analysis/ScalarEvolution.h"
43 #include "llvm/Analysis/ScalarEvolutionExpander.h"
44 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
45 #include "llvm/Analysis/TargetLibraryInfo.h"
46 #include "llvm/Analysis/TargetTransformInfo.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/IR/BasicBlock.h"
50 #include "llvm/IR/Constant.h"
51 #include "llvm/IR/ConstantRange.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DerivedTypes.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/InstrTypes.h"
59 #include "llvm/IR/Instruction.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/Intrinsics.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/Operator.h"
65 #include "llvm/IR/PassManager.h"
66 #include "llvm/IR/PatternMatch.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/IR/Use.h"
69 #include "llvm/IR/User.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/IR/ValueHandle.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Compiler.h"
76 #include "llvm/Support/Debug.h"
77 #include "llvm/Support/ErrorHandling.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Transforms/Scalar.h"
81 #include "llvm/Transforms/Scalar/LoopPassManager.h"
82 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
83 #include "llvm/Transforms/Utils/LoopUtils.h"
84 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
85 #include <cassert>
86 #include <cstdint>
87 #include <utility>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "indvars"
92 
93 STATISTIC(NumWidened     , "Number of indvars widened");
94 STATISTIC(NumReplaced    , "Number of exit values replaced");
95 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
96 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
97 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
98 
99 // Trip count verification can be enabled by default under NDEBUG if we
100 // implement a strong expression equivalence checker in SCEV. Until then, we
101 // use the verify-indvars flag, which may assert in some cases.
102 static cl::opt<bool> VerifyIndvars(
103   "verify-indvars", cl::Hidden,
104   cl::desc("Verify the ScalarEvolution result after running indvars"));
105 
106 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
107 
108 static cl::opt<ReplaceExitVal> ReplaceExitValue(
109     "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
110     cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
111     cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
112                clEnumValN(OnlyCheapRepl, "cheap",
113                           "only replace exit value when the cost is cheap"),
114                clEnumValN(AlwaysRepl, "always",
115                           "always replace exit value whenever possible")));
116 
117 static cl::opt<bool> UsePostIncrementRanges(
118   "indvars-post-increment-ranges", cl::Hidden,
119   cl::desc("Use post increment control-dependent ranges in IndVarSimplify"),
120   cl::init(true));
121 
122 static cl::opt<bool>
123 DisableLFTR("disable-lftr", cl::Hidden, cl::init(false),
124             cl::desc("Disable Linear Function Test Replace optimization"));
125 
126 namespace {
127 
128 struct RewritePhi;
129 
130 class IndVarSimplify {
131   LoopInfo *LI;
132   ScalarEvolution *SE;
133   DominatorTree *DT;
134   const DataLayout &DL;
135   TargetLibraryInfo *TLI;
136   const TargetTransformInfo *TTI;
137 
138   SmallVector<WeakTrackingVH, 16> DeadInsts;
139 
140   bool isValidRewrite(Value *FromVal, Value *ToVal);
141 
142   bool handleFloatingPointIV(Loop *L, PHINode *PH);
143   bool rewriteNonIntegerIVs(Loop *L);
144 
145   bool simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
146 
147   bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
148   bool rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
149   bool rewriteFirstIterationLoopExitValues(Loop *L);
150   bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) const;
151 
152   bool linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
153                                  const SCEV *ExitCount,
154                                  PHINode *IndVar, SCEVExpander &Rewriter);
155 
156   bool sinkUnusedInvariants(Loop *L);
157 
158 public:
IndVarSimplify(LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,const DataLayout & DL,TargetLibraryInfo * TLI,TargetTransformInfo * TTI)159   IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
160                  const DataLayout &DL, TargetLibraryInfo *TLI,
161                  TargetTransformInfo *TTI)
162       : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
163 
164   bool run(Loop *L);
165 };
166 
167 } // end anonymous namespace
168 
169 /// Return true if the SCEV expansion generated by the rewriter can replace the
170 /// original value. SCEV guarantees that it produces the same value, but the way
171 /// it is produced may be illegal IR.  Ideally, this function will only be
172 /// called for verification.
isValidRewrite(Value * FromVal,Value * ToVal)173 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
174   // If an SCEV expression subsumed multiple pointers, its expansion could
175   // reassociate the GEP changing the base pointer. This is illegal because the
176   // final address produced by a GEP chain must be inbounds relative to its
177   // underlying object. Otherwise basic alias analysis, among other things,
178   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
179   // producing an expression involving multiple pointers. Until then, we must
180   // bail out here.
181   //
182   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
183   // because it understands lcssa phis while SCEV does not.
184   Value *FromPtr = FromVal;
185   Value *ToPtr = ToVal;
186   if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) {
187     FromPtr = GEP->getPointerOperand();
188   }
189   if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) {
190     ToPtr = GEP->getPointerOperand();
191   }
192   if (FromPtr != FromVal || ToPtr != ToVal) {
193     // Quickly check the common case
194     if (FromPtr == ToPtr)
195       return true;
196 
197     // SCEV may have rewritten an expression that produces the GEP's pointer
198     // operand. That's ok as long as the pointer operand has the same base
199     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
200     // base of a recurrence. This handles the case in which SCEV expansion
201     // converts a pointer type recurrence into a nonrecurrent pointer base
202     // indexed by an integer recurrence.
203 
204     // If the GEP base pointer is a vector of pointers, abort.
205     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
206       return false;
207 
208     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
209     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
210     if (FromBase == ToBase)
211       return true;
212 
213     LLVM_DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " << *FromBase
214                       << " != " << *ToBase << "\n");
215 
216     return false;
217   }
218   return true;
219 }
220 
221 /// Determine the insertion point for this user. By default, insert immediately
222 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
223 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
224 /// common dominator for the incoming blocks.
getInsertPointForUses(Instruction * User,Value * Def,DominatorTree * DT,LoopInfo * LI)225 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
226                                           DominatorTree *DT, LoopInfo *LI) {
227   PHINode *PHI = dyn_cast<PHINode>(User);
228   if (!PHI)
229     return User;
230 
231   Instruction *InsertPt = nullptr;
232   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
233     if (PHI->getIncomingValue(i) != Def)
234       continue;
235 
236     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
237     if (!InsertPt) {
238       InsertPt = InsertBB->getTerminator();
239       continue;
240     }
241     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
242     InsertPt = InsertBB->getTerminator();
243   }
244   assert(InsertPt && "Missing phi operand");
245 
246   auto *DefI = dyn_cast<Instruction>(Def);
247   if (!DefI)
248     return InsertPt;
249 
250   assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
251 
252   auto *L = LI->getLoopFor(DefI->getParent());
253   assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
254 
255   for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
256     if (LI->getLoopFor(DTN->getBlock()) == L)
257       return DTN->getBlock()->getTerminator();
258 
259   llvm_unreachable("DefI dominates InsertPt!");
260 }
261 
262 //===----------------------------------------------------------------------===//
263 // rewriteNonIntegerIVs and helpers. Prefer integer IVs.
264 //===----------------------------------------------------------------------===//
265 
266 /// Convert APF to an integer, if possible.
ConvertToSInt(const APFloat & APF,int64_t & IntVal)267 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
268   bool isExact = false;
269   // See if we can convert this to an int64_t
270   uint64_t UIntVal;
271   if (APF.convertToInteger(makeMutableArrayRef(UIntVal), 64, true,
272                            APFloat::rmTowardZero, &isExact) != APFloat::opOK ||
273       !isExact)
274     return false;
275   IntVal = UIntVal;
276   return true;
277 }
278 
279 /// If the loop has floating induction variable then insert corresponding
280 /// integer induction variable if possible.
281 /// For example,
282 /// for(double i = 0; i < 10000; ++i)
283 ///   bar(i)
284 /// is converted into
285 /// for(int i = 0; i < 10000; ++i)
286 ///   bar((double)i);
handleFloatingPointIV(Loop * L,PHINode * PN)287 bool IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
288   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
289   unsigned BackEdge     = IncomingEdge^1;
290 
291   // Check incoming value.
292   auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
293 
294   int64_t InitValue;
295   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
296     return false;
297 
298   // Check IV increment. Reject this PN if increment operation is not
299   // an add or increment value can not be represented by an integer.
300   auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
301   if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return false;
302 
303   // If this is not an add of the PHI with a constantfp, or if the constant fp
304   // is not an integer, bail out.
305   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
306   int64_t IncValue;
307   if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
308       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
309     return false;
310 
311   // Check Incr uses. One user is PN and the other user is an exit condition
312   // used by the conditional terminator.
313   Value::user_iterator IncrUse = Incr->user_begin();
314   Instruction *U1 = cast<Instruction>(*IncrUse++);
315   if (IncrUse == Incr->user_end()) return false;
316   Instruction *U2 = cast<Instruction>(*IncrUse++);
317   if (IncrUse != Incr->user_end()) return false;
318 
319   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
320   // only used by a branch, we can't transform it.
321   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
322   if (!Compare)
323     Compare = dyn_cast<FCmpInst>(U2);
324   if (!Compare || !Compare->hasOneUse() ||
325       !isa<BranchInst>(Compare->user_back()))
326     return false;
327 
328   BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
329 
330   // We need to verify that the branch actually controls the iteration count
331   // of the loop.  If not, the new IV can overflow and no one will notice.
332   // The branch block must be in the loop and one of the successors must be out
333   // of the loop.
334   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
335   if (!L->contains(TheBr->getParent()) ||
336       (L->contains(TheBr->getSuccessor(0)) &&
337        L->contains(TheBr->getSuccessor(1))))
338     return false;
339 
340   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
341   // transform it.
342   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
343   int64_t ExitValue;
344   if (ExitValueVal == nullptr ||
345       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
346     return false;
347 
348   // Find new predicate for integer comparison.
349   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
350   switch (Compare->getPredicate()) {
351   default: return false;  // Unknown comparison.
352   case CmpInst::FCMP_OEQ:
353   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
354   case CmpInst::FCMP_ONE:
355   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
356   case CmpInst::FCMP_OGT:
357   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
358   case CmpInst::FCMP_OGE:
359   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
360   case CmpInst::FCMP_OLT:
361   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
362   case CmpInst::FCMP_OLE:
363   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
364   }
365 
366   // We convert the floating point induction variable to a signed i32 value if
367   // we can.  This is only safe if the comparison will not overflow in a way
368   // that won't be trapped by the integer equivalent operations.  Check for this
369   // now.
370   // TODO: We could use i64 if it is native and the range requires it.
371 
372   // The start/stride/exit values must all fit in signed i32.
373   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
374     return false;
375 
376   // If not actually striding (add x, 0.0), avoid touching the code.
377   if (IncValue == 0)
378     return false;
379 
380   // Positive and negative strides have different safety conditions.
381   if (IncValue > 0) {
382     // If we have a positive stride, we require the init to be less than the
383     // exit value.
384     if (InitValue >= ExitValue)
385       return false;
386 
387     uint32_t Range = uint32_t(ExitValue-InitValue);
388     // Check for infinite loop, either:
389     // while (i <= Exit) or until (i > Exit)
390     if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
391       if (++Range == 0) return false;  // Range overflows.
392     }
393 
394     unsigned Leftover = Range % uint32_t(IncValue);
395 
396     // If this is an equality comparison, we require that the strided value
397     // exactly land on the exit value, otherwise the IV condition will wrap
398     // around and do things the fp IV wouldn't.
399     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
400         Leftover != 0)
401       return false;
402 
403     // If the stride would wrap around the i32 before exiting, we can't
404     // transform the IV.
405     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
406       return false;
407   } else {
408     // If we have a negative stride, we require the init to be greater than the
409     // exit value.
410     if (InitValue <= ExitValue)
411       return false;
412 
413     uint32_t Range = uint32_t(InitValue-ExitValue);
414     // Check for infinite loop, either:
415     // while (i >= Exit) or until (i < Exit)
416     if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
417       if (++Range == 0) return false;  // Range overflows.
418     }
419 
420     unsigned Leftover = Range % uint32_t(-IncValue);
421 
422     // If this is an equality comparison, we require that the strided value
423     // exactly land on the exit value, otherwise the IV condition will wrap
424     // around and do things the fp IV wouldn't.
425     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
426         Leftover != 0)
427       return false;
428 
429     // If the stride would wrap around the i32 before exiting, we can't
430     // transform the IV.
431     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
432       return false;
433   }
434 
435   IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
436 
437   // Insert new integer induction variable.
438   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
439   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
440                       PN->getIncomingBlock(IncomingEdge));
441 
442   Value *NewAdd =
443     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
444                               Incr->getName()+".int", Incr);
445   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
446 
447   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
448                                       ConstantInt::get(Int32Ty, ExitValue),
449                                       Compare->getName());
450 
451   // In the following deletions, PN may become dead and may be deleted.
452   // Use a WeakTrackingVH to observe whether this happens.
453   WeakTrackingVH WeakPH = PN;
454 
455   // Delete the old floating point exit comparison.  The branch starts using the
456   // new comparison.
457   NewCompare->takeName(Compare);
458   Compare->replaceAllUsesWith(NewCompare);
459   RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
460 
461   // Delete the old floating point increment.
462   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
463   RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
464 
465   // If the FP induction variable still has uses, this is because something else
466   // in the loop uses its value.  In order to canonicalize the induction
467   // variable, we chose to eliminate the IV and rewrite it in terms of an
468   // int->fp cast.
469   //
470   // We give preference to sitofp over uitofp because it is faster on most
471   // platforms.
472   if (WeakPH) {
473     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
474                                  &*PN->getParent()->getFirstInsertionPt());
475     PN->replaceAllUsesWith(Conv);
476     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
477   }
478   return true;
479 }
480 
rewriteNonIntegerIVs(Loop * L)481 bool IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
482   // First step.  Check to see if there are any floating-point recurrences.
483   // If there are, change them into integer recurrences, permitting analysis by
484   // the SCEV routines.
485   BasicBlock *Header = L->getHeader();
486 
487   SmallVector<WeakTrackingVH, 8> PHIs;
488   for (PHINode &PN : Header->phis())
489     PHIs.push_back(&PN);
490 
491   bool Changed = false;
492   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
493     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
494       Changed |= handleFloatingPointIV(L, PN);
495 
496   // If the loop previously had floating-point IV, ScalarEvolution
497   // may not have been able to compute a trip count. Now that we've done some
498   // re-writing, the trip count may be computable.
499   if (Changed)
500     SE->forgetLoop(L);
501   return Changed;
502 }
503 
504 namespace {
505 
506 // Collect information about PHI nodes which can be transformed in
507 // rewriteLoopExitValues.
508 struct RewritePhi {
509   PHINode *PN;
510 
511   // Ith incoming value.
512   unsigned Ith;
513 
514   // Exit value after expansion.
515   Value *Val;
516 
517   // High Cost when expansion.
518   bool HighCost;
519 
RewritePhi__anonc65a48c90211::RewritePhi520   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
521       : PN(P), Ith(I), Val(V), HighCost(H) {}
522 };
523 
524 } // end anonymous namespace
525 
526 //===----------------------------------------------------------------------===//
527 // rewriteLoopExitValues - Optimize IV users outside the loop.
528 // As a side effect, reduces the amount of IV processing within the loop.
529 //===----------------------------------------------------------------------===//
530 
hasHardUserWithinLoop(const Loop * L,const Instruction * I) const531 bool IndVarSimplify::hasHardUserWithinLoop(const Loop *L, const Instruction *I) const {
532   SmallPtrSet<const Instruction *, 8> Visited;
533   SmallVector<const Instruction *, 8> WorkList;
534   Visited.insert(I);
535   WorkList.push_back(I);
536   while (!WorkList.empty()) {
537     const Instruction *Curr = WorkList.pop_back_val();
538     // This use is outside the loop, nothing to do.
539     if (!L->contains(Curr))
540       continue;
541     // Do we assume it is a "hard" use which will not be eliminated easily?
542     if (Curr->mayHaveSideEffects())
543       return true;
544     // Otherwise, add all its users to worklist.
545     for (auto U : Curr->users()) {
546       auto *UI = cast<Instruction>(U);
547       if (Visited.insert(UI).second)
548         WorkList.push_back(UI);
549     }
550   }
551   return false;
552 }
553 
554 /// Check to see if this loop has a computable loop-invariant execution count.
555 /// If so, this means that we can compute the final value of any expressions
556 /// that are recurrent in the loop, and substitute the exit values from the loop
557 /// into any instructions outside of the loop that use the final values of the
558 /// current expressions.
559 ///
560 /// This is mostly redundant with the regular IndVarSimplify activities that
561 /// happen later, except that it's more powerful in some cases, because it's
562 /// able to brute-force evaluate arbitrary instructions as long as they have
563 /// constant operands at the beginning of the loop.
rewriteLoopExitValues(Loop * L,SCEVExpander & Rewriter)564 bool IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
565   // Check a pre-condition.
566   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
567          "Indvars did not preserve LCSSA!");
568 
569   SmallVector<BasicBlock*, 8> ExitBlocks;
570   L->getUniqueExitBlocks(ExitBlocks);
571 
572   SmallVector<RewritePhi, 8> RewritePhiSet;
573   // Find all values that are computed inside the loop, but used outside of it.
574   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
575   // the exit blocks of the loop to find them.
576   for (BasicBlock *ExitBB : ExitBlocks) {
577     // If there are no PHI nodes in this exit block, then no values defined
578     // inside the loop are used on this path, skip it.
579     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
580     if (!PN) continue;
581 
582     unsigned NumPreds = PN->getNumIncomingValues();
583 
584     // Iterate over all of the PHI nodes.
585     BasicBlock::iterator BBI = ExitBB->begin();
586     while ((PN = dyn_cast<PHINode>(BBI++))) {
587       if (PN->use_empty())
588         continue; // dead use, don't replace it
589 
590       if (!SE->isSCEVable(PN->getType()))
591         continue;
592 
593       // It's necessary to tell ScalarEvolution about this explicitly so that
594       // it can walk the def-use list and forget all SCEVs, as it may not be
595       // watching the PHI itself. Once the new exit value is in place, there
596       // may not be a def-use connection between the loop and every instruction
597       // which got a SCEVAddRecExpr for that loop.
598       SE->forgetValue(PN);
599 
600       // Iterate over all of the values in all the PHI nodes.
601       for (unsigned i = 0; i != NumPreds; ++i) {
602         // If the value being merged in is not integer or is not defined
603         // in the loop, skip it.
604         Value *InVal = PN->getIncomingValue(i);
605         if (!isa<Instruction>(InVal))
606           continue;
607 
608         // If this pred is for a subloop, not L itself, skip it.
609         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
610           continue; // The Block is in a subloop, skip it.
611 
612         // Check that InVal is defined in the loop.
613         Instruction *Inst = cast<Instruction>(InVal);
614         if (!L->contains(Inst))
615           continue;
616 
617         // Okay, this instruction has a user outside of the current loop
618         // and varies predictably *inside* the loop.  Evaluate the value it
619         // contains when the loop exits, if possible.
620         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
621         if (!SE->isLoopInvariant(ExitValue, L) ||
622             !isSafeToExpand(ExitValue, *SE))
623           continue;
624 
625         // Computing the value outside of the loop brings no benefit if it is
626         // definitely used inside the loop in a way which can not be optimized
627         // away.
628         if (!isa<SCEVConstant>(ExitValue) && hasHardUserWithinLoop(L, Inst))
629           continue;
630 
631         bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
632         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
633 
634         LLVM_DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
635                           << '\n'
636                           << "  LoopVal = " << *Inst << "\n");
637 
638         if (!isValidRewrite(Inst, ExitVal)) {
639           DeadInsts.push_back(ExitVal);
640           continue;
641         }
642 
643 #ifndef NDEBUG
644         // If we reuse an instruction from a loop which is neither L nor one of
645         // its containing loops, we end up breaking LCSSA form for this loop by
646         // creating a new use of its instruction.
647         if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
648           if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
649             if (EVL != L)
650               assert(EVL->contains(L) && "LCSSA breach detected!");
651 #endif
652 
653         // Collect all the candidate PHINodes to be rewritten.
654         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
655       }
656     }
657   }
658 
659   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
660 
661   bool Changed = false;
662   // Transformation.
663   for (const RewritePhi &Phi : RewritePhiSet) {
664     PHINode *PN = Phi.PN;
665     Value *ExitVal = Phi.Val;
666 
667     // Only do the rewrite when the ExitValue can be expanded cheaply.
668     // If LoopCanBeDel is true, rewrite exit value aggressively.
669     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
670       DeadInsts.push_back(ExitVal);
671       continue;
672     }
673 
674     Changed = true;
675     ++NumReplaced;
676     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
677     PN->setIncomingValue(Phi.Ith, ExitVal);
678 
679     // If this instruction is dead now, delete it. Don't do it now to avoid
680     // invalidating iterators.
681     if (isInstructionTriviallyDead(Inst, TLI))
682       DeadInsts.push_back(Inst);
683 
684     // Replace PN with ExitVal if that is legal and does not break LCSSA.
685     if (PN->getNumIncomingValues() == 1 &&
686         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
687       PN->replaceAllUsesWith(ExitVal);
688       PN->eraseFromParent();
689     }
690   }
691 
692   // The insertion point instruction may have been deleted; clear it out
693   // so that the rewriter doesn't trip over it later.
694   Rewriter.clearInsertPoint();
695   return Changed;
696 }
697 
698 //===---------------------------------------------------------------------===//
699 // rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
700 // they will exit at the first iteration.
701 //===---------------------------------------------------------------------===//
702 
703 /// Check to see if this loop has loop invariant conditions which lead to loop
704 /// exits. If so, we know that if the exit path is taken, it is at the first
705 /// loop iteration. This lets us predict exit values of PHI nodes that live in
706 /// loop header.
rewriteFirstIterationLoopExitValues(Loop * L)707 bool IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
708   // Verify the input to the pass is already in LCSSA form.
709   assert(L->isLCSSAForm(*DT));
710 
711   SmallVector<BasicBlock *, 8> ExitBlocks;
712   L->getUniqueExitBlocks(ExitBlocks);
713   auto *LoopHeader = L->getHeader();
714   assert(LoopHeader && "Invalid loop");
715 
716   bool MadeAnyChanges = false;
717   for (auto *ExitBB : ExitBlocks) {
718     // If there are no more PHI nodes in this exit block, then no more
719     // values defined inside the loop are used on this path.
720     for (PHINode &PN : ExitBB->phis()) {
721       for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();
722            IncomingValIdx != E; ++IncomingValIdx) {
723         auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);
724 
725         // We currently only support loop exits from loop header. If the
726         // incoming block is not loop header, we need to recursively check
727         // all conditions starting from loop header are loop invariants.
728         // Additional support might be added in the future.
729         if (IncomingBB != LoopHeader)
730           continue;
731 
732         // Get condition that leads to the exit path.
733         auto *TermInst = IncomingBB->getTerminator();
734 
735         Value *Cond = nullptr;
736         if (auto *BI = dyn_cast<BranchInst>(TermInst)) {
737           // Must be a conditional branch, otherwise the block
738           // should not be in the loop.
739           Cond = BI->getCondition();
740         } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
741           Cond = SI->getCondition();
742         else
743           continue;
744 
745         if (!L->isLoopInvariant(Cond))
746           continue;
747 
748         auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));
749 
750         // Only deal with PHIs.
751         if (!ExitVal)
752           continue;
753 
754         // If ExitVal is a PHI on the loop header, then we know its
755         // value along this exit because the exit can only be taken
756         // on the first iteration.
757         auto *LoopPreheader = L->getLoopPreheader();
758         assert(LoopPreheader && "Invalid loop");
759         int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
760         if (PreheaderIdx != -1) {
761           assert(ExitVal->getParent() == LoopHeader &&
762                  "ExitVal must be in loop header");
763           MadeAnyChanges = true;
764           PN.setIncomingValue(IncomingValIdx,
765                               ExitVal->getIncomingValue(PreheaderIdx));
766         }
767       }
768     }
769   }
770   return MadeAnyChanges;
771 }
772 
773 /// Check whether it is possible to delete the loop after rewriting exit
774 /// value. If it is possible, ignore ReplaceExitValue and do rewriting
775 /// aggressively.
canLoopBeDeleted(Loop * L,SmallVector<RewritePhi,8> & RewritePhiSet)776 bool IndVarSimplify::canLoopBeDeleted(
777     Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
778   BasicBlock *Preheader = L->getLoopPreheader();
779   // If there is no preheader, the loop will not be deleted.
780   if (!Preheader)
781     return false;
782 
783   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
784   // We obviate multiple ExitingBlocks case for simplicity.
785   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
786   // after exit value rewriting, we can enhance the logic here.
787   SmallVector<BasicBlock *, 4> ExitingBlocks;
788   L->getExitingBlocks(ExitingBlocks);
789   SmallVector<BasicBlock *, 8> ExitBlocks;
790   L->getUniqueExitBlocks(ExitBlocks);
791   if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
792     return false;
793 
794   BasicBlock *ExitBlock = ExitBlocks[0];
795   BasicBlock::iterator BI = ExitBlock->begin();
796   while (PHINode *P = dyn_cast<PHINode>(BI)) {
797     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
798 
799     // If the Incoming value of P is found in RewritePhiSet, we know it
800     // could be rewritten to use a loop invariant value in transformation
801     // phase later. Skip it in the loop invariant check below.
802     bool found = false;
803     for (const RewritePhi &Phi : RewritePhiSet) {
804       unsigned i = Phi.Ith;
805       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
806         found = true;
807         break;
808       }
809     }
810 
811     Instruction *I;
812     if (!found && (I = dyn_cast<Instruction>(Incoming)))
813       if (!L->hasLoopInvariantOperands(I))
814         return false;
815 
816     ++BI;
817   }
818 
819   for (auto *BB : L->blocks())
820     if (llvm::any_of(*BB, [](Instruction &I) {
821           return I.mayHaveSideEffects();
822         }))
823       return false;
824 
825   return true;
826 }
827 
828 //===----------------------------------------------------------------------===//
829 //  IV Widening - Extend the width of an IV to cover its widest uses.
830 //===----------------------------------------------------------------------===//
831 
832 namespace {
833 
834 // Collect information about induction variables that are used by sign/zero
835 // extend operations. This information is recorded by CollectExtend and provides
836 // the input to WidenIV.
837 struct WideIVInfo {
838   PHINode *NarrowIV = nullptr;
839 
840   // Widest integer type created [sz]ext
841   Type *WidestNativeType = nullptr;
842 
843   // Was a sext user seen before a zext?
844   bool IsSigned = false;
845 };
846 
847 } // end anonymous namespace
848 
849 /// Update information about the induction variable that is extended by this
850 /// sign or zero extend operation. This is used to determine the final width of
851 /// the IV before actually widening it.
visitIVCast(CastInst * Cast,WideIVInfo & WI,ScalarEvolution * SE,const TargetTransformInfo * TTI)852 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
853                         const TargetTransformInfo *TTI) {
854   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
855   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
856     return;
857 
858   Type *Ty = Cast->getType();
859   uint64_t Width = SE->getTypeSizeInBits(Ty);
860   if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
861     return;
862 
863   // Check that `Cast` actually extends the induction variable (we rely on this
864   // later).  This takes care of cases where `Cast` is extending a truncation of
865   // the narrow induction variable, and thus can end up being narrower than the
866   // "narrow" induction variable.
867   uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());
868   if (NarrowIVWidth >= Width)
869     return;
870 
871   // Cast is either an sext or zext up to this point.
872   // We should not widen an indvar if arithmetics on the wider indvar are more
873   // expensive than those on the narrower indvar. We check only the cost of ADD
874   // because at least an ADD is required to increment the induction variable. We
875   // could compute more comprehensively the cost of all instructions on the
876   // induction variable when necessary.
877   if (TTI &&
878       TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
879           TTI->getArithmeticInstrCost(Instruction::Add,
880                                       Cast->getOperand(0)->getType())) {
881     return;
882   }
883 
884   if (!WI.WidestNativeType) {
885     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
886     WI.IsSigned = IsSigned;
887     return;
888   }
889 
890   // We extend the IV to satisfy the sign of its first user, arbitrarily.
891   if (WI.IsSigned != IsSigned)
892     return;
893 
894   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
895     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
896 }
897 
898 namespace {
899 
900 /// Record a link in the Narrow IV def-use chain along with the WideIV that
901 /// computes the same value as the Narrow IV def.  This avoids caching Use*
902 /// pointers.
903 struct NarrowIVDefUse {
904   Instruction *NarrowDef = nullptr;
905   Instruction *NarrowUse = nullptr;
906   Instruction *WideDef = nullptr;
907 
908   // True if the narrow def is never negative.  Tracking this information lets
909   // us use a sign extension instead of a zero extension or vice versa, when
910   // profitable and legal.
911   bool NeverNegative = false;
912 
NarrowIVDefUse__anonc65a48c90511::NarrowIVDefUse913   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
914                  bool NeverNegative)
915       : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
916         NeverNegative(NeverNegative) {}
917 };
918 
919 /// The goal of this transform is to remove sign and zero extends without
920 /// creating any new induction variables. To do this, it creates a new phi of
921 /// the wider type and redirects all users, either removing extends or inserting
922 /// truncs whenever we stop propagating the type.
923 class WidenIV {
924   // Parameters
925   PHINode *OrigPhi;
926   Type *WideType;
927 
928   // Context
929   LoopInfo        *LI;
930   Loop            *L;
931   ScalarEvolution *SE;
932   DominatorTree   *DT;
933 
934   // Does the module have any calls to the llvm.experimental.guard intrinsic
935   // at all? If not we can avoid scanning instructions looking for guards.
936   bool HasGuards;
937 
938   // Result
939   PHINode *WidePhi = nullptr;
940   Instruction *WideInc = nullptr;
941   const SCEV *WideIncExpr = nullptr;
942   SmallVectorImpl<WeakTrackingVH> &DeadInsts;
943 
944   SmallPtrSet<Instruction *,16> Widened;
945   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
946 
947   enum ExtendKind { ZeroExtended, SignExtended, Unknown };
948 
949   // A map tracking the kind of extension used to widen each narrow IV
950   // and narrow IV user.
951   // Key: pointer to a narrow IV or IV user.
952   // Value: the kind of extension used to widen this Instruction.
953   DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
954 
955   using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
956 
957   // A map with control-dependent ranges for post increment IV uses. The key is
958   // a pair of IV def and a use of this def denoting the context. The value is
959   // a ConstantRange representing possible values of the def at the given
960   // context.
961   DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
962 
getPostIncRangeInfo(Value * Def,Instruction * UseI)963   Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
964                                               Instruction *UseI) {
965     DefUserPair Key(Def, UseI);
966     auto It = PostIncRangeInfos.find(Key);
967     return It == PostIncRangeInfos.end()
968                ? Optional<ConstantRange>(None)
969                : Optional<ConstantRange>(It->second);
970   }
971 
972   void calculatePostIncRanges(PHINode *OrigPhi);
973   void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
974 
updatePostIncRangeInfo(Value * Def,Instruction * UseI,ConstantRange R)975   void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
976     DefUserPair Key(Def, UseI);
977     auto It = PostIncRangeInfos.find(Key);
978     if (It == PostIncRangeInfos.end())
979       PostIncRangeInfos.insert({Key, R});
980     else
981       It->second = R.intersectWith(It->second);
982   }
983 
984 public:
WidenIV(const WideIVInfo & WI,LoopInfo * LInfo,ScalarEvolution * SEv,DominatorTree * DTree,SmallVectorImpl<WeakTrackingVH> & DI,bool HasGuards)985   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
986           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
987           bool HasGuards)
988       : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
989         L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
990         HasGuards(HasGuards), DeadInsts(DI) {
991     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
992     ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
993   }
994 
995   PHINode *createWideIV(SCEVExpander &Rewriter);
996 
997 protected:
998   Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
999                           Instruction *Use);
1000 
1001   Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1002   Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1003                                      const SCEVAddRecExpr *WideAR);
1004   Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1005 
1006   ExtendKind getExtendKind(Instruction *I);
1007 
1008   using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1009 
1010   WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1011 
1012   WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1013 
1014   const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1015                               unsigned OpCode) const;
1016 
1017   Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
1018 
1019   bool widenLoopCompare(NarrowIVDefUse DU);
1020   bool widenWithVariantLoadUse(NarrowIVDefUse DU);
1021   void widenWithVariantLoadUseCodegen(NarrowIVDefUse DU);
1022 
1023   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1024 };
1025 
1026 } // end anonymous namespace
1027 
createExtendInst(Value * NarrowOper,Type * WideType,bool IsSigned,Instruction * Use)1028 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1029                                  bool IsSigned, Instruction *Use) {
1030   // Set the debug location and conservative insertion point.
1031   IRBuilder<> Builder(Use);
1032   // Hoist the insertion point into loop preheaders as far as possible.
1033   for (const Loop *L = LI->getLoopFor(Use->getParent());
1034        L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
1035        L = L->getParentLoop())
1036     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1037 
1038   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1039                     Builder.CreateZExt(NarrowOper, WideType);
1040 }
1041 
1042 /// Instantiate a wide operation to replace a narrow operation. This only needs
1043 /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1044 /// 0 for any operation we decide not to clone.
cloneIVUser(NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1045 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1046                                   const SCEVAddRecExpr *WideAR) {
1047   unsigned Opcode = DU.NarrowUse->getOpcode();
1048   switch (Opcode) {
1049   default:
1050     return nullptr;
1051   case Instruction::Add:
1052   case Instruction::Mul:
1053   case Instruction::UDiv:
1054   case Instruction::Sub:
1055     return cloneArithmeticIVUser(DU, WideAR);
1056 
1057   case Instruction::And:
1058   case Instruction::Or:
1059   case Instruction::Xor:
1060   case Instruction::Shl:
1061   case Instruction::LShr:
1062   case Instruction::AShr:
1063     return cloneBitwiseIVUser(DU);
1064   }
1065 }
1066 
cloneBitwiseIVUser(NarrowIVDefUse DU)1067 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1068   Instruction *NarrowUse = DU.NarrowUse;
1069   Instruction *NarrowDef = DU.NarrowDef;
1070   Instruction *WideDef = DU.WideDef;
1071 
1072   LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1073 
1074   // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1075   // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1076   // invariant and will be folded or hoisted. If it actually comes from a
1077   // widened IV, it should be removed during a future call to widenIVUse.
1078   bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1079   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1080                    ? WideDef
1081                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1082                                       IsSigned, NarrowUse);
1083   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1084                    ? WideDef
1085                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1086                                       IsSigned, NarrowUse);
1087 
1088   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1089   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1090                                         NarrowBO->getName());
1091   IRBuilder<> Builder(NarrowUse);
1092   Builder.Insert(WideBO);
1093   WideBO->copyIRFlags(NarrowBO);
1094   return WideBO;
1095 }
1096 
cloneArithmeticIVUser(NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1097 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1098                                             const SCEVAddRecExpr *WideAR) {
1099   Instruction *NarrowUse = DU.NarrowUse;
1100   Instruction *NarrowDef = DU.NarrowDef;
1101   Instruction *WideDef = DU.WideDef;
1102 
1103   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1104 
1105   unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1106 
1107   // We're trying to find X such that
1108   //
1109   //  Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1110   //
1111   // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1112   // and check using SCEV if any of them are correct.
1113 
1114   // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1115   // correct solution to X.
1116   auto GuessNonIVOperand = [&](bool SignExt) {
1117     const SCEV *WideLHS;
1118     const SCEV *WideRHS;
1119 
1120     auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1121       if (SignExt)
1122         return SE->getSignExtendExpr(S, Ty);
1123       return SE->getZeroExtendExpr(S, Ty);
1124     };
1125 
1126     if (IVOpIdx == 0) {
1127       WideLHS = SE->getSCEV(WideDef);
1128       const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1129       WideRHS = GetExtend(NarrowRHS, WideType);
1130     } else {
1131       const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1132       WideLHS = GetExtend(NarrowLHS, WideType);
1133       WideRHS = SE->getSCEV(WideDef);
1134     }
1135 
1136     // WideUse is "WideDef `op.wide` X" as described in the comment.
1137     const SCEV *WideUse = nullptr;
1138 
1139     switch (NarrowUse->getOpcode()) {
1140     default:
1141       llvm_unreachable("No other possibility!");
1142 
1143     case Instruction::Add:
1144       WideUse = SE->getAddExpr(WideLHS, WideRHS);
1145       break;
1146 
1147     case Instruction::Mul:
1148       WideUse = SE->getMulExpr(WideLHS, WideRHS);
1149       break;
1150 
1151     case Instruction::UDiv:
1152       WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1153       break;
1154 
1155     case Instruction::Sub:
1156       WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1157       break;
1158     }
1159 
1160     return WideUse == WideAR;
1161   };
1162 
1163   bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1164   if (!GuessNonIVOperand(SignExtend)) {
1165     SignExtend = !SignExtend;
1166     if (!GuessNonIVOperand(SignExtend))
1167       return nullptr;
1168   }
1169 
1170   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1171                    ? WideDef
1172                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1173                                       SignExtend, NarrowUse);
1174   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1175                    ? WideDef
1176                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1177                                       SignExtend, NarrowUse);
1178 
1179   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1180   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1181                                         NarrowBO->getName());
1182 
1183   IRBuilder<> Builder(NarrowUse);
1184   Builder.Insert(WideBO);
1185   WideBO->copyIRFlags(NarrowBO);
1186   return WideBO;
1187 }
1188 
getExtendKind(Instruction * I)1189 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1190   auto It = ExtendKindMap.find(I);
1191   assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1192   return It->second;
1193 }
1194 
getSCEVByOpCode(const SCEV * LHS,const SCEV * RHS,unsigned OpCode) const1195 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1196                                      unsigned OpCode) const {
1197   if (OpCode == Instruction::Add)
1198     return SE->getAddExpr(LHS, RHS);
1199   if (OpCode == Instruction::Sub)
1200     return SE->getMinusSCEV(LHS, RHS);
1201   if (OpCode == Instruction::Mul)
1202     return SE->getMulExpr(LHS, RHS);
1203 
1204   llvm_unreachable("Unsupported opcode.");
1205 }
1206 
1207 /// No-wrap operations can transfer sign extension of their result to their
1208 /// operands. Generate the SCEV value for the widened operation without
1209 /// actually modifying the IR yet. If the expression after extending the
1210 /// operands is an AddRec for this loop, return the AddRec and the kind of
1211 /// extension used.
getExtendedOperandRecurrence(NarrowIVDefUse DU)1212 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1213   // Handle the common case of add<nsw/nuw>
1214   const unsigned OpCode = DU.NarrowUse->getOpcode();
1215   // Only Add/Sub/Mul instructions supported yet.
1216   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1217       OpCode != Instruction::Mul)
1218     return {nullptr, Unknown};
1219 
1220   // One operand (NarrowDef) has already been extended to WideDef. Now determine
1221   // if extending the other will lead to a recurrence.
1222   const unsigned ExtendOperIdx =
1223       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1224   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1225 
1226   const SCEV *ExtendOperExpr = nullptr;
1227   const OverflowingBinaryOperator *OBO =
1228     cast<OverflowingBinaryOperator>(DU.NarrowUse);
1229   ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1230   if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
1231     ExtendOperExpr = SE->getSignExtendExpr(
1232       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1233   else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
1234     ExtendOperExpr = SE->getZeroExtendExpr(
1235       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1236   else
1237     return {nullptr, Unknown};
1238 
1239   // When creating this SCEV expr, don't apply the current operations NSW or NUW
1240   // flags. This instruction may be guarded by control flow that the no-wrap
1241   // behavior depends on. Non-control-equivalent instructions can be mapped to
1242   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1243   // semantics to those operations.
1244   const SCEV *lhs = SE->getSCEV(DU.WideDef);
1245   const SCEV *rhs = ExtendOperExpr;
1246 
1247   // Let's swap operands to the initial order for the case of non-commutative
1248   // operations, like SUB. See PR21014.
1249   if (ExtendOperIdx == 0)
1250     std::swap(lhs, rhs);
1251   const SCEVAddRecExpr *AddRec =
1252       dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1253 
1254   if (!AddRec || AddRec->getLoop() != L)
1255     return {nullptr, Unknown};
1256 
1257   return {AddRec, ExtKind};
1258 }
1259 
1260 /// Is this instruction potentially interesting for further simplification after
1261 /// widening it's type? In other words, can the extend be safely hoisted out of
1262 /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1263 /// so, return the extended recurrence and the kind of extension used. Otherwise
1264 /// return {nullptr, Unknown}.
getWideRecurrence(NarrowIVDefUse DU)1265 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1266   if (!SE->isSCEVable(DU.NarrowUse->getType()))
1267     return {nullptr, Unknown};
1268 
1269   const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1270   if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1271       SE->getTypeSizeInBits(WideType)) {
1272     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1273     // index. So don't follow this use.
1274     return {nullptr, Unknown};
1275   }
1276 
1277   const SCEV *WideExpr;
1278   ExtendKind ExtKind;
1279   if (DU.NeverNegative) {
1280     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1281     if (isa<SCEVAddRecExpr>(WideExpr))
1282       ExtKind = SignExtended;
1283     else {
1284       WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1285       ExtKind = ZeroExtended;
1286     }
1287   } else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1288     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1289     ExtKind = SignExtended;
1290   } else {
1291     WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1292     ExtKind = ZeroExtended;
1293   }
1294   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1295   if (!AddRec || AddRec->getLoop() != L)
1296     return {nullptr, Unknown};
1297   return {AddRec, ExtKind};
1298 }
1299 
1300 /// This IV user cannot be widen. Replace this use of the original narrow IV
1301 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
truncateIVUse(NarrowIVDefUse DU,DominatorTree * DT,LoopInfo * LI)1302 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI) {
1303   LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1304                     << *DU.NarrowUse << "\n");
1305   IRBuilder<> Builder(
1306       getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1307   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1308   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1309 }
1310 
1311 /// If the narrow use is a compare instruction, then widen the compare
1312 //  (and possibly the other operand).  The extend operation is hoisted into the
1313 // loop preheader as far as possible.
widenLoopCompare(NarrowIVDefUse DU)1314 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1315   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1316   if (!Cmp)
1317     return false;
1318 
1319   // We can legally widen the comparison in the following two cases:
1320   //
1321   //  - The signedness of the IV extension and comparison match
1322   //
1323   //  - The narrow IV is always positive (and thus its sign extension is equal
1324   //    to its zero extension).  For instance, let's say we're zero extending
1325   //    %narrow for the following use
1326   //
1327   //      icmp slt i32 %narrow, %val   ... (A)
1328   //
1329   //    and %narrow is always positive.  Then
1330   //
1331   //      (A) == icmp slt i32 sext(%narrow), sext(%val)
1332   //          == icmp slt i32 zext(%narrow), sext(%val)
1333   bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1334   if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1335     return false;
1336 
1337   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1338   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1339   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1340   assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1341 
1342   // Widen the compare instruction.
1343   IRBuilder<> Builder(
1344       getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1345   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1346 
1347   // Widen the other operand of the compare, if necessary.
1348   if (CastWidth < IVWidth) {
1349     Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1350     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1351   }
1352   return true;
1353 }
1354 
1355 /// If the narrow use is an instruction whose two operands are the defining
1356 /// instruction of DU and a load instruction, then we have the following:
1357 /// if the load is hoisted outside the loop, then we do not reach this function
1358 /// as scalar evolution analysis works fine in widenIVUse with variables
1359 /// hoisted outside the loop and efficient code is subsequently generated by
1360 /// not emitting truncate instructions. But when the load is not hoisted
1361 /// (whether due to limitation in alias analysis or due to a true legality),
1362 /// then scalar evolution can not proceed with loop variant values and
1363 /// inefficient code is generated. This function handles the non-hoisted load
1364 /// special case by making the optimization generate the same type of code for
1365 /// hoisted and non-hoisted load (widen use and eliminate sign extend
1366 /// instruction). This special case is important especially when the induction
1367 /// variables are affecting addressing mode in code generation.
widenWithVariantLoadUse(NarrowIVDefUse DU)1368 bool WidenIV::widenWithVariantLoadUse(NarrowIVDefUse DU) {
1369   Instruction *NarrowUse = DU.NarrowUse;
1370   Instruction *NarrowDef = DU.NarrowDef;
1371   Instruction *WideDef = DU.WideDef;
1372 
1373   // Handle the common case of add<nsw/nuw>
1374   const unsigned OpCode = NarrowUse->getOpcode();
1375   // Only Add/Sub/Mul instructions are supported.
1376   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1377       OpCode != Instruction::Mul)
1378     return false;
1379 
1380   // The operand that is not defined by NarrowDef of DU. Let's call it the
1381   // other operand.
1382   unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == NarrowDef ? 1 : 0;
1383   assert(DU.NarrowUse->getOperand(1 - ExtendOperIdx) == DU.NarrowDef &&
1384          "bad DU");
1385 
1386   const SCEV *ExtendOperExpr = nullptr;
1387   const OverflowingBinaryOperator *OBO =
1388     cast<OverflowingBinaryOperator>(NarrowUse);
1389   ExtendKind ExtKind = getExtendKind(NarrowDef);
1390   if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
1391     ExtendOperExpr = SE->getSignExtendExpr(
1392       SE->getSCEV(NarrowUse->getOperand(ExtendOperIdx)), WideType);
1393   else if (ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
1394     ExtendOperExpr = SE->getZeroExtendExpr(
1395       SE->getSCEV(NarrowUse->getOperand(ExtendOperIdx)), WideType);
1396   else
1397     return false;
1398 
1399   // We are interested in the other operand being a load instruction.
1400   // But, we should look into relaxing this restriction later on.
1401   auto *I = dyn_cast<Instruction>(NarrowUse->getOperand(ExtendOperIdx));
1402   if (I && I->getOpcode() != Instruction::Load)
1403     return false;
1404 
1405   // Verifying that Defining operand is an AddRec
1406   const SCEV *Op1 = SE->getSCEV(WideDef);
1407   const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1408   if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1409     return false;
1410   // Verifying that other operand is an Extend.
1411   if (ExtKind == SignExtended) {
1412     if (!isa<SCEVSignExtendExpr>(ExtendOperExpr))
1413       return false;
1414   } else {
1415     if (!isa<SCEVZeroExtendExpr>(ExtendOperExpr))
1416       return false;
1417   }
1418 
1419   if (ExtKind == SignExtended) {
1420     for (Use &U : NarrowUse->uses()) {
1421       SExtInst *User = dyn_cast<SExtInst>(U.getUser());
1422       if (!User || User->getType() != WideType)
1423         return false;
1424     }
1425   } else { // ExtKind == ZeroExtended
1426     for (Use &U : NarrowUse->uses()) {
1427       ZExtInst *User = dyn_cast<ZExtInst>(U.getUser());
1428       if (!User || User->getType() != WideType)
1429         return false;
1430     }
1431   }
1432 
1433   return true;
1434 }
1435 
1436 /// Special Case for widening with variant Loads (see
1437 /// WidenIV::widenWithVariantLoadUse). This is the code generation part.
widenWithVariantLoadUseCodegen(NarrowIVDefUse DU)1438 void WidenIV::widenWithVariantLoadUseCodegen(NarrowIVDefUse DU) {
1439   Instruction *NarrowUse = DU.NarrowUse;
1440   Instruction *NarrowDef = DU.NarrowDef;
1441   Instruction *WideDef = DU.WideDef;
1442 
1443   ExtendKind ExtKind = getExtendKind(NarrowDef);
1444 
1445   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1446 
1447   // Generating a widening use instruction.
1448   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1449                    ? WideDef
1450                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1451                                       ExtKind, NarrowUse);
1452   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1453                    ? WideDef
1454                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1455                                       ExtKind, NarrowUse);
1456 
1457   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1458   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1459                                         NarrowBO->getName());
1460   IRBuilder<> Builder(NarrowUse);
1461   Builder.Insert(WideBO);
1462   WideBO->copyIRFlags(NarrowBO);
1463 
1464   if (ExtKind == SignExtended)
1465     ExtendKindMap[NarrowUse] = SignExtended;
1466   else
1467     ExtendKindMap[NarrowUse] = ZeroExtended;
1468 
1469   // Update the Use.
1470   if (ExtKind == SignExtended) {
1471     for (Use &U : NarrowUse->uses()) {
1472       SExtInst *User = dyn_cast<SExtInst>(U.getUser());
1473       if (User && User->getType() == WideType) {
1474         LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1475                           << *WideBO << "\n");
1476         ++NumElimExt;
1477         User->replaceAllUsesWith(WideBO);
1478         DeadInsts.emplace_back(User);
1479       }
1480     }
1481   } else { // ExtKind == ZeroExtended
1482     for (Use &U : NarrowUse->uses()) {
1483       ZExtInst *User = dyn_cast<ZExtInst>(U.getUser());
1484       if (User && User->getType() == WideType) {
1485         LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1486                           << *WideBO << "\n");
1487         ++NumElimExt;
1488         User->replaceAllUsesWith(WideBO);
1489         DeadInsts.emplace_back(User);
1490       }
1491     }
1492   }
1493 }
1494 
1495 /// Determine whether an individual user of the narrow IV can be widened. If so,
1496 /// return the wide clone of the user.
widenIVUse(NarrowIVDefUse DU,SCEVExpander & Rewriter)1497 Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1498   assert(ExtendKindMap.count(DU.NarrowDef) &&
1499          "Should already know the kind of extension used to widen NarrowDef");
1500 
1501   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1502   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1503     if (LI->getLoopFor(UsePhi->getParent()) != L) {
1504       // For LCSSA phis, sink the truncate outside the loop.
1505       // After SimplifyCFG most loop exit targets have a single predecessor.
1506       // Otherwise fall back to a truncate within the loop.
1507       if (UsePhi->getNumOperands() != 1)
1508         truncateIVUse(DU, DT, LI);
1509       else {
1510         // Widening the PHI requires us to insert a trunc.  The logical place
1511         // for this trunc is in the same BB as the PHI.  This is not possible if
1512         // the BB is terminated by a catchswitch.
1513         if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1514           return nullptr;
1515 
1516         PHINode *WidePhi =
1517           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1518                           UsePhi);
1519         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1520         IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1521         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1522         UsePhi->replaceAllUsesWith(Trunc);
1523         DeadInsts.emplace_back(UsePhi);
1524         LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1525                           << *WidePhi << "\n");
1526       }
1527       return nullptr;
1528     }
1529   }
1530 
1531   // This narrow use can be widened by a sext if it's non-negative or its narrow
1532   // def was widended by a sext. Same for zext.
1533   auto canWidenBySExt = [&]() {
1534     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1535   };
1536   auto canWidenByZExt = [&]() {
1537     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1538   };
1539 
1540   // Our raison d'etre! Eliminate sign and zero extension.
1541   if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1542       (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1543     Value *NewDef = DU.WideDef;
1544     if (DU.NarrowUse->getType() != WideType) {
1545       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1546       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1547       if (CastWidth < IVWidth) {
1548         // The cast isn't as wide as the IV, so insert a Trunc.
1549         IRBuilder<> Builder(DU.NarrowUse);
1550         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1551       }
1552       else {
1553         // A wider extend was hidden behind a narrower one. This may induce
1554         // another round of IV widening in which the intermediate IV becomes
1555         // dead. It should be very rare.
1556         LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1557                           << " not wide enough to subsume " << *DU.NarrowUse
1558                           << "\n");
1559         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1560         NewDef = DU.NarrowUse;
1561       }
1562     }
1563     if (NewDef != DU.NarrowUse) {
1564       LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1565                         << " replaced by " << *DU.WideDef << "\n");
1566       ++NumElimExt;
1567       DU.NarrowUse->replaceAllUsesWith(NewDef);
1568       DeadInsts.emplace_back(DU.NarrowUse);
1569     }
1570     // Now that the extend is gone, we want to expose it's uses for potential
1571     // further simplification. We don't need to directly inform SimplifyIVUsers
1572     // of the new users, because their parent IV will be processed later as a
1573     // new loop phi. If we preserved IVUsers analysis, we would also want to
1574     // push the uses of WideDef here.
1575 
1576     // No further widening is needed. The deceased [sz]ext had done it for us.
1577     return nullptr;
1578   }
1579 
1580   // Does this user itself evaluate to a recurrence after widening?
1581   WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1582   if (!WideAddRec.first)
1583     WideAddRec = getWideRecurrence(DU);
1584 
1585   assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
1586   if (!WideAddRec.first) {
1587     // If use is a loop condition, try to promote the condition instead of
1588     // truncating the IV first.
1589     if (widenLoopCompare(DU))
1590       return nullptr;
1591 
1592     // We are here about to generate a truncate instruction that may hurt
1593     // performance because the scalar evolution expression computed earlier
1594     // in WideAddRec.first does not indicate a polynomial induction expression.
1595     // In that case, look at the operands of the use instruction to determine
1596     // if we can still widen the use instead of truncating its operand.
1597     if (widenWithVariantLoadUse(DU)) {
1598       widenWithVariantLoadUseCodegen(DU);
1599       return nullptr;
1600     }
1601 
1602     // This user does not evaluate to a recurrence after widening, so don't
1603     // follow it. Instead insert a Trunc to kill off the original use,
1604     // eventually isolating the original narrow IV so it can be removed.
1605     truncateIVUse(DU, DT, LI);
1606     return nullptr;
1607   }
1608   // Assume block terminators cannot evaluate to a recurrence. We can't to
1609   // insert a Trunc after a terminator if there happens to be a critical edge.
1610   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1611          "SCEV is not expected to evaluate a block terminator");
1612 
1613   // Reuse the IV increment that SCEVExpander created as long as it dominates
1614   // NarrowUse.
1615   Instruction *WideUse = nullptr;
1616   if (WideAddRec.first == WideIncExpr &&
1617       Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1618     WideUse = WideInc;
1619   else {
1620     WideUse = cloneIVUser(DU, WideAddRec.first);
1621     if (!WideUse)
1622       return nullptr;
1623   }
1624   // Evaluation of WideAddRec ensured that the narrow expression could be
1625   // extended outside the loop without overflow. This suggests that the wide use
1626   // evaluates to the same expression as the extended narrow use, but doesn't
1627   // absolutely guarantee it. Hence the following failsafe check. In rare cases
1628   // where it fails, we simply throw away the newly created wide use.
1629   if (WideAddRec.first != SE->getSCEV(WideUse)) {
1630     LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1631                       << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1632                       << "\n");
1633     DeadInsts.emplace_back(WideUse);
1634     return nullptr;
1635   }
1636 
1637   ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1638   // Returning WideUse pushes it on the worklist.
1639   return WideUse;
1640 }
1641 
1642 /// Add eligible users of NarrowDef to NarrowIVUsers.
pushNarrowIVUsers(Instruction * NarrowDef,Instruction * WideDef)1643 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1644   const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1645   bool NonNegativeDef =
1646       SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1647                            SE->getConstant(NarrowSCEV->getType(), 0));
1648   for (User *U : NarrowDef->users()) {
1649     Instruction *NarrowUser = cast<Instruction>(U);
1650 
1651     // Handle data flow merges and bizarre phi cycles.
1652     if (!Widened.insert(NarrowUser).second)
1653       continue;
1654 
1655     bool NonNegativeUse = false;
1656     if (!NonNegativeDef) {
1657       // We might have a control-dependent range information for this context.
1658       if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1659         NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1660     }
1661 
1662     NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1663                                NonNegativeDef || NonNegativeUse);
1664   }
1665 }
1666 
1667 /// Process a single induction variable. First use the SCEVExpander to create a
1668 /// wide induction variable that evaluates to the same recurrence as the
1669 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1670 /// def-use chain. After widenIVUse has processed all interesting IV users, the
1671 /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1672 ///
1673 /// It would be simpler to delete uses as they are processed, but we must avoid
1674 /// invalidating SCEV expressions.
createWideIV(SCEVExpander & Rewriter)1675 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1676   // Is this phi an induction variable?
1677   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1678   if (!AddRec)
1679     return nullptr;
1680 
1681   // Widen the induction variable expression.
1682   const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1683                                ? SE->getSignExtendExpr(AddRec, WideType)
1684                                : SE->getZeroExtendExpr(AddRec, WideType);
1685 
1686   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1687          "Expect the new IV expression to preserve its type");
1688 
1689   // Can the IV be extended outside the loop without overflow?
1690   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1691   if (!AddRec || AddRec->getLoop() != L)
1692     return nullptr;
1693 
1694   // An AddRec must have loop-invariant operands. Since this AddRec is
1695   // materialized by a loop header phi, the expression cannot have any post-loop
1696   // operands, so they must dominate the loop header.
1697   assert(
1698       SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1699       SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1700       "Loop header phi recurrence inputs do not dominate the loop");
1701 
1702   // Iterate over IV uses (including transitive ones) looking for IV increments
1703   // of the form 'add nsw %iv, <const>'. For each increment and each use of
1704   // the increment calculate control-dependent range information basing on
1705   // dominating conditions inside of the loop (e.g. a range check inside of the
1706   // loop). Calculated ranges are stored in PostIncRangeInfos map.
1707   //
1708   // Control-dependent range information is later used to prove that a narrow
1709   // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1710   // this on demand because when pushNarrowIVUsers needs this information some
1711   // of the dominating conditions might be already widened.
1712   if (UsePostIncrementRanges)
1713     calculatePostIncRanges(OrigPhi);
1714 
1715   // The rewriter provides a value for the desired IV expression. This may
1716   // either find an existing phi or materialize a new one. Either way, we
1717   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1718   // of the phi-SCC dominates the loop entry.
1719   Instruction *InsertPt = &L->getHeader()->front();
1720   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1721 
1722   // Remembering the WideIV increment generated by SCEVExpander allows
1723   // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1724   // employ a general reuse mechanism because the call above is the only call to
1725   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1726   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1727     WideInc =
1728       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1729     WideIncExpr = SE->getSCEV(WideInc);
1730     // Propagate the debug location associated with the original loop increment
1731     // to the new (widened) increment.
1732     auto *OrigInc =
1733       cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1734     WideInc->setDebugLoc(OrigInc->getDebugLoc());
1735   }
1736 
1737   LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1738   ++NumWidened;
1739 
1740   // Traverse the def-use chain using a worklist starting at the original IV.
1741   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1742 
1743   Widened.insert(OrigPhi);
1744   pushNarrowIVUsers(OrigPhi, WidePhi);
1745 
1746   while (!NarrowIVUsers.empty()) {
1747     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1748 
1749     // Process a def-use edge. This may replace the use, so don't hold a
1750     // use_iterator across it.
1751     Instruction *WideUse = widenIVUse(DU, Rewriter);
1752 
1753     // Follow all def-use edges from the previous narrow use.
1754     if (WideUse)
1755       pushNarrowIVUsers(DU.NarrowUse, WideUse);
1756 
1757     // widenIVUse may have removed the def-use edge.
1758     if (DU.NarrowDef->use_empty())
1759       DeadInsts.emplace_back(DU.NarrowDef);
1760   }
1761 
1762   // Attach any debug information to the new PHI. Since OrigPhi and WidePHI
1763   // evaluate the same recurrence, we can just copy the debug info over.
1764   SmallVector<DbgValueInst *, 1> DbgValues;
1765   llvm::findDbgValues(DbgValues, OrigPhi);
1766   auto *MDPhi = MetadataAsValue::get(WidePhi->getContext(),
1767                                      ValueAsMetadata::get(WidePhi));
1768   for (auto &DbgValue : DbgValues)
1769     DbgValue->setOperand(0, MDPhi);
1770   return WidePhi;
1771 }
1772 
1773 /// Calculates control-dependent range for the given def at the given context
1774 /// by looking at dominating conditions inside of the loop
calculatePostIncRange(Instruction * NarrowDef,Instruction * NarrowUser)1775 void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
1776                                     Instruction *NarrowUser) {
1777   using namespace llvm::PatternMatch;
1778 
1779   Value *NarrowDefLHS;
1780   const APInt *NarrowDefRHS;
1781   if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
1782                                  m_APInt(NarrowDefRHS))) ||
1783       !NarrowDefRHS->isNonNegative())
1784     return;
1785 
1786   auto UpdateRangeFromCondition = [&] (Value *Condition,
1787                                        bool TrueDest) {
1788     CmpInst::Predicate Pred;
1789     Value *CmpRHS;
1790     if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
1791                                  m_Value(CmpRHS))))
1792       return;
1793 
1794     CmpInst::Predicate P =
1795             TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
1796 
1797     auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1798     auto CmpConstrainedLHSRange =
1799             ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
1800     auto NarrowDefRange =
1801             CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1802 
1803     updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1804   };
1805 
1806   auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
1807     if (!HasGuards)
1808       return;
1809 
1810     for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
1811                                      Ctx->getParent()->rend())) {
1812       Value *C = nullptr;
1813       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
1814         UpdateRangeFromCondition(C, /*TrueDest=*/true);
1815     }
1816   };
1817 
1818   UpdateRangeFromGuards(NarrowUser);
1819 
1820   BasicBlock *NarrowUserBB = NarrowUser->getParent();
1821   // If NarrowUserBB is statically unreachable asking dominator queries may
1822   // yield surprising results. (e.g. the block may not have a dom tree node)
1823   if (!DT->isReachableFromEntry(NarrowUserBB))
1824     return;
1825 
1826   for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1827        L->contains(DTB->getBlock());
1828        DTB = DTB->getIDom()) {
1829     auto *BB = DTB->getBlock();
1830     auto *TI = BB->getTerminator();
1831     UpdateRangeFromGuards(TI);
1832 
1833     auto *BI = dyn_cast<BranchInst>(TI);
1834     if (!BI || !BI->isConditional())
1835       continue;
1836 
1837     auto *TrueSuccessor = BI->getSuccessor(0);
1838     auto *FalseSuccessor = BI->getSuccessor(1);
1839 
1840     auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
1841       return BBE.isSingleEdge() &&
1842              DT->dominates(BBE, NarrowUser->getParent());
1843     };
1844 
1845     if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
1846       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
1847 
1848     if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
1849       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
1850   }
1851 }
1852 
1853 /// Calculates PostIncRangeInfos map for the given IV
calculatePostIncRanges(PHINode * OrigPhi)1854 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
1855   SmallPtrSet<Instruction *, 16> Visited;
1856   SmallVector<Instruction *, 6> Worklist;
1857   Worklist.push_back(OrigPhi);
1858   Visited.insert(OrigPhi);
1859 
1860   while (!Worklist.empty()) {
1861     Instruction *NarrowDef = Worklist.pop_back_val();
1862 
1863     for (Use &U : NarrowDef->uses()) {
1864       auto *NarrowUser = cast<Instruction>(U.getUser());
1865 
1866       // Don't go looking outside the current loop.
1867       auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
1868       if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
1869         continue;
1870 
1871       if (!Visited.insert(NarrowUser).second)
1872         continue;
1873 
1874       Worklist.push_back(NarrowUser);
1875 
1876       calculatePostIncRange(NarrowDef, NarrowUser);
1877     }
1878   }
1879 }
1880 
1881 //===----------------------------------------------------------------------===//
1882 //  Live IV Reduction - Minimize IVs live across the loop.
1883 //===----------------------------------------------------------------------===//
1884 
1885 //===----------------------------------------------------------------------===//
1886 //  Simplification of IV users based on SCEV evaluation.
1887 //===----------------------------------------------------------------------===//
1888 
1889 namespace {
1890 
1891 class IndVarSimplifyVisitor : public IVVisitor {
1892   ScalarEvolution *SE;
1893   const TargetTransformInfo *TTI;
1894   PHINode *IVPhi;
1895 
1896 public:
1897   WideIVInfo WI;
1898 
IndVarSimplifyVisitor(PHINode * IV,ScalarEvolution * SCEV,const TargetTransformInfo * TTI,const DominatorTree * DTree)1899   IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
1900                         const TargetTransformInfo *TTI,
1901                         const DominatorTree *DTree)
1902     : SE(SCEV), TTI(TTI), IVPhi(IV) {
1903     DT = DTree;
1904     WI.NarrowIV = IVPhi;
1905   }
1906 
1907   // Implement the interface used by simplifyUsersOfIV.
visitCast(CastInst * Cast)1908   void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
1909 };
1910 
1911 } // end anonymous namespace
1912 
1913 /// Iteratively perform simplification on a worklist of IV users. Each
1914 /// successive simplification may push more users which may themselves be
1915 /// candidates for simplification.
1916 ///
1917 /// Sign/Zero extend elimination is interleaved with IV simplification.
simplifyAndExtend(Loop * L,SCEVExpander & Rewriter,LoopInfo * LI)1918 bool IndVarSimplify::simplifyAndExtend(Loop *L,
1919                                        SCEVExpander &Rewriter,
1920                                        LoopInfo *LI) {
1921   SmallVector<WideIVInfo, 8> WideIVs;
1922 
1923   auto *GuardDecl = L->getBlocks()[0]->getModule()->getFunction(
1924           Intrinsic::getName(Intrinsic::experimental_guard));
1925   bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1926 
1927   SmallVector<PHINode*, 8> LoopPhis;
1928   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1929     LoopPhis.push_back(cast<PHINode>(I));
1930   }
1931   // Each round of simplification iterates through the SimplifyIVUsers worklist
1932   // for all current phis, then determines whether any IVs can be
1933   // widened. Widening adds new phis to LoopPhis, inducing another round of
1934   // simplification on the wide IVs.
1935   bool Changed = false;
1936   while (!LoopPhis.empty()) {
1937     // Evaluate as many IV expressions as possible before widening any IVs. This
1938     // forces SCEV to set no-wrap flags before evaluating sign/zero
1939     // extension. The first time SCEV attempts to normalize sign/zero extension,
1940     // the result becomes final. So for the most predictable results, we delay
1941     // evaluation of sign/zero extend evaluation until needed, and avoid running
1942     // other SCEV based analysis prior to simplifyAndExtend.
1943     do {
1944       PHINode *CurrIV = LoopPhis.pop_back_val();
1945 
1946       // Information about sign/zero extensions of CurrIV.
1947       IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1948 
1949       Changed |=
1950           simplifyUsersOfIV(CurrIV, SE, DT, LI, DeadInsts, Rewriter, &Visitor);
1951 
1952       if (Visitor.WI.WidestNativeType) {
1953         WideIVs.push_back(Visitor.WI);
1954       }
1955     } while(!LoopPhis.empty());
1956 
1957     for (; !WideIVs.empty(); WideIVs.pop_back()) {
1958       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts, HasGuards);
1959       if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1960         Changed = true;
1961         LoopPhis.push_back(WidePhi);
1962       }
1963     }
1964   }
1965   return Changed;
1966 }
1967 
1968 //===----------------------------------------------------------------------===//
1969 //  linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1970 //===----------------------------------------------------------------------===//
1971 
1972 /// Given an Value which is hoped to be part of an add recurance in the given
1973 /// loop, return the associated Phi node if so.  Otherwise, return null.  Note
1974 /// that this is less general than SCEVs AddRec checking.
getLoopPhiForCounter(Value * IncV,Loop * L)1975 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L) {
1976   Instruction *IncI = dyn_cast<Instruction>(IncV);
1977   if (!IncI)
1978     return nullptr;
1979 
1980   switch (IncI->getOpcode()) {
1981   case Instruction::Add:
1982   case Instruction::Sub:
1983     break;
1984   case Instruction::GetElementPtr:
1985     // An IV counter must preserve its type.
1986     if (IncI->getNumOperands() == 2)
1987       break;
1988     LLVM_FALLTHROUGH;
1989   default:
1990     return nullptr;
1991   }
1992 
1993   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1994   if (Phi && Phi->getParent() == L->getHeader()) {
1995     if (L->isLoopInvariant(IncI->getOperand(1)))
1996       return Phi;
1997     return nullptr;
1998   }
1999   if (IncI->getOpcode() == Instruction::GetElementPtr)
2000     return nullptr;
2001 
2002   // Allow add/sub to be commuted.
2003   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
2004   if (Phi && Phi->getParent() == L->getHeader()) {
2005     if (L->isLoopInvariant(IncI->getOperand(0)))
2006       return Phi;
2007   }
2008   return nullptr;
2009 }
2010 
2011 /// Given a loop with one backedge and one exit, return the ICmpInst
2012 /// controlling the sole loop exit.  There is no guarantee that the exiting
2013 /// block is also the latch.
getLoopTest(Loop * L,BasicBlock * ExitingBB)2014 static ICmpInst *getLoopTest(Loop *L, BasicBlock *ExitingBB) {
2015 
2016   BasicBlock *LatchBlock = L->getLoopLatch();
2017   // Don't bother with LFTR if the loop is not properly simplified.
2018   if (!LatchBlock)
2019     return nullptr;
2020 
2021   BranchInst *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
2022   assert(BI && "expected exit branch");
2023 
2024   return dyn_cast<ICmpInst>(BI->getCondition());
2025 }
2026 
2027 /// linearFunctionTestReplace policy. Return true unless we can show that the
2028 /// current exit test is already sufficiently canonical.
needsLFTR(Loop * L,BasicBlock * ExitingBB)2029 static bool needsLFTR(Loop *L, BasicBlock *ExitingBB) {
2030   // Do LFTR to simplify the exit condition to an ICMP.
2031   ICmpInst *Cond = getLoopTest(L, ExitingBB);
2032   if (!Cond)
2033     return true;
2034 
2035   // Do LFTR to simplify the exit ICMP to EQ/NE
2036   ICmpInst::Predicate Pred = Cond->getPredicate();
2037   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
2038     return true;
2039 
2040   // Look for a loop invariant RHS
2041   Value *LHS = Cond->getOperand(0);
2042   Value *RHS = Cond->getOperand(1);
2043   if (!L->isLoopInvariant(RHS)) {
2044     if (!L->isLoopInvariant(LHS))
2045       return true;
2046     std::swap(LHS, RHS);
2047   }
2048   // Look for a simple IV counter LHS
2049   PHINode *Phi = dyn_cast<PHINode>(LHS);
2050   if (!Phi)
2051     Phi = getLoopPhiForCounter(LHS, L);
2052 
2053   if (!Phi)
2054     return true;
2055 
2056   // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
2057   int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
2058   if (Idx < 0)
2059     return true;
2060 
2061   // Do LFTR if the exit condition's IV is *not* a simple counter.
2062   Value *IncV = Phi->getIncomingValue(Idx);
2063   return Phi != getLoopPhiForCounter(IncV, L);
2064 }
2065 
2066 /// Return true if undefined behavior would provable be executed on the path to
2067 /// OnPathTo if Root produced a posion result.  Note that this doesn't say
2068 /// anything about whether OnPathTo is actually executed or whether Root is
2069 /// actually poison.  This can be used to assess whether a new use of Root can
2070 /// be added at a location which is control equivalent with OnPathTo (such as
2071 /// immediately before it) without introducing UB which didn't previously
2072 /// exist.  Note that a false result conveys no information.
mustExecuteUBIfPoisonOnPathTo(Instruction * Root,Instruction * OnPathTo,DominatorTree * DT)2073 static bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root,
2074                                           Instruction *OnPathTo,
2075                                           DominatorTree *DT) {
2076   // Basic approach is to assume Root is poison, propagate poison forward
2077   // through all users we can easily track, and then check whether any of those
2078   // users are provable UB and must execute before out exiting block might
2079   // exit.
2080 
2081   // The set of all recursive users we've visited (which are assumed to all be
2082   // poison because of said visit)
2083   SmallSet<const Value *, 16> KnownPoison;
2084   SmallVector<const Instruction*, 16> Worklist;
2085   Worklist.push_back(Root);
2086   while (!Worklist.empty()) {
2087     const Instruction *I = Worklist.pop_back_val();
2088 
2089     // If we know this must trigger UB on a path leading our target.
2090     if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
2091       return true;
2092 
2093     // If we can't analyze propagation through this instruction, just skip it
2094     // and transitive users.  Safe as false is a conservative result.
2095     if (!propagatesFullPoison(I) && I != Root)
2096       continue;
2097 
2098     if (KnownPoison.insert(I).second)
2099       for (const User *User : I->users())
2100         Worklist.push_back(cast<Instruction>(User));
2101   }
2102 
2103   // Might be non-UB, or might have a path we couldn't prove must execute on
2104   // way to exiting bb.
2105   return false;
2106 }
2107 
2108 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
2109 /// down to checking that all operands are constant and listing instructions
2110 /// that may hide undef.
hasConcreteDefImpl(Value * V,SmallPtrSetImpl<Value * > & Visited,unsigned Depth)2111 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
2112                                unsigned Depth) {
2113   if (isa<Constant>(V))
2114     return !isa<UndefValue>(V);
2115 
2116   if (Depth >= 6)
2117     return false;
2118 
2119   // Conservatively handle non-constant non-instructions. For example, Arguments
2120   // may be undef.
2121   Instruction *I = dyn_cast<Instruction>(V);
2122   if (!I)
2123     return false;
2124 
2125   // Load and return values may be undef.
2126   if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
2127     return false;
2128 
2129   // Optimistically handle other instructions.
2130   for (Value *Op : I->operands()) {
2131     if (!Visited.insert(Op).second)
2132       continue;
2133     if (!hasConcreteDefImpl(Op, Visited, Depth+1))
2134       return false;
2135   }
2136   return true;
2137 }
2138 
2139 /// Return true if the given value is concrete. We must prove that undef can
2140 /// never reach it.
2141 ///
2142 /// TODO: If we decide that this is a good approach to checking for undef, we
2143 /// may factor it into a common location.
hasConcreteDef(Value * V)2144 static bool hasConcreteDef(Value *V) {
2145   SmallPtrSet<Value*, 8> Visited;
2146   Visited.insert(V);
2147   return hasConcreteDefImpl(V, Visited, 0);
2148 }
2149 
2150 /// Return true if this IV has any uses other than the (soon to be rewritten)
2151 /// loop exit test.
AlmostDeadIV(PHINode * Phi,BasicBlock * LatchBlock,Value * Cond)2152 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
2153   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
2154   Value *IncV = Phi->getIncomingValue(LatchIdx);
2155 
2156   for (User *U : Phi->users())
2157     if (U != Cond && U != IncV) return false;
2158 
2159   for (User *U : IncV->users())
2160     if (U != Cond && U != Phi) return false;
2161   return true;
2162 }
2163 
2164 /// Return true if the given phi is a "counter" in L.  A counter is an
2165 /// add recurance (of integer or pointer type) with an arbitrary start, and a
2166 /// step of 1.  Note that L must have exactly one latch.
isLoopCounter(PHINode * Phi,Loop * L,ScalarEvolution * SE)2167 static bool isLoopCounter(PHINode* Phi, Loop *L,
2168                           ScalarEvolution *SE) {
2169   assert(Phi->getParent() == L->getHeader());
2170   assert(L->getLoopLatch());
2171 
2172   if (!SE->isSCEVable(Phi->getType()))
2173     return false;
2174 
2175   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
2176   if (!AR || AR->getLoop() != L || !AR->isAffine())
2177     return false;
2178 
2179   const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
2180   if (!Step || !Step->isOne())
2181     return false;
2182 
2183   int LatchIdx = Phi->getBasicBlockIndex(L->getLoopLatch());
2184   Value *IncV = Phi->getIncomingValue(LatchIdx);
2185   return (getLoopPhiForCounter(IncV, L) == Phi);
2186 }
2187 
2188 /// Search the loop header for a loop counter (anadd rec w/step of one)
2189 /// suitable for use by LFTR.  If multiple counters are available, select the
2190 /// "best" one based profitable heuristics.
2191 ///
2192 /// BECount may be an i8* pointer type. The pointer difference is already
2193 /// valid count without scaling the address stride, so it remains a pointer
2194 /// expression as far as SCEV is concerned.
FindLoopCounter(Loop * L,BasicBlock * ExitingBB,const SCEV * BECount,ScalarEvolution * SE,DominatorTree * DT)2195 static PHINode *FindLoopCounter(Loop *L, BasicBlock *ExitingBB,
2196                                 const SCEV *BECount,
2197                                 ScalarEvolution *SE, DominatorTree *DT) {
2198   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
2199 
2200   Value *Cond = cast<BranchInst>(ExitingBB->getTerminator())->getCondition();
2201 
2202   // Loop over all of the PHI nodes, looking for a simple counter.
2203   PHINode *BestPhi = nullptr;
2204   const SCEV *BestInit = nullptr;
2205   BasicBlock *LatchBlock = L->getLoopLatch();
2206   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
2207   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2208 
2209   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
2210     PHINode *Phi = cast<PHINode>(I);
2211     if (!isLoopCounter(Phi, L, SE))
2212       continue;
2213 
2214     // Avoid comparing an integer IV against a pointer Limit.
2215     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
2216       continue;
2217 
2218     const auto *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
2219 
2220     // AR may be a pointer type, while BECount is an integer type.
2221     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
2222     // AR may not be a narrower type, or we may never exit.
2223     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
2224     if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
2225       continue;
2226 
2227     // Avoid reusing a potentially undef value to compute other values that may
2228     // have originally had a concrete definition.
2229     if (!hasConcreteDef(Phi)) {
2230       // We explicitly allow unknown phis as long as they are already used by
2231       // the loop test. In this case we assume that performing LFTR could not
2232       // increase the number of undef users.
2233       // TODO: Generalize this to allow *any* loop exit which is known to
2234       // execute on each iteration
2235       if (L->getExitingBlock())
2236         if (ICmpInst *Cond = getLoopTest(L, ExitingBB))
2237           if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L) &&
2238               Phi != getLoopPhiForCounter(Cond->getOperand(1), L))
2239             continue;
2240     }
2241 
2242     // Avoid introducing undefined behavior due to poison which didn't exist in
2243     // the original program.  (Annoyingly, the rules for poison and undef
2244     // propagation are distinct, so this does NOT cover the undef case above.)
2245     // We have to ensure that we don't introduce UB by introducing a use on an
2246     // iteration where said IV produces poison.  Our strategy here differs for
2247     // pointers and integer IVs.  For integers, we strip and reinfer as needed,
2248     // see code in linearFunctionTestReplace.  For pointers, we restrict
2249     // transforms as there is no good way to reinfer inbounds once lost.
2250     if (!Phi->getType()->isIntegerTy() &&
2251         !mustExecuteUBIfPoisonOnPathTo(Phi, ExitingBB->getTerminator(), DT))
2252       continue;
2253 
2254     const SCEV *Init = AR->getStart();
2255 
2256     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2257       // Don't force a live loop counter if another IV can be used.
2258       if (AlmostDeadIV(Phi, LatchBlock, Cond))
2259         continue;
2260 
2261       // Prefer to count-from-zero. This is a more "canonical" counter form. It
2262       // also prefers integer to pointer IVs.
2263       if (BestInit->isZero() != Init->isZero()) {
2264         if (BestInit->isZero())
2265           continue;
2266       }
2267       // If two IVs both count from zero or both count from nonzero then the
2268       // narrower is likely a dead phi that has been widened. Use the wider phi
2269       // to allow the other to be eliminated.
2270       else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
2271         continue;
2272     }
2273     BestPhi = Phi;
2274     BestInit = Init;
2275   }
2276   return BestPhi;
2277 }
2278 
2279 /// Insert an IR expression which computes the value held by the IV IndVar
2280 /// (which must be an loop counter w/unit stride) after the backedge of loop L
2281 /// is taken ExitCount times.
genLoopLimit(PHINode * IndVar,BasicBlock * ExitingBB,const SCEV * ExitCount,bool UsePostInc,Loop * L,SCEVExpander & Rewriter,ScalarEvolution * SE)2282 static Value *genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB,
2283                            const SCEV *ExitCount, bool UsePostInc, Loop *L,
2284                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
2285   assert(isLoopCounter(IndVar, L, SE));
2286   const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2287   const SCEV *IVInit = AR->getStart();
2288 
2289   // IVInit may be a pointer while ExitCount is an integer when FindLoopCounter
2290   // finds a valid pointer IV. Sign extend ExitCount in order to materialize a
2291   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
2292   // the existing GEPs whenever possible.
2293   if (IndVar->getType()->isPointerTy() &&
2294       !ExitCount->getType()->isPointerTy()) {
2295     // IVOffset will be the new GEP offset that is interpreted by GEP as a
2296     // signed value. ExitCount on the other hand represents the loop trip count,
2297     // which is an unsigned value. FindLoopCounter only allows induction
2298     // variables that have a positive unit stride of one. This means we don't
2299     // have to handle the case of negative offsets (yet) and just need to zero
2300     // extend ExitCount.
2301     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
2302     const SCEV *IVOffset = SE->getTruncateOrZeroExtend(ExitCount, OfsTy);
2303     if (UsePostInc)
2304       IVOffset = SE->getAddExpr(IVOffset, SE->getOne(OfsTy));
2305 
2306     // Expand the code for the iteration count.
2307     assert(SE->isLoopInvariant(IVOffset, L) &&
2308            "Computed iteration count is not loop invariant!");
2309     BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());
2310     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
2311 
2312     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
2313     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
2314     // We could handle pointer IVs other than i8*, but we need to compensate for
2315     // gep index scaling.
2316     assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
2317                              cast<PointerType>(GEPBase->getType())
2318                                  ->getElementType())->isOne() &&
2319            "unit stride pointer IV must be i8*");
2320 
2321     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2322     return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
2323   } else {
2324     // In any other case, convert both IVInit and ExitCount to integers before
2325     // comparing. This may result in SCEV expansion of pointers, but in practice
2326     // SCEV will fold the pointer arithmetic away as such:
2327     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
2328     //
2329     // Valid Cases: (1) both integers is most common; (2) both may be pointers
2330     // for simple memset-style loops.
2331     //
2332     // IVInit integer and ExitCount pointer would only occur if a canonical IV
2333     // were generated on top of case #2, which is not expected.
2334 
2335     assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
2336     // For unit stride, IVCount = Start + ExitCount with 2's complement
2337     // overflow.
2338     const SCEV *IVInit = AR->getStart();
2339 
2340     // For integer IVs, truncate the IV before computing IVInit + BECount.
2341     if (SE->getTypeSizeInBits(IVInit->getType())
2342         > SE->getTypeSizeInBits(ExitCount->getType()))
2343       IVInit = SE->getTruncateExpr(IVInit, ExitCount->getType());
2344 
2345     const SCEV *IVLimit = SE->getAddExpr(IVInit, ExitCount);
2346 
2347     if (UsePostInc)
2348       IVLimit = SE->getAddExpr(IVLimit, SE->getOne(IVLimit->getType()));
2349 
2350     // Expand the code for the iteration count.
2351     BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());
2352     IRBuilder<> Builder(BI);
2353     assert(SE->isLoopInvariant(IVLimit, L) &&
2354            "Computed iteration count is not loop invariant!");
2355     // Ensure that we generate the same type as IndVar, or a smaller integer
2356     // type. In the presence of null pointer values, we have an integer type
2357     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
2358     Type *LimitTy = ExitCount->getType()->isPointerTy() ?
2359       IndVar->getType() : ExitCount->getType();
2360     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
2361   }
2362 }
2363 
2364 /// This method rewrites the exit condition of the loop to be a canonical !=
2365 /// comparison against the incremented loop induction variable.  This pass is
2366 /// able to rewrite the exit tests of any loop where the SCEV analysis can
2367 /// determine a loop-invariant trip count of the loop, which is actually a much
2368 /// broader range than just linear tests.
2369 bool IndVarSimplify::
linearFunctionTestReplace(Loop * L,BasicBlock * ExitingBB,const SCEV * ExitCount,PHINode * IndVar,SCEVExpander & Rewriter)2370 linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,
2371                           const SCEV *ExitCount,
2372                           PHINode *IndVar, SCEVExpander &Rewriter) {
2373   assert(L->getLoopLatch() && "Loop no longer in simplified form?");
2374   assert(isLoopCounter(IndVar, L, SE));
2375   Instruction * const IncVar =
2376     cast<Instruction>(IndVar->getIncomingValueForBlock(L->getLoopLatch()));
2377 
2378   // Initialize CmpIndVar to the preincremented IV.
2379   Value *CmpIndVar = IndVar;
2380   bool UsePostInc = false;
2381 
2382   // If the exiting block is the same as the backedge block, we prefer to
2383   // compare against the post-incremented value, otherwise we must compare
2384   // against the preincremented value.
2385   if (ExitingBB == L->getLoopLatch()) {
2386     bool SafeToPostInc = IndVar->getType()->isIntegerTy();
2387     if (!SafeToPostInc) {
2388       // For pointer IVs, we chose to not strip inbounds which requires us not
2389       // to add a potentially UB introducing use.  We need to either a) show
2390       // the loop test we're modifying is already in post-inc form, or b) show
2391       // that adding a use must not introduce UB.
2392       if (ICmpInst *LoopTest = getLoopTest(L, ExitingBB))
2393         SafeToPostInc = LoopTest->getOperand(0) == IncVar ||
2394           LoopTest->getOperand(1) == IncVar;
2395       if (!SafeToPostInc)
2396         SafeToPostInc =
2397           mustExecuteUBIfPoisonOnPathTo(IncVar, ExitingBB->getTerminator(), DT);
2398     }
2399 
2400     if (SafeToPostInc) {
2401       UsePostInc = true;
2402       CmpIndVar = IncVar;
2403     }
2404   }
2405 
2406   // It may be necessary to drop nowrap flags on the incrementing instruction
2407   // if either LFTR moves from a pre-inc check to a post-inc check (in which
2408   // case the increment might have previously been poison on the last iteration
2409   // only) or if LFTR switches to a different IV that was previously dynamically
2410   // dead (and as such may be arbitrarily poison). We remove any nowrap flags
2411   // that SCEV didn't infer for the post-inc addrec (even if we use a pre-inc
2412   // check), because the pre-inc addrec flags may be adopted from the original
2413   // instruction, while SCEV has to explicitly prove the post-inc nowrap flags.
2414   // TODO: This handling is inaccurate for one case: If we switch to a
2415   // dynamically dead IV that wraps on the first loop iteration only, which is
2416   // not covered by the post-inc addrec. (If the new IV was not dynamically
2417   // dead, it could not be poison on the first iteration in the first place.)
2418   if (auto *BO = dyn_cast<BinaryOperator>(IncVar)) {
2419     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IncVar));
2420     if (BO->hasNoUnsignedWrap())
2421       BO->setHasNoUnsignedWrap(AR->hasNoUnsignedWrap());
2422     if (BO->hasNoSignedWrap())
2423       BO->setHasNoSignedWrap(AR->hasNoSignedWrap());
2424   }
2425 
2426   Value *ExitCnt = genLoopLimit(
2427       IndVar, ExitingBB, ExitCount, UsePostInc, L, Rewriter, SE);
2428   assert(ExitCnt->getType()->isPointerTy() ==
2429              IndVar->getType()->isPointerTy() &&
2430          "genLoopLimit missed a cast");
2431 
2432   // Insert a new icmp_ne or icmp_eq instruction before the branch.
2433   BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());
2434   ICmpInst::Predicate P;
2435   if (L->contains(BI->getSuccessor(0)))
2436     P = ICmpInst::ICMP_NE;
2437   else
2438     P = ICmpInst::ICMP_EQ;
2439 
2440   IRBuilder<> Builder(BI);
2441 
2442   // The new loop exit condition should reuse the debug location of the
2443   // original loop exit condition.
2444   if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2445     Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
2446 
2447   // LFTR can ignore IV overflow and truncate to the width of
2448   // ExitCount. This avoids materializing the add(zext(add)) expression.
2449   unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
2450   unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
2451   if (CmpIndVarSize > ExitCntSize) {
2452     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2453     const SCEV *ARStart = AR->getStart();
2454     const SCEV *ARStep = AR->getStepRecurrence(*SE);
2455     // For constant ExitCount, avoid truncation.
2456     if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(ExitCount)) {
2457       const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2458       APInt Count = cast<SCEVConstant>(ExitCount)->getAPInt();
2459       Count = Count.zext(CmpIndVarSize);
2460       if (UsePostInc)
2461         ++Count;
2462       APInt NewLimit;
2463       if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2464         NewLimit = Start - Count;
2465       else
2466         NewLimit = Start + Count;
2467       ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
2468 
2469       LLVM_DEBUG(dbgs() << "  Widen RHS:\t" << *ExitCnt << "\n");
2470     } else {
2471       // We try to extend trip count first. If that doesn't work we truncate IV.
2472       // Zext(trunc(IV)) == IV implies equivalence of the following two:
2473       // Trunc(IV) == ExitCnt and IV == zext(ExitCnt). Similarly for sext. If
2474       // one of the two holds, extend the trip count, otherwise we truncate IV.
2475       bool Extended = false;
2476       const SCEV *IV = SE->getSCEV(CmpIndVar);
2477       const SCEV *ZExtTrunc =
2478            SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2479                                                      ExitCnt->getType()),
2480                                  CmpIndVar->getType());
2481 
2482       if (ZExtTrunc == IV) {
2483         Extended = true;
2484         ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),
2485                                      "wide.trip.count");
2486       } else {
2487         const SCEV *SExtTrunc =
2488           SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2489                                                     ExitCnt->getType()),
2490                                 CmpIndVar->getType());
2491         if (SExtTrunc == IV) {
2492           Extended = true;
2493           ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),
2494                                        "wide.trip.count");
2495         }
2496       }
2497 
2498       if (!Extended)
2499         CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
2500                                         "lftr.wideiv");
2501     }
2502   }
2503   LLVM_DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
2504                     << "      LHS:" << *CmpIndVar << '\n'
2505                     << "       op:\t" << (P == ICmpInst::ICMP_NE ? "!=" : "==")
2506                     << "\n"
2507                     << "      RHS:\t" << *ExitCnt << "\n"
2508                     << "ExitCount:\t" << *ExitCount << "\n"
2509                     << "  was: " << *BI->getCondition() << "\n");
2510 
2511   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
2512   Value *OrigCond = BI->getCondition();
2513   // It's tempting to use replaceAllUsesWith here to fully replace the old
2514   // comparison, but that's not immediately safe, since users of the old
2515   // comparison may not be dominated by the new comparison. Instead, just
2516   // update the branch to use the new comparison; in the common case this
2517   // will make old comparison dead.
2518   BI->setCondition(Cond);
2519   DeadInsts.push_back(OrigCond);
2520 
2521   ++NumLFTR;
2522   return true;
2523 }
2524 
2525 //===----------------------------------------------------------------------===//
2526 //  sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
2527 //===----------------------------------------------------------------------===//
2528 
2529 /// If there's a single exit block, sink any loop-invariant values that
2530 /// were defined in the preheader but not used inside the loop into the
2531 /// exit block to reduce register pressure in the loop.
sinkUnusedInvariants(Loop * L)2532 bool IndVarSimplify::sinkUnusedInvariants(Loop *L) {
2533   BasicBlock *ExitBlock = L->getExitBlock();
2534   if (!ExitBlock) return false;
2535 
2536   BasicBlock *Preheader = L->getLoopPreheader();
2537   if (!Preheader) return false;
2538 
2539   bool MadeAnyChanges = false;
2540   BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt();
2541   BasicBlock::iterator I(Preheader->getTerminator());
2542   while (I != Preheader->begin()) {
2543     --I;
2544     // New instructions were inserted at the end of the preheader.
2545     if (isa<PHINode>(I))
2546       break;
2547 
2548     // Don't move instructions which might have side effects, since the side
2549     // effects need to complete before instructions inside the loop.  Also don't
2550     // move instructions which might read memory, since the loop may modify
2551     // memory. Note that it's okay if the instruction might have undefined
2552     // behavior: LoopSimplify guarantees that the preheader dominates the exit
2553     // block.
2554     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2555       continue;
2556 
2557     // Skip debug info intrinsics.
2558     if (isa<DbgInfoIntrinsic>(I))
2559       continue;
2560 
2561     // Skip eh pad instructions.
2562     if (I->isEHPad())
2563       continue;
2564 
2565     // Don't sink alloca: we never want to sink static alloca's out of the
2566     // entry block, and correctly sinking dynamic alloca's requires
2567     // checks for stacksave/stackrestore intrinsics.
2568     // FIXME: Refactor this check somehow?
2569     if (isa<AllocaInst>(I))
2570       continue;
2571 
2572     // Determine if there is a use in or before the loop (direct or
2573     // otherwise).
2574     bool UsedInLoop = false;
2575     for (Use &U : I->uses()) {
2576       Instruction *User = cast<Instruction>(U.getUser());
2577       BasicBlock *UseBB = User->getParent();
2578       if (PHINode *P = dyn_cast<PHINode>(User)) {
2579         unsigned i =
2580           PHINode::getIncomingValueNumForOperand(U.getOperandNo());
2581         UseBB = P->getIncomingBlock(i);
2582       }
2583       if (UseBB == Preheader || L->contains(UseBB)) {
2584         UsedInLoop = true;
2585         break;
2586       }
2587     }
2588 
2589     // If there is, the def must remain in the preheader.
2590     if (UsedInLoop)
2591       continue;
2592 
2593     // Otherwise, sink it to the exit block.
2594     Instruction *ToMove = &*I;
2595     bool Done = false;
2596 
2597     if (I != Preheader->begin()) {
2598       // Skip debug info intrinsics.
2599       do {
2600         --I;
2601       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2602 
2603       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2604         Done = true;
2605     } else {
2606       Done = true;
2607     }
2608 
2609     MadeAnyChanges = true;
2610     ToMove->moveBefore(*ExitBlock, InsertPt);
2611     if (Done) break;
2612     InsertPt = ToMove->getIterator();
2613   }
2614 
2615   return MadeAnyChanges;
2616 }
2617 
2618 //===----------------------------------------------------------------------===//
2619 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
2620 //===----------------------------------------------------------------------===//
2621 
run(Loop * L)2622 bool IndVarSimplify::run(Loop *L) {
2623   // We need (and expect!) the incoming loop to be in LCSSA.
2624   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2625          "LCSSA required to run indvars!");
2626   bool Changed = false;
2627 
2628   // If LoopSimplify form is not available, stay out of trouble. Some notes:
2629   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
2630   //    canonicalization can be a pessimization without LSR to "clean up"
2631   //    afterwards.
2632   //  - We depend on having a preheader; in particular,
2633   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
2634   //    and we're in trouble if we can't find the induction variable even when
2635   //    we've manually inserted one.
2636   //  - LFTR relies on having a single backedge.
2637   if (!L->isLoopSimplifyForm())
2638     return false;
2639 
2640   // If there are any floating-point recurrences, attempt to
2641   // transform them to use integer recurrences.
2642   Changed |= rewriteNonIntegerIVs(L);
2643 
2644   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2645 
2646   // Create a rewriter object which we'll use to transform the code with.
2647   SCEVExpander Rewriter(*SE, DL, "indvars");
2648 #ifndef NDEBUG
2649   Rewriter.setDebugType(DEBUG_TYPE);
2650 #endif
2651 
2652   // Eliminate redundant IV users.
2653   //
2654   // Simplification works best when run before other consumers of SCEV. We
2655   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2656   // other expressions involving loop IVs have been evaluated. This helps SCEV
2657   // set no-wrap flags before normalizing sign/zero extension.
2658   Rewriter.disableCanonicalMode();
2659   Changed |= simplifyAndExtend(L, Rewriter, LI);
2660 
2661   // Check to see if this loop has a computable loop-invariant execution count.
2662   // If so, this means that we can compute the final value of any expressions
2663   // that are recurrent in the loop, and substitute the exit values from the
2664   // loop into any instructions outside of the loop that use the final values of
2665   // the current expressions.
2666   //
2667   if (ReplaceExitValue != NeverRepl &&
2668       !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2669     Changed |= rewriteLoopExitValues(L, Rewriter);
2670 
2671   // Eliminate redundant IV cycles.
2672   NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
2673 
2674   // If we have a trip count expression, rewrite the loop's exit condition
2675   // using it.
2676   if (!DisableLFTR) {
2677     // For the moment, we only do LFTR for single exit loops.  The code is
2678     // structured as it is in the expectation of generalization to multi-exit
2679     // loops in the near future.  See D62625 for context.
2680     SmallVector<BasicBlock*, 16> ExitingBlocks;
2681     if (auto *ExitingBB = L->getExitingBlock())
2682       ExitingBlocks.push_back(ExitingBB);
2683     for (BasicBlock *ExitingBB : ExitingBlocks) {
2684       // Can't rewrite non-branch yet.
2685       if (!isa<BranchInst>(ExitingBB->getTerminator()))
2686         continue;
2687 
2688       if (!needsLFTR(L, ExitingBB))
2689         continue;
2690 
2691       const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2692       if (isa<SCEVCouldNotCompute>(ExitCount))
2693         continue;
2694 
2695       // Better to fold to true (TODO: do so!)
2696       if (ExitCount->isZero())
2697         continue;
2698 
2699       PHINode *IndVar = FindLoopCounter(L, ExitingBB, ExitCount, SE, DT);
2700       if (!IndVar)
2701         continue;
2702 
2703       // Avoid high cost expansions.  Note: This heuristic is questionable in
2704       // that our definition of "high cost" is not exactly principled.
2705       if (Rewriter.isHighCostExpansion(ExitCount, L))
2706         continue;
2707 
2708       // Check preconditions for proper SCEVExpander operation. SCEV does not
2709       // express SCEVExpander's dependencies, such as LoopSimplify. Instead
2710       // any pass that uses the SCEVExpander must do it. This does not work
2711       // well for loop passes because SCEVExpander makes assumptions about
2712       // all loops, while LoopPassManager only forces the current loop to be
2713       // simplified.
2714       //
2715       // FIXME: SCEV expansion has no way to bail out, so the caller must
2716       // explicitly check any assumptions made by SCEV. Brittle.
2717       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ExitCount);
2718       if (!AR || AR->getLoop()->getLoopPreheader())
2719         Changed |= linearFunctionTestReplace(L, ExitingBB,
2720                                              ExitCount, IndVar,
2721                                              Rewriter);
2722     }
2723   }
2724   // Clear the rewriter cache, because values that are in the rewriter's cache
2725   // can be deleted in the loop below, causing the AssertingVH in the cache to
2726   // trigger.
2727   Rewriter.clear();
2728 
2729   // Now that we're done iterating through lists, clean up any instructions
2730   // which are now dead.
2731   while (!DeadInsts.empty())
2732     if (Instruction *Inst =
2733             dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2734       Changed |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
2735 
2736   // The Rewriter may not be used from this point on.
2737 
2738   // Loop-invariant instructions in the preheader that aren't used in the
2739   // loop may be sunk below the loop to reduce register pressure.
2740   Changed |= sinkUnusedInvariants(L);
2741 
2742   // rewriteFirstIterationLoopExitValues does not rely on the computation of
2743   // trip count and therefore can further simplify exit values in addition to
2744   // rewriteLoopExitValues.
2745   Changed |= rewriteFirstIterationLoopExitValues(L);
2746 
2747   // Clean up dead instructions.
2748   Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
2749 
2750   // Check a post-condition.
2751   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2752          "Indvars did not preserve LCSSA!");
2753 
2754   // Verify that LFTR, and any other change have not interfered with SCEV's
2755   // ability to compute trip count.
2756 #ifndef NDEBUG
2757   if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2758     SE->forgetLoop(L);
2759     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2760     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2761         SE->getTypeSizeInBits(NewBECount->getType()))
2762       NewBECount = SE->getTruncateOrNoop(NewBECount,
2763                                          BackedgeTakenCount->getType());
2764     else
2765       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2766                                                  NewBECount->getType());
2767     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2768   }
2769 #endif
2770 
2771   return Changed;
2772 }
2773 
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater &)2774 PreservedAnalyses IndVarSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
2775                                           LoopStandardAnalysisResults &AR,
2776                                           LPMUpdater &) {
2777   Function *F = L.getHeader()->getParent();
2778   const DataLayout &DL = F->getParent()->getDataLayout();
2779 
2780   IndVarSimplify IVS(&AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI);
2781   if (!IVS.run(&L))
2782     return PreservedAnalyses::all();
2783 
2784   auto PA = getLoopPassPreservedAnalyses();
2785   PA.preserveSet<CFGAnalyses>();
2786   return PA;
2787 }
2788 
2789 namespace {
2790 
2791 struct IndVarSimplifyLegacyPass : public LoopPass {
2792   static char ID; // Pass identification, replacement for typeid
2793 
IndVarSimplifyLegacyPass__anonc65a48c90e11::IndVarSimplifyLegacyPass2794   IndVarSimplifyLegacyPass() : LoopPass(ID) {
2795     initializeIndVarSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
2796   }
2797 
runOnLoop__anonc65a48c90e11::IndVarSimplifyLegacyPass2798   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
2799     if (skipLoop(L))
2800       return false;
2801 
2802     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2803     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2804     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2805     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2806     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2807     auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2808     auto *TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
2809     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2810 
2811     IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2812     return IVS.run(L);
2813   }
2814 
getAnalysisUsage__anonc65a48c90e11::IndVarSimplifyLegacyPass2815   void getAnalysisUsage(AnalysisUsage &AU) const override {
2816     AU.setPreservesCFG();
2817     getLoopAnalysisUsage(AU);
2818   }
2819 };
2820 
2821 } // end anonymous namespace
2822 
2823 char IndVarSimplifyLegacyPass::ID = 0;
2824 
2825 INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars",
2826                       "Induction Variable Simplification", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)2827 INITIALIZE_PASS_DEPENDENCY(LoopPass)
2828 INITIALIZE_PASS_END(IndVarSimplifyLegacyPass, "indvars",
2829                     "Induction Variable Simplification", false, false)
2830 
2831 Pass *llvm::createIndVarSimplifyPass() {
2832   return new IndVarSimplifyLegacyPass();
2833 }
2834