xref: /llvm-project/llvm/lib/Transforms/Utils/ScalarEvolutionExpander.cpp (revision 9efb07f261b2cd673c0a5abf2ed2546ad288ab48)
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution expander,
10 // which is used to generate the code corresponding to a given scalar evolution
11 // expression.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/LoopUtils.h"
30 
31 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
32 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
33 #else
34 #define SCEV_DEBUG_WITH_TYPE(TYPE, X)
35 #endif
36 
37 using namespace llvm;
38 
39 cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
40     "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
41     cl::desc("When performing SCEV expansion only if it is cheap to do, this "
42              "controls the budget that is considered cheap (default = 4)"));
43 
44 using namespace PatternMatch;
45 
46 PoisonFlags::PoisonFlags(const Instruction *I) {
47   NUW = false;
48   NSW = false;
49   Exact = false;
50   Disjoint = false;
51   NNeg = false;
52   SameSign = false;
53   GEPNW = GEPNoWrapFlags::none();
54   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
55     NUW = OBO->hasNoUnsignedWrap();
56     NSW = OBO->hasNoSignedWrap();
57   }
58   if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
59     Exact = PEO->isExact();
60   if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
61     Disjoint = PDI->isDisjoint();
62   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
63     NNeg = PNI->hasNonNeg();
64   if (auto *TI = dyn_cast<TruncInst>(I)) {
65     NUW = TI->hasNoUnsignedWrap();
66     NSW = TI->hasNoSignedWrap();
67   }
68   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
69     GEPNW = GEP->getNoWrapFlags();
70   if (auto *ICmp = dyn_cast<ICmpInst>(I))
71     SameSign = ICmp->hasSameSign();
72 }
73 
74 void PoisonFlags::apply(Instruction *I) {
75   if (isa<OverflowingBinaryOperator>(I)) {
76     I->setHasNoUnsignedWrap(NUW);
77     I->setHasNoSignedWrap(NSW);
78   }
79   if (isa<PossiblyExactOperator>(I))
80     I->setIsExact(Exact);
81   if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
82     PDI->setIsDisjoint(Disjoint);
83   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
84     PNI->setNonNeg(NNeg);
85   if (isa<TruncInst>(I)) {
86     I->setHasNoUnsignedWrap(NUW);
87     I->setHasNoSignedWrap(NSW);
88   }
89   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
90     GEP->setNoWrapFlags(GEPNW);
91   if (auto *ICmp = dyn_cast<ICmpInst>(I))
92     ICmp->setSameSign(SameSign);
93 }
94 
95 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
96 /// reusing an existing cast if a suitable one (= dominating IP) exists, or
97 /// creating a new one.
98 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
99                                        Instruction::CastOps Op,
100                                        BasicBlock::iterator IP) {
101   // This function must be called with the builder having a valid insertion
102   // point. It doesn't need to be the actual IP where the uses of the returned
103   // cast will be added, but it must dominate such IP.
104   // We use this precondition to produce a cast that will dominate all its
105   // uses. In particular, this is crucial for the case where the builder's
106   // insertion point *is* the point where we were asked to put the cast.
107   // Since we don't know the builder's insertion point is actually
108   // where the uses will be added (only that it dominates it), we are
109   // not allowed to move it.
110   BasicBlock::iterator BIP = Builder.GetInsertPoint();
111 
112   Value *Ret = nullptr;
113 
114   // Check to see if there is already a cast!
115   for (User *U : V->users()) {
116     if (U->getType() != Ty)
117       continue;
118     CastInst *CI = dyn_cast<CastInst>(U);
119     if (!CI || CI->getOpcode() != Op)
120       continue;
121 
122     // Found a suitable cast that is at IP or comes before IP. Use it. Note that
123     // the cast must also properly dominate the Builder's insertion point.
124     if (IP->getParent() == CI->getParent() && &*BIP != CI &&
125         (&*IP == CI || CI->comesBefore(&*IP))) {
126       Ret = CI;
127       break;
128     }
129   }
130 
131   // Create a new cast.
132   if (!Ret) {
133     SCEVInsertPointGuard Guard(Builder, this);
134     Builder.SetInsertPoint(&*IP);
135     Ret = Builder.CreateCast(Op, V, Ty, V->getName());
136   }
137 
138   // We assert at the end of the function since IP might point to an
139   // instruction with different dominance properties than a cast
140   // (an invoke for example) and not dominate BIP (but the cast does).
141   assert(!isa<Instruction>(Ret) ||
142          SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
143 
144   return Ret;
145 }
146 
147 BasicBlock::iterator
148 SCEVExpander::findInsertPointAfter(Instruction *I,
149                                    Instruction *MustDominate) const {
150   BasicBlock::iterator IP = ++I->getIterator();
151   if (auto *II = dyn_cast<InvokeInst>(I))
152     IP = II->getNormalDest()->begin();
153 
154   while (isa<PHINode>(IP))
155     ++IP;
156 
157   if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
158     ++IP;
159   } else if (isa<CatchSwitchInst>(IP)) {
160     IP = MustDominate->getParent()->getFirstInsertionPt();
161   } else {
162     assert(!IP->isEHPad() && "unexpected eh pad!");
163   }
164 
165   // Adjust insert point to be after instructions inserted by the expander, so
166   // we can re-use already inserted instructions. Avoid skipping past the
167   // original \p MustDominate, in case it is an inserted instruction.
168   while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
169     ++IP;
170 
171   return IP;
172 }
173 
174 BasicBlock::iterator
175 SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
176   // Cast the argument at the beginning of the entry block, after
177   // any bitcasts of other arguments.
178   if (Argument *A = dyn_cast<Argument>(V)) {
179     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
180     while ((isa<BitCastInst>(IP) &&
181             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
182             cast<BitCastInst>(IP)->getOperand(0) != A) ||
183            isa<DbgInfoIntrinsic>(IP))
184       ++IP;
185     return IP;
186   }
187 
188   // Cast the instruction immediately after the instruction.
189   if (Instruction *I = dyn_cast<Instruction>(V))
190     return findInsertPointAfter(I, &*Builder.GetInsertPoint());
191 
192   // Otherwise, this must be some kind of a constant,
193   // so let's plop this cast into the function's entry block.
194   assert(isa<Constant>(V) &&
195          "Expected the cast argument to be a global/constant");
196   return Builder.GetInsertBlock()
197       ->getParent()
198       ->getEntryBlock()
199       .getFirstInsertionPt();
200 }
201 
202 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
203 /// which must be possible with a noop cast, doing what we can to share
204 /// the casts.
205 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
206   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
207   assert((Op == Instruction::BitCast ||
208           Op == Instruction::PtrToInt ||
209           Op == Instruction::IntToPtr) &&
210          "InsertNoopCastOfTo cannot perform non-noop casts!");
211   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
212          "InsertNoopCastOfTo cannot change sizes!");
213 
214   // inttoptr only works for integral pointers. For non-integral pointers, we
215   // can create a GEP on null with the integral value as index. Note that
216   // it is safe to use GEP of null instead of inttoptr here, because only
217   // expressions already based on a GEP of null should be converted to pointers
218   // during expansion.
219   if (Op == Instruction::IntToPtr) {
220     auto *PtrTy = cast<PointerType>(Ty);
221     if (DL.isNonIntegralPointerType(PtrTy))
222       return Builder.CreatePtrAdd(Constant::getNullValue(PtrTy), V, "scevgep");
223   }
224   // Short-circuit unnecessary bitcasts.
225   if (Op == Instruction::BitCast) {
226     if (V->getType() == Ty)
227       return V;
228     if (CastInst *CI = dyn_cast<CastInst>(V)) {
229       if (CI->getOperand(0)->getType() == Ty)
230         return CI->getOperand(0);
231     }
232   }
233   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
234   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
235       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
236     if (CastInst *CI = dyn_cast<CastInst>(V))
237       if ((CI->getOpcode() == Instruction::PtrToInt ||
238            CI->getOpcode() == Instruction::IntToPtr) &&
239           SE.getTypeSizeInBits(CI->getType()) ==
240           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
241         return CI->getOperand(0);
242     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
243       if ((CE->getOpcode() == Instruction::PtrToInt ||
244            CE->getOpcode() == Instruction::IntToPtr) &&
245           SE.getTypeSizeInBits(CE->getType()) ==
246           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
247         return CE->getOperand(0);
248   }
249 
250   // Fold a cast of a constant.
251   if (Constant *C = dyn_cast<Constant>(V))
252     return ConstantExpr::getCast(Op, C, Ty);
253 
254   // Try to reuse existing cast, or insert one.
255   return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
256 }
257 
258 /// InsertBinop - Insert the specified binary operator, doing a small amount
259 /// of work to avoid inserting an obviously redundant operation, and hoisting
260 /// to an outer loop when the opportunity is there and it is safe.
261 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
262                                  Value *LHS, Value *RHS,
263                                  SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
264   // Fold a binop with constant operands.
265   if (Constant *CLHS = dyn_cast<Constant>(LHS))
266     if (Constant *CRHS = dyn_cast<Constant>(RHS))
267       if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL))
268         return Res;
269 
270   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
271   unsigned ScanLimit = 6;
272   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
273   // Scanning starts from the last instruction before the insertion point.
274   BasicBlock::iterator IP = Builder.GetInsertPoint();
275   if (IP != BlockBegin) {
276     --IP;
277     for (; ScanLimit; --IP, --ScanLimit) {
278       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
279       // generated code.
280       if (isa<DbgInfoIntrinsic>(IP))
281         ScanLimit++;
282 
283       auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
284         // Ensure that no-wrap flags match.
285         if (isa<OverflowingBinaryOperator>(I)) {
286           if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
287             return true;
288           if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
289             return true;
290         }
291         // Conservatively, do not use any instruction which has any of exact
292         // flags installed.
293         if (isa<PossiblyExactOperator>(I) && I->isExact())
294           return true;
295         return false;
296       };
297       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
298           IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
299         return &*IP;
300       if (IP == BlockBegin) break;
301     }
302   }
303 
304   // Save the original insertion point so we can restore it when we're done.
305   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
306   SCEVInsertPointGuard Guard(Builder, this);
307 
308   if (IsSafeToHoist) {
309     // Move the insertion point out of as many loops as we can.
310     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
311       if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
312       BasicBlock *Preheader = L->getLoopPreheader();
313       if (!Preheader) break;
314 
315       // Ok, move up a level.
316       Builder.SetInsertPoint(Preheader->getTerminator());
317     }
318   }
319 
320   // If we haven't found this binop, insert it.
321   // TODO: Use the Builder, which will make CreateBinOp below fold with
322   // InstSimplifyFolder.
323   Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS));
324   BO->setDebugLoc(Loc);
325   if (Flags & SCEV::FlagNUW)
326     BO->setHasNoUnsignedWrap();
327   if (Flags & SCEV::FlagNSW)
328     BO->setHasNoSignedWrap();
329 
330   return BO;
331 }
332 
333 /// expandAddToGEP - Expand an addition expression with a pointer type into
334 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
335 /// BasicAliasAnalysis and other passes analyze the result. See the rules
336 /// for getelementptr vs. inttoptr in
337 /// http://llvm.org/docs/LangRef.html#pointeraliasing
338 /// for details.
339 ///
340 /// Design note: The correctness of using getelementptr here depends on
341 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
342 /// they may introduce pointer arithmetic which may not be safely converted
343 /// into getelementptr.
344 ///
345 /// Design note: It might seem desirable for this function to be more
346 /// loop-aware. If some of the indices are loop-invariant while others
347 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
348 /// loop-invariant portions of the overall computation outside the loop.
349 /// However, there are a few reasons this is not done here. Hoisting simple
350 /// arithmetic is a low-level optimization that often isn't very
351 /// important until late in the optimization process. In fact, passes
352 /// like InstructionCombining will combine GEPs, even if it means
353 /// pushing loop-invariant computation down into loops, so even if the
354 /// GEPs were split here, the work would quickly be undone. The
355 /// LoopStrengthReduction pass, which is usually run quite late (and
356 /// after the last InstructionCombining pass), takes care of hoisting
357 /// loop-invariant portions of expressions, after considering what
358 /// can be folded using target addressing modes.
359 ///
360 Value *SCEVExpander::expandAddToGEP(const SCEV *Offset, Value *V,
361                                     SCEV::NoWrapFlags Flags) {
362   assert(!isa<Instruction>(V) ||
363          SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
364 
365   Value *Idx = expand(Offset);
366   GEPNoWrapFlags NW = (Flags & SCEV::FlagNUW) ? GEPNoWrapFlags::noUnsignedWrap()
367                                               : GEPNoWrapFlags::none();
368 
369   // Fold a GEP with constant operands.
370   if (Constant *CLHS = dyn_cast<Constant>(V))
371     if (Constant *CRHS = dyn_cast<Constant>(Idx))
372       return Builder.CreatePtrAdd(CLHS, CRHS, "", NW);
373 
374   // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
375   unsigned ScanLimit = 6;
376   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
377   // Scanning starts from the last instruction before the insertion point.
378   BasicBlock::iterator IP = Builder.GetInsertPoint();
379   if (IP != BlockBegin) {
380     --IP;
381     for (; ScanLimit; --IP, --ScanLimit) {
382       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
383       // generated code.
384       if (isa<DbgInfoIntrinsic>(IP))
385         ScanLimit++;
386       if (auto *GEP = dyn_cast<GetElementPtrInst>(IP)) {
387         if (GEP->getPointerOperand() == V &&
388             GEP->getSourceElementType() == Builder.getInt8Ty() &&
389             GEP->getOperand(1) == Idx) {
390           rememberFlags(GEP);
391           GEP->setNoWrapFlags(GEP->getNoWrapFlags() & NW);
392           return &*IP;
393         }
394       }
395       if (IP == BlockBegin) break;
396     }
397   }
398 
399   // Save the original insertion point so we can restore it when we're done.
400   SCEVInsertPointGuard Guard(Builder, this);
401 
402   // Move the insertion point out of as many loops as we can.
403   while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
404     if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
405     BasicBlock *Preheader = L->getLoopPreheader();
406     if (!Preheader) break;
407 
408     // Ok, move up a level.
409     Builder.SetInsertPoint(Preheader->getTerminator());
410   }
411 
412   // Emit a GEP.
413   return Builder.CreatePtrAdd(V, Idx, "scevgep", NW);
414 }
415 
416 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
417 /// SCEV expansion. If they are nested, this is the most nested. If they are
418 /// neighboring, pick the later.
419 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
420                                         DominatorTree &DT) {
421   if (!A) return B;
422   if (!B) return A;
423   if (A->contains(B)) return B;
424   if (B->contains(A)) return A;
425   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
426   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
427   return A; // Arbitrarily break the tie.
428 }
429 
430 /// getRelevantLoop - Get the most relevant loop associated with the given
431 /// expression, according to PickMostRelevantLoop.
432 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
433   // Test whether we've already computed the most relevant loop for this SCEV.
434   auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
435   if (!Pair.second)
436     return Pair.first->second;
437 
438   switch (S->getSCEVType()) {
439   case scConstant:
440   case scVScale:
441     return nullptr; // A constant has no relevant loops.
442   case scTruncate:
443   case scZeroExtend:
444   case scSignExtend:
445   case scPtrToInt:
446   case scAddExpr:
447   case scMulExpr:
448   case scUDivExpr:
449   case scAddRecExpr:
450   case scUMaxExpr:
451   case scSMaxExpr:
452   case scUMinExpr:
453   case scSMinExpr:
454   case scSequentialUMinExpr: {
455     const Loop *L = nullptr;
456     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
457       L = AR->getLoop();
458     for (const SCEV *Op : S->operands())
459       L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
460     return RelevantLoops[S] = L;
461   }
462   case scUnknown: {
463     const SCEVUnknown *U = cast<SCEVUnknown>(S);
464     if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
465       return Pair.first->second = SE.LI.getLoopFor(I->getParent());
466     // A non-instruction has no relevant loops.
467     return nullptr;
468   }
469   case scCouldNotCompute:
470     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
471   }
472   llvm_unreachable("Unexpected SCEV type!");
473 }
474 
475 namespace {
476 
477 /// LoopCompare - Compare loops by PickMostRelevantLoop.
478 class LoopCompare {
479   DominatorTree &DT;
480 public:
481   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
482 
483   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
484                   std::pair<const Loop *, const SCEV *> RHS) const {
485     // Keep pointer operands sorted at the end.
486     if (LHS.second->getType()->isPointerTy() !=
487         RHS.second->getType()->isPointerTy())
488       return LHS.second->getType()->isPointerTy();
489 
490     // Compare loops with PickMostRelevantLoop.
491     if (LHS.first != RHS.first)
492       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
493 
494     // If one operand is a non-constant negative and the other is not,
495     // put the non-constant negative on the right so that a sub can
496     // be used instead of a negate and add.
497     if (LHS.second->isNonConstantNegative()) {
498       if (!RHS.second->isNonConstantNegative())
499         return false;
500     } else if (RHS.second->isNonConstantNegative())
501       return true;
502 
503     // Otherwise they are equivalent according to this comparison.
504     return false;
505   }
506 };
507 
508 }
509 
510 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
511   // Recognize the canonical representation of an unsimplifed urem.
512   const SCEV *URemLHS = nullptr;
513   const SCEV *URemRHS = nullptr;
514   if (SE.matchURem(S, URemLHS, URemRHS)) {
515     Value *LHS = expand(URemLHS);
516     Value *RHS = expand(URemRHS);
517     return InsertBinop(Instruction::URem, LHS, RHS, SCEV::FlagAnyWrap,
518                       /*IsSafeToHoist*/ false);
519   }
520 
521   // Collect all the add operands in a loop, along with their associated loops.
522   // Iterate in reverse so that constants are emitted last, all else equal, and
523   // so that pointer operands are inserted first, which the code below relies on
524   // to form more involved GEPs.
525   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
526   for (const SCEV *Op : reverse(S->operands()))
527     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
528 
529   // Sort by loop. Use a stable sort so that constants follow non-constants and
530   // pointer operands precede non-pointer operands.
531   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
532 
533   // Emit instructions to add all the operands. Hoist as much as possible
534   // out of loops, and form meaningful getelementptrs where possible.
535   Value *Sum = nullptr;
536   for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
537     const Loop *CurLoop = I->first;
538     const SCEV *Op = I->second;
539     if (!Sum) {
540       // This is the first operand. Just expand it.
541       Sum = expand(Op);
542       ++I;
543       continue;
544     }
545 
546     assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
547     if (isa<PointerType>(Sum->getType())) {
548       // The running sum expression is a pointer. Try to form a getelementptr
549       // at this level with that as the base.
550       SmallVector<const SCEV *, 4> NewOps;
551       for (; I != E && I->first == CurLoop; ++I) {
552         // If the operand is SCEVUnknown and not instructions, peek through
553         // it, to enable more of it to be folded into the GEP.
554         const SCEV *X = I->second;
555         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
556           if (!isa<Instruction>(U->getValue()))
557             X = SE.getSCEV(U->getValue());
558         NewOps.push_back(X);
559       }
560       Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum, S->getNoWrapFlags());
561     } else if (Op->isNonConstantNegative()) {
562       // Instead of doing a negate and add, just do a subtract.
563       Value *W = expand(SE.getNegativeSCEV(Op));
564       Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
565                         /*IsSafeToHoist*/ true);
566       ++I;
567     } else {
568       // A simple add.
569       Value *W = expand(Op);
570       // Canonicalize a constant to the RHS.
571       if (isa<Constant>(Sum))
572         std::swap(Sum, W);
573       Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
574                         /*IsSafeToHoist*/ true);
575       ++I;
576     }
577   }
578 
579   return Sum;
580 }
581 
582 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
583   Type *Ty = S->getType();
584 
585   // Collect all the mul operands in a loop, along with their associated loops.
586   // Iterate in reverse so that constants are emitted last, all else equal.
587   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
588   for (const SCEV *Op : reverse(S->operands()))
589     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
590 
591   // Sort by loop. Use a stable sort so that constants follow non-constants.
592   llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
593 
594   // Emit instructions to mul all the operands. Hoist as much as possible
595   // out of loops.
596   Value *Prod = nullptr;
597   auto I = OpsAndLoops.begin();
598 
599   // Expand the calculation of X pow N in the following manner:
600   // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
601   // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
602   const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() {
603     auto E = I;
604     // Calculate how many times the same operand from the same loop is included
605     // into this power.
606     uint64_t Exponent = 0;
607     const uint64_t MaxExponent = UINT64_MAX >> 1;
608     // No one sane will ever try to calculate such huge exponents, but if we
609     // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
610     // below when the power of 2 exceeds our Exponent, and we want it to be
611     // 1u << 31 at most to not deal with unsigned overflow.
612     while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
613       ++Exponent;
614       ++E;
615     }
616     assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
617 
618     // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
619     // that are needed into the result.
620     Value *P = expand(I->second);
621     Value *Result = nullptr;
622     if (Exponent & 1)
623       Result = P;
624     for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
625       P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
626                       /*IsSafeToHoist*/ true);
627       if (Exponent & BinExp)
628         Result = Result ? InsertBinop(Instruction::Mul, Result, P,
629                                       SCEV::FlagAnyWrap,
630                                       /*IsSafeToHoist*/ true)
631                         : P;
632     }
633 
634     I = E;
635     assert(Result && "Nothing was expanded?");
636     return Result;
637   };
638 
639   while (I != OpsAndLoops.end()) {
640     if (!Prod) {
641       // This is the first operand. Just expand it.
642       Prod = ExpandOpBinPowN();
643     } else if (I->second->isAllOnesValue()) {
644       // Instead of doing a multiply by negative one, just do a negate.
645       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
646                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
647       ++I;
648     } else {
649       // A simple mul.
650       Value *W = ExpandOpBinPowN();
651       // Canonicalize a constant to the RHS.
652       if (isa<Constant>(Prod)) std::swap(Prod, W);
653       const APInt *RHS;
654       if (match(W, m_Power2(RHS))) {
655         // Canonicalize Prod*(1<<C) to Prod<<C.
656         assert(!Ty->isVectorTy() && "vector types are not SCEVable");
657         auto NWFlags = S->getNoWrapFlags();
658         // clear nsw flag if shl will produce poison value.
659         if (RHS->logBase2() == RHS->getBitWidth() - 1)
660           NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
661         Prod = InsertBinop(Instruction::Shl, Prod,
662                            ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
663                            /*IsSafeToHoist*/ true);
664       } else {
665         Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
666                            /*IsSafeToHoist*/ true);
667       }
668     }
669   }
670 
671   return Prod;
672 }
673 
674 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
675   Value *LHS = expand(S->getLHS());
676   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
677     const APInt &RHS = SC->getAPInt();
678     if (RHS.isPowerOf2())
679       return InsertBinop(Instruction::LShr, LHS,
680                          ConstantInt::get(SC->getType(), RHS.logBase2()),
681                          SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
682   }
683 
684   Value *RHS = expand(S->getRHS());
685   return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
686                      /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
687 }
688 
689 /// Determine if this is a well-behaved chain of instructions leading back to
690 /// the PHI. If so, it may be reused by expanded expressions.
691 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
692                                          const Loop *L) {
693   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
694       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
695     return false;
696   // If any of the operands don't dominate the insert position, bail.
697   // Addrec operands are always loop-invariant, so this can only happen
698   // if there are instructions which haven't been hoisted.
699   if (L == IVIncInsertLoop) {
700     for (Use &Op : llvm::drop_begin(IncV->operands()))
701       if (Instruction *OInst = dyn_cast<Instruction>(Op))
702         if (!SE.DT.dominates(OInst, IVIncInsertPos))
703           return false;
704   }
705   // Advance to the next instruction.
706   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
707   if (!IncV)
708     return false;
709 
710   if (IncV->mayHaveSideEffects())
711     return false;
712 
713   if (IncV == PN)
714     return true;
715 
716   return isNormalAddRecExprPHI(PN, IncV, L);
717 }
718 
719 /// getIVIncOperand returns an induction variable increment's induction
720 /// variable operand.
721 ///
722 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
723 /// operands dominate InsertPos.
724 ///
725 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
726 /// simple patterns generated by getAddRecExprPHILiterally and
727 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
728 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
729                                            Instruction *InsertPos,
730                                            bool allowScale) {
731   if (IncV == InsertPos)
732     return nullptr;
733 
734   switch (IncV->getOpcode()) {
735   default:
736     return nullptr;
737   // Check for a simple Add/Sub or GEP of a loop invariant step.
738   case Instruction::Add:
739   case Instruction::Sub: {
740     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
741     if (!OInst || SE.DT.dominates(OInst, InsertPos))
742       return dyn_cast<Instruction>(IncV->getOperand(0));
743     return nullptr;
744   }
745   case Instruction::BitCast:
746     return dyn_cast<Instruction>(IncV->getOperand(0));
747   case Instruction::GetElementPtr:
748     for (Use &U : llvm::drop_begin(IncV->operands())) {
749       if (isa<Constant>(U))
750         continue;
751       if (Instruction *OInst = dyn_cast<Instruction>(U)) {
752         if (!SE.DT.dominates(OInst, InsertPos))
753           return nullptr;
754       }
755       if (allowScale) {
756         // allow any kind of GEP as long as it can be hoisted.
757         continue;
758       }
759       // GEPs produced by SCEVExpander use i8 element type.
760       if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
761         return nullptr;
762       break;
763     }
764     return dyn_cast<Instruction>(IncV->getOperand(0));
765   }
766 }
767 
768 /// If the insert point of the current builder or any of the builders on the
769 /// stack of saved builders has 'I' as its insert point, update it to point to
770 /// the instruction after 'I'.  This is intended to be used when the instruction
771 /// 'I' is being moved.  If this fixup is not done and 'I' is moved to a
772 /// different block, the inconsistent insert point (with a mismatched
773 /// Instruction and Block) can lead to an instruction being inserted in a block
774 /// other than its parent.
775 void SCEVExpander::fixupInsertPoints(Instruction *I) {
776   BasicBlock::iterator It(*I);
777   BasicBlock::iterator NewInsertPt = std::next(It);
778   if (Builder.GetInsertPoint() == It)
779     Builder.SetInsertPoint(&*NewInsertPt);
780   for (auto *InsertPtGuard : InsertPointGuards)
781     if (InsertPtGuard->GetInsertPoint() == It)
782       InsertPtGuard->SetInsertPoint(NewInsertPt);
783 }
784 
785 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
786 /// it available to other uses in this loop. Recursively hoist any operands,
787 /// until we reach a value that dominates InsertPos.
788 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos,
789                               bool RecomputePoisonFlags) {
790   auto FixupPoisonFlags = [this](Instruction *I) {
791     // Drop flags that are potentially inferred from old context and infer flags
792     // in new context.
793     rememberFlags(I);
794     I->dropPoisonGeneratingFlags();
795     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
796       if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
797         auto *BO = cast<BinaryOperator>(I);
798         BO->setHasNoUnsignedWrap(
799             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW);
800         BO->setHasNoSignedWrap(
801             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW);
802       }
803   };
804 
805   if (SE.DT.dominates(IncV, InsertPos)) {
806     if (RecomputePoisonFlags)
807       FixupPoisonFlags(IncV);
808     return true;
809   }
810 
811   // InsertPos must itself dominate IncV so that IncV's new position satisfies
812   // its existing users.
813   if (isa<PHINode>(InsertPos) ||
814       !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
815     return false;
816 
817   if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
818     return false;
819 
820   // Check that the chain of IV operands leading back to Phi can be hoisted.
821   SmallVector<Instruction*, 4> IVIncs;
822   for(;;) {
823     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
824     if (!Oper)
825       return false;
826     // IncV is safe to hoist.
827     IVIncs.push_back(IncV);
828     IncV = Oper;
829     if (SE.DT.dominates(IncV, InsertPos))
830       break;
831   }
832   for (Instruction *I : llvm::reverse(IVIncs)) {
833     fixupInsertPoints(I);
834     I->moveBefore(InsertPos);
835     if (RecomputePoisonFlags)
836       FixupPoisonFlags(I);
837   }
838   return true;
839 }
840 
841 bool SCEVExpander::canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi,
842                                                   PHINode *WidePhi,
843                                                   Instruction *OrigInc,
844                                                   Instruction *WideInc) {
845   return match(OrigInc, m_c_BinOp(m_Specific(OrigPhi), m_Value())) &&
846          match(WideInc, m_c_BinOp(m_Specific(WidePhi), m_Value())) &&
847          OrigInc->getOpcode() == WideInc->getOpcode();
848 }
849 
850 /// Determine if this cyclic phi is in a form that would have been generated by
851 /// LSR. We don't care if the phi was actually expanded in this pass, as long
852 /// as it is in a low-cost form, for example, no implied multiplication. This
853 /// should match any patterns generated by getAddRecExprPHILiterally and
854 /// expandAddtoGEP.
855 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
856                                            const Loop *L) {
857   for(Instruction *IVOper = IncV;
858       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
859                                 /*allowScale=*/false));) {
860     if (IVOper == PN)
861       return true;
862   }
863   return false;
864 }
865 
866 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
867 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
868 /// need to materialize IV increments elsewhere to handle difficult situations.
869 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
870                                  bool useSubtract) {
871   Value *IncV;
872   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
873   if (PN->getType()->isPointerTy()) {
874     // TODO: Change name to IVName.iv.next.
875     IncV = Builder.CreatePtrAdd(PN, StepV, "scevgep");
876   } else {
877     IncV = useSubtract ?
878       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
879       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
880   }
881   return IncV;
882 }
883 
884 /// Check whether we can cheaply express the requested SCEV in terms of
885 /// the available PHI SCEV by truncation and/or inversion of the step.
886 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
887                                     const SCEVAddRecExpr *Phi,
888                                     const SCEVAddRecExpr *Requested,
889                                     bool &InvertStep) {
890   // We can't transform to match a pointer PHI.
891   Type *PhiTy = Phi->getType();
892   Type *RequestedTy = Requested->getType();
893   if (PhiTy->isPointerTy() || RequestedTy->isPointerTy())
894     return false;
895 
896   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
897     return false;
898 
899   // Try truncate it if necessary.
900   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
901   if (!Phi)
902     return false;
903 
904   // Check whether truncation will help.
905   if (Phi == Requested) {
906     InvertStep = false;
907     return true;
908   }
909 
910   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
911   if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
912     InvertStep = true;
913     return true;
914   }
915 
916   return false;
917 }
918 
919 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
920   if (!isa<IntegerType>(AR->getType()))
921     return false;
922 
923   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
924   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
925   const SCEV *Step = AR->getStepRecurrence(SE);
926   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
927                                             SE.getSignExtendExpr(AR, WideTy));
928   const SCEV *ExtendAfterOp =
929     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
930   return ExtendAfterOp == OpAfterExtend;
931 }
932 
933 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
934   if (!isa<IntegerType>(AR->getType()))
935     return false;
936 
937   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
938   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
939   const SCEV *Step = AR->getStepRecurrence(SE);
940   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
941                                             SE.getZeroExtendExpr(AR, WideTy));
942   const SCEV *ExtendAfterOp =
943     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
944   return ExtendAfterOp == OpAfterExtend;
945 }
946 
947 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
948 /// the base addrec, which is the addrec without any non-loop-dominating
949 /// values, and return the PHI.
950 PHINode *
951 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
952                                         const Loop *L, Type *&TruncTy,
953                                         bool &InvertStep) {
954   assert((!IVIncInsertLoop || IVIncInsertPos) &&
955          "Uninitialized insert position");
956 
957   // Reuse a previously-inserted PHI, if present.
958   BasicBlock *LatchBlock = L->getLoopLatch();
959   if (LatchBlock) {
960     PHINode *AddRecPhiMatch = nullptr;
961     Instruction *IncV = nullptr;
962     TruncTy = nullptr;
963     InvertStep = false;
964 
965     // Only try partially matching scevs that need truncation and/or
966     // step-inversion if we know this loop is outside the current loop.
967     bool TryNonMatchingSCEV =
968         IVIncInsertLoop &&
969         SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
970 
971     for (PHINode &PN : L->getHeader()->phis()) {
972       if (!SE.isSCEVable(PN.getType()))
973         continue;
974 
975       // We should not look for a incomplete PHI. Getting SCEV for a incomplete
976       // PHI has no meaning at all.
977       if (!PN.isComplete()) {
978         SCEV_DEBUG_WITH_TYPE(
979             DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
980         continue;
981       }
982 
983       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
984       if (!PhiSCEV)
985         continue;
986 
987       bool IsMatchingSCEV = PhiSCEV == Normalized;
988       // We only handle truncation and inversion of phi recurrences for the
989       // expanded expression if the expanded expression's loop dominates the
990       // loop we insert to. Check now, so we can bail out early.
991       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
992           continue;
993 
994       // TODO: this possibly can be reworked to avoid this cast at all.
995       Instruction *TempIncV =
996           dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
997       if (!TempIncV)
998         continue;
999 
1000       // Check whether we can reuse this PHI node.
1001       if (LSRMode) {
1002         if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1003           continue;
1004       } else {
1005         if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1006           continue;
1007       }
1008 
1009       // Stop if we have found an exact match SCEV.
1010       if (IsMatchingSCEV) {
1011         IncV = TempIncV;
1012         TruncTy = nullptr;
1013         InvertStep = false;
1014         AddRecPhiMatch = &PN;
1015         break;
1016       }
1017 
1018       // Try whether the phi can be translated into the requested form
1019       // (truncated and/or offset by a constant).
1020       if ((!TruncTy || InvertStep) &&
1021           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1022         // Record the phi node. But don't stop we might find an exact match
1023         // later.
1024         AddRecPhiMatch = &PN;
1025         IncV = TempIncV;
1026         TruncTy = Normalized->getType();
1027       }
1028     }
1029 
1030     if (AddRecPhiMatch) {
1031       // Ok, the add recurrence looks usable.
1032       // Remember this PHI, even in post-inc mode.
1033       InsertedValues.insert(AddRecPhiMatch);
1034       // Remember the increment.
1035       rememberInstruction(IncV);
1036       // Those values were not actually inserted but re-used.
1037       ReusedValues.insert(AddRecPhiMatch);
1038       ReusedValues.insert(IncV);
1039       return AddRecPhiMatch;
1040     }
1041   }
1042 
1043   // Save the original insertion point so we can restore it when we're done.
1044   SCEVInsertPointGuard Guard(Builder, this);
1045 
1046   // Another AddRec may need to be recursively expanded below. For example, if
1047   // this AddRec is quadratic, the StepV may itself be an AddRec in this
1048   // loop. Remove this loop from the PostIncLoops set before expanding such
1049   // AddRecs. Otherwise, we cannot find a valid position for the step
1050   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1051   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1052   // so it's not worth implementing SmallPtrSet::swap.
1053   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1054   PostIncLoops.clear();
1055 
1056   // Expand code for the start value into the loop preheader.
1057   assert(L->getLoopPreheader() &&
1058          "Can't expand add recurrences without a loop preheader!");
1059   Value *StartV =
1060       expand(Normalized->getStart(), L->getLoopPreheader()->getTerminator());
1061 
1062   // StartV must have been be inserted into L's preheader to dominate the new
1063   // phi.
1064   assert(!isa<Instruction>(StartV) ||
1065          SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1066                                  L->getHeader()));
1067 
1068   // Expand code for the step value. Do this before creating the PHI so that PHI
1069   // reuse code doesn't see an incomplete PHI.
1070   const SCEV *Step = Normalized->getStepRecurrence(SE);
1071   Type *ExpandTy = Normalized->getType();
1072   // If the stride is negative, insert a sub instead of an add for the increment
1073   // (unless it's a constant, because subtracts of constants are canonicalized
1074   // to adds).
1075   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1076   if (useSubtract)
1077     Step = SE.getNegativeSCEV(Step);
1078   // Expand the step somewhere that dominates the loop header.
1079   Value *StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1080 
1081   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1082   // we actually do emit an addition.  It does not apply if we emit a
1083   // subtraction.
1084   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1085   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1086 
1087   // Create the PHI.
1088   BasicBlock *Header = L->getHeader();
1089   Builder.SetInsertPoint(Header, Header->begin());
1090   PHINode *PN =
1091       Builder.CreatePHI(ExpandTy, pred_size(Header), Twine(IVName) + ".iv");
1092 
1093   // Create the step instructions and populate the PHI.
1094   for (BasicBlock *Pred : predecessors(Header)) {
1095     // Add a start value.
1096     if (!L->contains(Pred)) {
1097       PN->addIncoming(StartV, Pred);
1098       continue;
1099     }
1100 
1101     // Create a step value and add it to the PHI.
1102     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1103     // instructions at IVIncInsertPos.
1104     Instruction *InsertPos = L == IVIncInsertLoop ?
1105       IVIncInsertPos : Pred->getTerminator();
1106     Builder.SetInsertPoint(InsertPos);
1107     Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1108 
1109     if (isa<OverflowingBinaryOperator>(IncV)) {
1110       if (IncrementIsNUW)
1111         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1112       if (IncrementIsNSW)
1113         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1114     }
1115     PN->addIncoming(IncV, Pred);
1116   }
1117 
1118   // After expanding subexpressions, restore the PostIncLoops set so the caller
1119   // can ensure that IVIncrement dominates the current uses.
1120   PostIncLoops = SavedPostIncLoops;
1121 
1122   // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
1123   // effective when we are able to use an IV inserted here, so record it.
1124   InsertedValues.insert(PN);
1125   InsertedIVs.push_back(PN);
1126   return PN;
1127 }
1128 
1129 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1130   const Loop *L = S->getLoop();
1131 
1132   // Determine a normalized form of this expression, which is the expression
1133   // before any post-inc adjustment is made.
1134   const SCEVAddRecExpr *Normalized = S;
1135   if (PostIncLoops.count(L)) {
1136     PostIncLoopSet Loops;
1137     Loops.insert(L);
1138     Normalized = cast<SCEVAddRecExpr>(
1139         normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false));
1140   }
1141 
1142   [[maybe_unused]] const SCEV *Start = Normalized->getStart();
1143   const SCEV *Step = Normalized->getStepRecurrence(SE);
1144   assert(SE.properlyDominates(Start, L->getHeader()) &&
1145          "Start does not properly dominate loop header");
1146   assert(SE.dominates(Step, L->getHeader()) && "Step not dominate loop header");
1147 
1148   // In some cases, we decide to reuse an existing phi node but need to truncate
1149   // it and/or invert the step.
1150   Type *TruncTy = nullptr;
1151   bool InvertStep = false;
1152   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1153 
1154   // Accommodate post-inc mode, if necessary.
1155   Value *Result;
1156   if (!PostIncLoops.count(L))
1157     Result = PN;
1158   else {
1159     // In PostInc mode, use the post-incremented value.
1160     BasicBlock *LatchBlock = L->getLoopLatch();
1161     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1162     Result = PN->getIncomingValueForBlock(LatchBlock);
1163 
1164     // We might be introducing a new use of the post-inc IV that is not poison
1165     // safe, in which case we should drop poison generating flags. Only keep
1166     // those flags for which SCEV has proven that they always hold.
1167     if (isa<OverflowingBinaryOperator>(Result)) {
1168       auto *I = cast<Instruction>(Result);
1169       if (!S->hasNoUnsignedWrap())
1170         I->setHasNoUnsignedWrap(false);
1171       if (!S->hasNoSignedWrap())
1172         I->setHasNoSignedWrap(false);
1173     }
1174 
1175     // For an expansion to use the postinc form, the client must call
1176     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1177     // or dominated by IVIncInsertPos.
1178     if (isa<Instruction>(Result) &&
1179         !SE.DT.dominates(cast<Instruction>(Result),
1180                          &*Builder.GetInsertPoint())) {
1181       // The induction variable's postinc expansion does not dominate this use.
1182       // IVUsers tries to prevent this case, so it is rare. However, it can
1183       // happen when an IVUser outside the loop is not dominated by the latch
1184       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1185       // all cases. Consider a phi outside whose operand is replaced during
1186       // expansion with the value of the postinc user. Without fundamentally
1187       // changing the way postinc users are tracked, the only remedy is
1188       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1189       // but hopefully expandCodeFor handles that.
1190       bool useSubtract =
1191           !S->getType()->isPointerTy() && Step->isNonConstantNegative();
1192       if (useSubtract)
1193         Step = SE.getNegativeSCEV(Step);
1194       Value *StepV;
1195       {
1196         // Expand the step somewhere that dominates the loop header.
1197         SCEVInsertPointGuard Guard(Builder, this);
1198         StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1199       }
1200       Result = expandIVInc(PN, StepV, L, useSubtract);
1201     }
1202   }
1203 
1204   // We have decided to reuse an induction variable of a dominating loop. Apply
1205   // truncation and/or inversion of the step.
1206   if (TruncTy) {
1207     // Truncate the result.
1208     if (TruncTy != Result->getType())
1209       Result = Builder.CreateTrunc(Result, TruncTy);
1210 
1211     // Invert the result.
1212     if (InvertStep)
1213       Result = Builder.CreateSub(expand(Normalized->getStart()), Result);
1214   }
1215 
1216   return Result;
1217 }
1218 
1219 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1220   // In canonical mode we compute the addrec as an expression of a canonical IV
1221   // using evaluateAtIteration and expand the resulting SCEV expression. This
1222   // way we avoid introducing new IVs to carry on the computation of the addrec
1223   // throughout the loop.
1224   //
1225   // For nested addrecs evaluateAtIteration might need a canonical IV of a
1226   // type wider than the addrec itself. Emitting a canonical IV of the
1227   // proper type might produce non-legal types, for example expanding an i64
1228   // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
1229   // back to non-canonical mode for nested addrecs.
1230   if (!CanonicalMode || (S->getNumOperands() > 2))
1231     return expandAddRecExprLiterally(S);
1232 
1233   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1234   const Loop *L = S->getLoop();
1235 
1236   // First check for an existing canonical IV in a suitable type.
1237   PHINode *CanonicalIV = nullptr;
1238   if (PHINode *PN = L->getCanonicalInductionVariable())
1239     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1240       CanonicalIV = PN;
1241 
1242   // Rewrite an AddRec in terms of the canonical induction variable, if
1243   // its type is more narrow.
1244   if (CanonicalIV &&
1245       SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
1246       !S->getType()->isPointerTy()) {
1247     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1248     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1249       NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType());
1250     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1251                                        S->getNoWrapFlags(SCEV::FlagNW)));
1252     BasicBlock::iterator NewInsertPt =
1253         findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
1254     V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
1255     return V;
1256   }
1257 
1258   // {X,+,F} --> X + {0,+,F}
1259   if (!S->getStart()->isZero()) {
1260     if (isa<PointerType>(S->getType())) {
1261       Value *StartV = expand(SE.getPointerBase(S));
1262       return expandAddToGEP(SE.removePointerBase(S), StartV,
1263                             S->getNoWrapFlags(SCEV::FlagNUW));
1264     }
1265 
1266     SmallVector<const SCEV *, 4> NewOps(S->operands());
1267     NewOps[0] = SE.getConstant(Ty, 0);
1268     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1269                                         S->getNoWrapFlags(SCEV::FlagNW));
1270 
1271     // Just do a normal add. Pre-expand the operands to suppress folding.
1272     //
1273     // The LHS and RHS values are factored out of the expand call to make the
1274     // output independent of the argument evaluation order.
1275     const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1276     const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1277     return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1278   }
1279 
1280   // If we don't yet have a canonical IV, create one.
1281   if (!CanonicalIV) {
1282     // Create and insert the PHI node for the induction variable in the
1283     // specified loop.
1284     BasicBlock *Header = L->getHeader();
1285     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1286     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar");
1287     CanonicalIV->insertBefore(Header->begin());
1288     rememberInstruction(CanonicalIV);
1289 
1290     SmallSet<BasicBlock *, 4> PredSeen;
1291     Constant *One = ConstantInt::get(Ty, 1);
1292     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1293       BasicBlock *HP = *HPI;
1294       if (!PredSeen.insert(HP).second) {
1295         // There must be an incoming value for each predecessor, even the
1296         // duplicates!
1297         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1298         continue;
1299       }
1300 
1301       if (L->contains(HP)) {
1302         // Insert a unit add instruction right before the terminator
1303         // corresponding to the back-edge.
1304         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1305                                                      "indvar.next",
1306                                                      HP->getTerminator()->getIterator());
1307         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1308         rememberInstruction(Add);
1309         CanonicalIV->addIncoming(Add, HP);
1310       } else {
1311         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1312       }
1313     }
1314   }
1315 
1316   // {0,+,1} --> Insert a canonical induction variable into the loop!
1317   if (S->isAffine() && S->getOperand(1)->isOne()) {
1318     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1319            "IVs with types different from the canonical IV should "
1320            "already have been handled!");
1321     return CanonicalIV;
1322   }
1323 
1324   // {0,+,F} --> {0,+,1} * F
1325 
1326   // If this is a simple linear addrec, emit it now as a special case.
1327   if (S->isAffine())    // {0,+,F} --> i*F
1328     return
1329       expand(SE.getTruncateOrNoop(
1330         SE.getMulExpr(SE.getUnknown(CanonicalIV),
1331                       SE.getNoopOrAnyExtend(S->getOperand(1),
1332                                             CanonicalIV->getType())),
1333         Ty));
1334 
1335   // If this is a chain of recurrences, turn it into a closed form, using the
1336   // folders, then expandCodeFor the closed form.  This allows the folders to
1337   // simplify the expression without having to build a bunch of special code
1338   // into this folder.
1339   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
1340 
1341   // Promote S up to the canonical IV type, if the cast is foldable.
1342   const SCEV *NewS = S;
1343   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1344   if (isa<SCEVAddRecExpr>(Ext))
1345     NewS = Ext;
1346 
1347   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1348 
1349   // Truncate the result down to the original type, if needed.
1350   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1351   return expand(T);
1352 }
1353 
1354 Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
1355   Value *V = expand(S->getOperand());
1356   return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
1357                            GetOptimalInsertionPointForCastOf(V));
1358 }
1359 
1360 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1361   Value *V = expand(S->getOperand());
1362   return Builder.CreateTrunc(V, S->getType());
1363 }
1364 
1365 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1366   Value *V = expand(S->getOperand());
1367   return Builder.CreateZExt(V, S->getType(), "",
1368                             SE.isKnownNonNegative(S->getOperand()));
1369 }
1370 
1371 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1372   Value *V = expand(S->getOperand());
1373   return Builder.CreateSExt(V, S->getType());
1374 }
1375 
1376 Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S,
1377                                       Intrinsic::ID IntrinID, Twine Name,
1378                                       bool IsSequential) {
1379   Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1380   Type *Ty = LHS->getType();
1381   if (IsSequential)
1382     LHS = Builder.CreateFreeze(LHS);
1383   for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1384     Value *RHS = expand(S->getOperand(i));
1385     if (IsSequential && i != 0)
1386       RHS = Builder.CreateFreeze(RHS);
1387     Value *Sel;
1388     if (Ty->isIntegerTy())
1389       Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
1390                                     /*FMFSource=*/nullptr, Name);
1391     else {
1392       Value *ICmp =
1393           Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
1394       Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name);
1395     }
1396     LHS = Sel;
1397   }
1398   return LHS;
1399 }
1400 
1401 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1402   return expandMinMaxExpr(S, Intrinsic::smax, "smax");
1403 }
1404 
1405 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1406   return expandMinMaxExpr(S, Intrinsic::umax, "umax");
1407 }
1408 
1409 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
1410   return expandMinMaxExpr(S, Intrinsic::smin, "smin");
1411 }
1412 
1413 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
1414   return expandMinMaxExpr(S, Intrinsic::umin, "umin");
1415 }
1416 
1417 Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) {
1418   return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true);
1419 }
1420 
1421 Value *SCEVExpander::visitVScale(const SCEVVScale *S) {
1422   return Builder.CreateVScale(ConstantInt::get(S->getType(), 1));
1423 }
1424 
1425 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1426                                    BasicBlock::iterator IP) {
1427   setInsertPoint(IP);
1428   Value *V = expandCodeFor(SH, Ty);
1429   return V;
1430 }
1431 
1432 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1433   // Expand the code for this SCEV.
1434   Value *V = expand(SH);
1435 
1436   if (Ty) {
1437     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1438            "non-trivial casts should be done with the SCEVs directly!");
1439     V = InsertNoopCastOfTo(V, Ty);
1440   }
1441   return V;
1442 }
1443 
1444 Value *SCEVExpander::FindValueInExprValueMap(
1445     const SCEV *S, const Instruction *InsertPt,
1446     SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
1447   // If the expansion is not in CanonicalMode, and the SCEV contains any
1448   // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1449   if (!CanonicalMode && SE.containsAddRecurrence(S))
1450     return nullptr;
1451 
1452   // If S is a constant, it may be worse to reuse an existing Value.
1453   if (isa<SCEVConstant>(S))
1454     return nullptr;
1455 
1456   for (Value *V : SE.getSCEVValues(S)) {
1457     Instruction *EntInst = dyn_cast<Instruction>(V);
1458     if (!EntInst)
1459       continue;
1460 
1461     // Choose a Value from the set which dominates the InsertPt.
1462     // InsertPt should be inside the Value's parent loop so as not to break
1463     // the LCSSA form.
1464     assert(EntInst->getFunction() == InsertPt->getFunction());
1465     if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) ||
1466         !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1467           SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1468       continue;
1469 
1470     // Make sure reusing the instruction is poison-safe.
1471     if (SE.canReuseInstruction(S, EntInst, DropPoisonGeneratingInsts))
1472       return V;
1473     DropPoisonGeneratingInsts.clear();
1474   }
1475   return nullptr;
1476 }
1477 
1478 // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1479 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1480 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1481 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1482 // the expansion will try to reuse Value from ExprValueMap, and only when it
1483 // fails, expand the SCEV literally.
1484 Value *SCEVExpander::expand(const SCEV *S) {
1485   // Compute an insertion point for this SCEV object. Hoist the instructions
1486   // as far out in the loop nest as possible.
1487   BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
1488 
1489   // We can move insertion point only if there is no div or rem operations
1490   // otherwise we are risky to move it over the check for zero denominator.
1491   auto SafeToHoist = [](const SCEV *S) {
1492     return !SCEVExprContains(S, [](const SCEV *S) {
1493               if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1494                 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1495                   // Division by non-zero constants can be hoisted.
1496                   return SC->getValue()->isZero();
1497                 // All other divisions should not be moved as they may be
1498                 // divisions by zero and should be kept within the
1499                 // conditions of the surrounding loops that guard their
1500                 // execution (see PR35406).
1501                 return true;
1502               }
1503               return false;
1504             });
1505   };
1506   if (SafeToHoist(S)) {
1507     for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1508          L = L->getParentLoop()) {
1509       if (SE.isLoopInvariant(S, L)) {
1510         if (!L) break;
1511         if (BasicBlock *Preheader = L->getLoopPreheader()) {
1512           InsertPt = Preheader->getTerminator()->getIterator();
1513         } else {
1514           // LSR sets the insertion point for AddRec start/step values to the
1515           // block start to simplify value reuse, even though it's an invalid
1516           // position. SCEVExpander must correct for this in all cases.
1517           InsertPt = L->getHeader()->getFirstInsertionPt();
1518         }
1519       } else {
1520         // If the SCEV is computable at this level, insert it into the header
1521         // after the PHIs (and after any other instructions that we've inserted
1522         // there) so that it is guaranteed to dominate any user inside the loop.
1523         if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1524           InsertPt = L->getHeader()->getFirstInsertionPt();
1525 
1526         while (InsertPt != Builder.GetInsertPoint() &&
1527                (isInsertedInstruction(&*InsertPt) ||
1528                 isa<DbgInfoIntrinsic>(&*InsertPt))) {
1529           InsertPt = std::next(InsertPt);
1530         }
1531         break;
1532       }
1533     }
1534   }
1535 
1536   // Check to see if we already expanded this here.
1537   auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1538   if (I != InsertedExpressions.end())
1539     return I->second;
1540 
1541   SCEVInsertPointGuard Guard(Builder, this);
1542   Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1543 
1544   // Expand the expression into instructions.
1545   SmallVector<Instruction *> DropPoisonGeneratingInsts;
1546   Value *V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1547   if (!V) {
1548     V = visit(S);
1549     V = fixupLCSSAFormFor(V);
1550   } else {
1551     for (Instruction *I : DropPoisonGeneratingInsts) {
1552       rememberFlags(I);
1553       I->dropPoisonGeneratingAnnotations();
1554       // See if we can re-infer from first principles any of the flags we just
1555       // dropped.
1556       if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
1557         if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1558           auto *BO = cast<BinaryOperator>(I);
1559           BO->setHasNoUnsignedWrap(
1560             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == SCEV::FlagNUW);
1561           BO->setHasNoSignedWrap(
1562             ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == SCEV::FlagNSW);
1563         }
1564       if (auto *NNI = dyn_cast<PossiblyNonNegInst>(I)) {
1565         auto *Src = NNI->getOperand(0);
1566         if (isImpliedByDomCondition(ICmpInst::ICMP_SGE, Src,
1567                                     Constant::getNullValue(Src->getType()), I,
1568                                     DL).value_or(false))
1569           NNI->setNonNeg(true);
1570       }
1571     }
1572   }
1573   // Remember the expanded value for this SCEV at this location.
1574   //
1575   // This is independent of PostIncLoops. The mapped value simply materializes
1576   // the expression at this insertion point. If the mapped value happened to be
1577   // a postinc expansion, it could be reused by a non-postinc user, but only if
1578   // its insertion point was already at the head of the loop.
1579   InsertedExpressions[std::make_pair(S, &*InsertPt)] = V;
1580   return V;
1581 }
1582 
1583 void SCEVExpander::rememberInstruction(Value *I) {
1584   auto DoInsert = [this](Value *V) {
1585     if (!PostIncLoops.empty())
1586       InsertedPostIncValues.insert(V);
1587     else
1588       InsertedValues.insert(V);
1589   };
1590   DoInsert(I);
1591 }
1592 
1593 void SCEVExpander::rememberFlags(Instruction *I) {
1594   // If we already have flags for the instruction, keep the existing ones.
1595   OrigFlags.try_emplace(I, PoisonFlags(I));
1596 }
1597 
1598 void SCEVExpander::replaceCongruentIVInc(
1599     PHINode *&Phi, PHINode *&OrigPhi, Loop *L, const DominatorTree *DT,
1600     SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
1601   BasicBlock *LatchBlock = L->getLoopLatch();
1602   if (!LatchBlock)
1603     return;
1604 
1605   Instruction *OrigInc =
1606       dyn_cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1607   Instruction *IsomorphicInc =
1608       dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1609   if (!OrigInc || !IsomorphicInc)
1610     return;
1611 
1612   // If this phi has the same width but is more canonical, replace the
1613   // original with it. As part of the "more canonical" determination,
1614   // respect a prior decision to use an IV chain.
1615   if (OrigPhi->getType() == Phi->getType() &&
1616       !(ChainedPhis.count(Phi) ||
1617         isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1618       (ChainedPhis.count(Phi) ||
1619        isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1620     std::swap(OrigPhi, Phi);
1621     std::swap(OrigInc, IsomorphicInc);
1622   }
1623 
1624   // Replacing the congruent phi is sufficient because acyclic
1625   // redundancy elimination, CSE/GVN, should handle the
1626   // rest. However, once SCEV proves that a phi is congruent,
1627   // it's often the head of an IV user cycle that is isomorphic
1628   // with the original phi. It's worth eagerly cleaning up the
1629   // common case of a single IV increment so that DeleteDeadPHIs
1630   // can remove cycles that had postinc uses.
1631   // Because we may potentially introduce a new use of OrigIV that didn't
1632   // exist before at this point, its poison flags need readjustment.
1633   const SCEV *TruncExpr =
1634       SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1635   if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) ||
1636       !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc))
1637     return;
1638 
1639   bool BothHaveNUW = false;
1640   bool BothHaveNSW = false;
1641   auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1642   auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1643   if (OBOIncV && OBOIsomorphic) {
1644     BothHaveNUW =
1645         OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1646     BothHaveNSW =
1647         OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1648   }
1649 
1650   if (!hoistIVInc(OrigInc, IsomorphicInc,
1651                   /*RecomputePoisonFlags*/ true))
1652     return;
1653 
1654   // We are replacing with a wider increment. If both OrigInc and IsomorphicInc
1655   // are NUW/NSW, then we can preserve them on the wider increment; the narrower
1656   // IsomorphicInc would wrap before the wider OrigInc, so the replacement won't
1657   // make IsomorphicInc's uses more poisonous.
1658   assert(OrigInc->getType()->getScalarSizeInBits() >=
1659              IsomorphicInc->getType()->getScalarSizeInBits() &&
1660          "Should only replace an increment with a wider one.");
1661   if (BothHaveNUW || BothHaveNSW) {
1662     OrigInc->setHasNoUnsignedWrap(OBOIncV->hasNoUnsignedWrap() || BothHaveNUW);
1663     OrigInc->setHasNoSignedWrap(OBOIncV->hasNoSignedWrap() || BothHaveNSW);
1664   }
1665 
1666   SCEV_DEBUG_WITH_TYPE(DebugType,
1667                        dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1668                               << *IsomorphicInc << '\n');
1669   Value *NewInc = OrigInc;
1670   if (OrigInc->getType() != IsomorphicInc->getType()) {
1671     BasicBlock::iterator IP;
1672     if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1673       IP = PN->getParent()->getFirstInsertionPt();
1674     else
1675       IP = OrigInc->getNextNonDebugInstruction()->getIterator();
1676 
1677     IRBuilder<> Builder(IP->getParent(), IP);
1678     Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1679     NewInc =
1680         Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1681   }
1682   IsomorphicInc->replaceAllUsesWith(NewInc);
1683   DeadInsts.emplace_back(IsomorphicInc);
1684 }
1685 
1686 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1687 /// replace them with their most canonical representative. Return the number of
1688 /// phis eliminated.
1689 ///
1690 /// This does not depend on any SCEVExpander state but should be used in
1691 /// the same context that SCEVExpander is used.
1692 unsigned
1693 SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1694                                   SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1695                                   const TargetTransformInfo *TTI) {
1696   // Find integer phis in order of increasing width.
1697   SmallVector<PHINode*, 8> Phis;
1698   for (PHINode &PN : L->getHeader()->phis())
1699     Phis.push_back(&PN);
1700 
1701   if (TTI)
1702     // Use stable_sort to preserve order of equivalent PHIs, so the order
1703     // of the sorted Phis is the same from run to run on the same loop.
1704     llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
1705       // Put pointers at the back and make sure pointer < pointer = false.
1706       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1707         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1708       return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1709              LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
1710     });
1711 
1712   unsigned NumElim = 0;
1713   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1714   // Process phis from wide to narrow. Map wide phis to their truncation
1715   // so narrow phis can reuse them.
1716   for (PHINode *Phi : Phis) {
1717     auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1718       if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1719         return V;
1720       if (!SE.isSCEVable(PN->getType()))
1721         return nullptr;
1722       auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1723       if (!Const)
1724         return nullptr;
1725       return Const->getValue();
1726     };
1727 
1728     // Fold constant phis. They may be congruent to other constant phis and
1729     // would confuse the logic below that expects proper IVs.
1730     if (Value *V = SimplifyPHINode(Phi)) {
1731       if (V->getType() != Phi->getType())
1732         continue;
1733       SE.forgetValue(Phi);
1734       Phi->replaceAllUsesWith(V);
1735       DeadInsts.emplace_back(Phi);
1736       ++NumElim;
1737       SCEV_DEBUG_WITH_TYPE(DebugType,
1738                            dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
1739                                   << '\n');
1740       continue;
1741     }
1742 
1743     if (!SE.isSCEVable(Phi->getType()))
1744       continue;
1745 
1746     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1747     if (!OrigPhiRef) {
1748       OrigPhiRef = Phi;
1749       if (Phi->getType()->isIntegerTy() && TTI &&
1750           TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1751         // Make sure we only rewrite using simple induction variables;
1752         // otherwise, we can make the trip count of a loop unanalyzable
1753         // to SCEV.
1754         const SCEV *PhiExpr = SE.getSCEV(Phi);
1755         if (isa<SCEVAddRecExpr>(PhiExpr)) {
1756           // This phi can be freely truncated to the narrowest phi type. Map the
1757           // truncated expression to it so it will be reused for narrow types.
1758           const SCEV *TruncExpr =
1759               SE.getTruncateExpr(PhiExpr, Phis.back()->getType());
1760           ExprToIVMap[TruncExpr] = Phi;
1761         }
1762       }
1763       continue;
1764     }
1765 
1766     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1767     // sense.
1768     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1769       continue;
1770 
1771     replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1772     SCEV_DEBUG_WITH_TYPE(DebugType,
1773                          dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
1774                                 << '\n');
1775     SCEV_DEBUG_WITH_TYPE(
1776         DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
1777     ++NumElim;
1778     Value *NewIV = OrigPhiRef;
1779     if (OrigPhiRef->getType() != Phi->getType()) {
1780       IRBuilder<> Builder(L->getHeader(),
1781                           L->getHeader()->getFirstInsertionPt());
1782       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1783       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1784     }
1785     Phi->replaceAllUsesWith(NewIV);
1786     DeadInsts.emplace_back(Phi);
1787   }
1788   return NumElim;
1789 }
1790 
1791 bool SCEVExpander::hasRelatedExistingExpansion(const SCEV *S,
1792                                                const Instruction *At,
1793                                                Loop *L) {
1794   using namespace llvm::PatternMatch;
1795 
1796   SmallVector<BasicBlock *, 4> ExitingBlocks;
1797   L->getExitingBlocks(ExitingBlocks);
1798 
1799   // Look for suitable value in simple conditions at the loop exits.
1800   for (BasicBlock *BB : ExitingBlocks) {
1801     ICmpInst::Predicate Pred;
1802     Instruction *LHS, *RHS;
1803 
1804     if (!match(BB->getTerminator(),
1805                m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1806                     m_BasicBlock(), m_BasicBlock())))
1807       continue;
1808 
1809     if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1810       return true;
1811 
1812     if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1813       return true;
1814   }
1815 
1816   // Use expand's logic which is used for reusing a previous Value in
1817   // ExprValueMap.  Note that we don't currently model the cost of
1818   // needing to drop poison generating flags on the instruction if we
1819   // want to reuse it.  We effectively assume that has zero cost.
1820   SmallVector<Instruction *> DropPoisonGeneratingInsts;
1821   return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr;
1822 }
1823 
1824 template<typename T> static InstructionCost costAndCollectOperands(
1825   const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
1826   TargetTransformInfo::TargetCostKind CostKind,
1827   SmallVectorImpl<SCEVOperand> &Worklist) {
1828 
1829   const T *S = cast<T>(WorkItem.S);
1830   InstructionCost Cost = 0;
1831   // Object to help map SCEV operands to expanded IR instructions.
1832   struct OperationIndices {
1833     OperationIndices(unsigned Opc, size_t min, size_t max) :
1834       Opcode(Opc), MinIdx(min), MaxIdx(max) { }
1835     unsigned Opcode;
1836     size_t MinIdx;
1837     size_t MaxIdx;
1838   };
1839 
1840   // Collect the operations of all the instructions that will be needed to
1841   // expand the SCEVExpr. This is so that when we come to cost the operands,
1842   // we know what the generated user(s) will be.
1843   SmallVector<OperationIndices, 2> Operations;
1844 
1845   auto CastCost = [&](unsigned Opcode) -> InstructionCost {
1846     Operations.emplace_back(Opcode, 0, 0);
1847     return TTI.getCastInstrCost(Opcode, S->getType(),
1848                                 S->getOperand(0)->getType(),
1849                                 TTI::CastContextHint::None, CostKind);
1850   };
1851 
1852   auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
1853                        unsigned MinIdx = 0,
1854                        unsigned MaxIdx = 1) -> InstructionCost {
1855     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
1856     return NumRequired *
1857       TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
1858   };
1859 
1860   auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
1861                         unsigned MaxIdx) -> InstructionCost {
1862     Operations.emplace_back(Opcode, MinIdx, MaxIdx);
1863     Type *OpType = S->getType();
1864     return NumRequired * TTI.getCmpSelInstrCost(
1865                              Opcode, OpType, CmpInst::makeCmpResultType(OpType),
1866                              CmpInst::BAD_ICMP_PREDICATE, CostKind);
1867   };
1868 
1869   switch (S->getSCEVType()) {
1870   case scCouldNotCompute:
1871     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
1872   case scUnknown:
1873   case scConstant:
1874   case scVScale:
1875     return 0;
1876   case scPtrToInt:
1877     Cost = CastCost(Instruction::PtrToInt);
1878     break;
1879   case scTruncate:
1880     Cost = CastCost(Instruction::Trunc);
1881     break;
1882   case scZeroExtend:
1883     Cost = CastCost(Instruction::ZExt);
1884     break;
1885   case scSignExtend:
1886     Cost = CastCost(Instruction::SExt);
1887     break;
1888   case scUDivExpr: {
1889     unsigned Opcode = Instruction::UDiv;
1890     if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
1891       if (SC->getAPInt().isPowerOf2())
1892         Opcode = Instruction::LShr;
1893     Cost = ArithCost(Opcode, 1);
1894     break;
1895   }
1896   case scAddExpr:
1897     Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
1898     break;
1899   case scMulExpr:
1900     // TODO: this is a very pessimistic cost modelling for Mul,
1901     // because of Bin Pow algorithm actually used by the expander,
1902     // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
1903     Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
1904     break;
1905   case scSMaxExpr:
1906   case scUMaxExpr:
1907   case scSMinExpr:
1908   case scUMinExpr:
1909   case scSequentialUMinExpr: {
1910     // FIXME: should this ask the cost for Intrinsic's?
1911     // The reduction tree.
1912     Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
1913     Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
1914     switch (S->getSCEVType()) {
1915     case scSequentialUMinExpr: {
1916       // The safety net against poison.
1917       // FIXME: this is broken.
1918       Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
1919       Cost += ArithCost(Instruction::Or,
1920                         S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
1921       Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
1922       break;
1923     }
1924     default:
1925       assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
1926              "Unhandled SCEV expression type?");
1927       break;
1928     }
1929     break;
1930   }
1931   case scAddRecExpr: {
1932     // Addrec expands to a phi and add per recurrence.
1933     unsigned NumRecurrences = S->getNumOperands() - 1;
1934     Cost += TTI.getCFInstrCost(Instruction::PHI, CostKind) * NumRecurrences;
1935     Cost +=
1936         TTI.getArithmeticInstrCost(Instruction::Add, S->getType(), CostKind) *
1937         NumRecurrences;
1938     // AR start is used in phi.
1939     Worklist.emplace_back(Instruction::PHI, 0, S->getOperand(0));
1940     // Other operands are used in add.
1941     for (const SCEV *Op : S->operands().drop_front())
1942       Worklist.emplace_back(Instruction::Add, 1, Op);
1943     break;
1944   }
1945   }
1946 
1947   for (auto &CostOp : Operations) {
1948     for (auto SCEVOp : enumerate(S->operands())) {
1949       // Clamp the index to account for multiple IR operations being chained.
1950       size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
1951       size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
1952       Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
1953     }
1954   }
1955   return Cost;
1956 }
1957 
1958 bool SCEVExpander::isHighCostExpansionHelper(
1959     const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
1960     InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
1961     SmallPtrSetImpl<const SCEV *> &Processed,
1962     SmallVectorImpl<SCEVOperand> &Worklist) {
1963   if (Cost > Budget)
1964     return true; // Already run out of budget, give up.
1965 
1966   const SCEV *S = WorkItem.S;
1967   // Was the cost of expansion of this expression already accounted for?
1968   if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
1969     return false; // We have already accounted for this expression.
1970 
1971   // If we can find an existing value for this scev available at the point "At"
1972   // then consider the expression cheap.
1973   if (hasRelatedExistingExpansion(S, &At, L))
1974     return false; // Consider the expression to be free.
1975 
1976   TargetTransformInfo::TargetCostKind CostKind =
1977       L->getHeader()->getParent()->hasMinSize()
1978           ? TargetTransformInfo::TCK_CodeSize
1979           : TargetTransformInfo::TCK_RecipThroughput;
1980 
1981   switch (S->getSCEVType()) {
1982   case scCouldNotCompute:
1983     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
1984   case scUnknown:
1985   case scVScale:
1986     // Assume to be zero-cost.
1987     return false;
1988   case scConstant: {
1989     // Only evalulate the costs of constants when optimizing for size.
1990     if (CostKind != TargetTransformInfo::TCK_CodeSize)
1991       return false;
1992     const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
1993     Type *Ty = S->getType();
1994     Cost += TTI.getIntImmCostInst(
1995         WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
1996     return Cost > Budget;
1997   }
1998   case scTruncate:
1999   case scPtrToInt:
2000   case scZeroExtend:
2001   case scSignExtend: {
2002     Cost +=
2003         costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
2004     return false; // Will answer upon next entry into this function.
2005   }
2006   case scUDivExpr: {
2007     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2008     // HowManyLessThans produced to compute a precise expression, rather than a
2009     // UDiv from the user's code. If we can't find a UDiv in the code with some
2010     // simple searching, we need to account for it's cost.
2011 
2012     // At the beginning of this function we already tried to find existing
2013     // value for plain 'S'. Now try to lookup 'S + 1' since it is common
2014     // pattern involving division. This is just a simple search heuristic.
2015     if (hasRelatedExistingExpansion(
2016             SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
2017       return false; // Consider it to be free.
2018 
2019     Cost +=
2020         costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
2021     return false; // Will answer upon next entry into this function.
2022   }
2023   case scAddExpr:
2024   case scMulExpr:
2025   case scUMaxExpr:
2026   case scSMaxExpr:
2027   case scUMinExpr:
2028   case scSMinExpr:
2029   case scSequentialUMinExpr: {
2030     assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2031            "Nary expr should have more than 1 operand.");
2032     // The simple nary expr will require one less op (or pair of ops)
2033     // than the number of it's terms.
2034     Cost +=
2035         costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
2036     return Cost > Budget;
2037   }
2038   case scAddRecExpr: {
2039     assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2040            "Polynomial should be at least linear");
2041     Cost += costAndCollectOperands<SCEVAddRecExpr>(
2042         WorkItem, TTI, CostKind, Worklist);
2043     return Cost > Budget;
2044   }
2045   }
2046   llvm_unreachable("Unknown SCEV kind!");
2047 }
2048 
2049 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2050                                             Instruction *IP) {
2051   assert(IP);
2052   switch (Pred->getKind()) {
2053   case SCEVPredicate::P_Union:
2054     return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2055   case SCEVPredicate::P_Compare:
2056     return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP);
2057   case SCEVPredicate::P_Wrap: {
2058     auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2059     return expandWrapPredicate(AddRecPred, IP);
2060   }
2061   }
2062   llvm_unreachable("Unknown SCEV predicate type");
2063 }
2064 
2065 Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred,
2066                                             Instruction *IP) {
2067   Value *Expr0 = expand(Pred->getLHS(), IP);
2068   Value *Expr1 = expand(Pred->getRHS(), IP);
2069 
2070   Builder.SetInsertPoint(IP);
2071   auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
2072   auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
2073   return I;
2074 }
2075 
2076 Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2077                                            Instruction *Loc, bool Signed) {
2078   assert(AR->isAffine() && "Cannot generate RT check for "
2079                            "non-affine expression");
2080 
2081   // FIXME: It is highly suspicious that we're ignoring the predicates here.
2082   SmallVector<const SCEVPredicate *, 4> Pred;
2083   const SCEV *ExitCount =
2084       SE.getPredicatedSymbolicMaxBackedgeTakenCount(AR->getLoop(), Pred);
2085 
2086   assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
2087 
2088   const SCEV *Step = AR->getStepRecurrence(SE);
2089   const SCEV *Start = AR->getStart();
2090 
2091   Type *ARTy = AR->getType();
2092   unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2093   unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2094 
2095   // The expression {Start,+,Step} has nusw/nssw if
2096   //   Step < 0, Start - |Step| * Backedge <= Start
2097   //   Step >= 0, Start + |Step| * Backedge > Start
2098   // and |Step| * Backedge doesn't unsigned overflow.
2099 
2100   Builder.SetInsertPoint(Loc);
2101   Value *TripCountVal = expand(ExitCount, Loc);
2102 
2103   IntegerType *Ty =
2104       IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2105 
2106   Value *StepValue = expand(Step, Loc);
2107   Value *NegStepValue = expand(SE.getNegativeSCEV(Step), Loc);
2108   Value *StartValue = expand(Start, Loc);
2109 
2110   ConstantInt *Zero =
2111       ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
2112 
2113   Builder.SetInsertPoint(Loc);
2114   // Compute |Step|
2115   Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2116   Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2117 
2118   // Compute |Step| * Backedge
2119   // Compute:
2120   //   1. Start + |Step| * Backedge < Start
2121   //   2. Start - |Step| * Backedge > Start
2122   //
2123   // And select either 1. or 2. depending on whether step is positive or
2124   // negative. If Step is known to be positive or negative, only create
2125   // either 1. or 2.
2126   auto ComputeEndCheck = [&]() -> Value * {
2127     // Checking <u 0 is always false.
2128     if (!Signed && Start->isZero() && SE.isKnownPositive(Step))
2129       return ConstantInt::getFalse(Loc->getContext());
2130 
2131     // Get the backedge taken count and truncate or extended to the AR type.
2132     Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2133 
2134     Value *MulV, *OfMul;
2135     if (Step->isOne()) {
2136       // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't
2137       // needed, there is never an overflow, so to avoid artificially inflating
2138       // the cost of the check, directly emit the optimized IR.
2139       MulV = TruncTripCount;
2140       OfMul = ConstantInt::getFalse(MulV->getContext());
2141     } else {
2142       auto *MulF = Intrinsic::getOrInsertDeclaration(
2143           Loc->getModule(), Intrinsic::umul_with_overflow, Ty);
2144       CallInst *Mul =
2145           Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2146       MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2147       OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2148     }
2149 
2150     Value *Add = nullptr, *Sub = nullptr;
2151     bool NeedPosCheck = !SE.isKnownNegative(Step);
2152     bool NeedNegCheck = !SE.isKnownPositive(Step);
2153 
2154     if (isa<PointerType>(ARTy)) {
2155       Value *NegMulV = Builder.CreateNeg(MulV);
2156       if (NeedPosCheck)
2157         Add = Builder.CreatePtrAdd(StartValue, MulV);
2158       if (NeedNegCheck)
2159         Sub = Builder.CreatePtrAdd(StartValue, NegMulV);
2160     } else {
2161       if (NeedPosCheck)
2162         Add = Builder.CreateAdd(StartValue, MulV);
2163       if (NeedNegCheck)
2164         Sub = Builder.CreateSub(StartValue, MulV);
2165     }
2166 
2167     Value *EndCompareLT = nullptr;
2168     Value *EndCompareGT = nullptr;
2169     Value *EndCheck = nullptr;
2170     if (NeedPosCheck)
2171       EndCheck = EndCompareLT = Builder.CreateICmp(
2172           Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2173     if (NeedNegCheck)
2174       EndCheck = EndCompareGT = Builder.CreateICmp(
2175           Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2176     if (NeedPosCheck && NeedNegCheck) {
2177       // Select the answer based on the sign of Step.
2178       EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2179     }
2180     return Builder.CreateOr(EndCheck, OfMul);
2181   };
2182   Value *EndCheck = ComputeEndCheck();
2183 
2184   // If the backedge taken count type is larger than the AR type,
2185   // check that we don't drop any bits by truncating it. If we are
2186   // dropping bits, then we have overflow (unless the step is zero).
2187   if (SrcBits > DstBits) {
2188     auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2189     auto *BackedgeCheck =
2190         Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2191                            ConstantInt::get(Loc->getContext(), MaxVal));
2192     BackedgeCheck = Builder.CreateAnd(
2193         BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2194 
2195     EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2196   }
2197 
2198   return EndCheck;
2199 }
2200 
2201 Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2202                                          Instruction *IP) {
2203   const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2204   Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2205 
2206   // Add a check for NUSW
2207   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2208     NUSWCheck = generateOverflowCheck(A, IP, false);
2209 
2210   // Add a check for NSSW
2211   if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2212     NSSWCheck = generateOverflowCheck(A, IP, true);
2213 
2214   if (NUSWCheck && NSSWCheck)
2215     return Builder.CreateOr(NUSWCheck, NSSWCheck);
2216 
2217   if (NUSWCheck)
2218     return NUSWCheck;
2219 
2220   if (NSSWCheck)
2221     return NSSWCheck;
2222 
2223   return ConstantInt::getFalse(IP->getContext());
2224 }
2225 
2226 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2227                                           Instruction *IP) {
2228   // Loop over all checks in this set.
2229   SmallVector<Value *> Checks;
2230   for (const auto *Pred : Union->getPredicates()) {
2231     Checks.push_back(expandCodeForPredicate(Pred, IP));
2232     Builder.SetInsertPoint(IP);
2233   }
2234 
2235   if (Checks.empty())
2236     return ConstantInt::getFalse(IP->getContext());
2237   return Builder.CreateOr(Checks);
2238 }
2239 
2240 Value *SCEVExpander::fixupLCSSAFormFor(Value *V) {
2241   auto *DefI = dyn_cast<Instruction>(V);
2242   if (!PreserveLCSSA || !DefI)
2243     return V;
2244 
2245   BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
2246   Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent());
2247   Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent());
2248   if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2249     return V;
2250 
2251   // Create a temporary instruction to at the current insertion point, so we
2252   // can hand it off to the helper to create LCSSA PHIs if required for the
2253   // new use.
2254   // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
2255   // would accept a insertion point and return an LCSSA phi for that
2256   // insertion point, so there is no need to insert & remove the temporary
2257   // instruction.
2258   Type *ToTy;
2259   if (DefI->getType()->isIntegerTy())
2260     ToTy = PointerType::get(DefI->getContext(), 0);
2261   else
2262     ToTy = Type::getInt32Ty(DefI->getContext());
2263   Instruction *User =
2264       CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt);
2265   auto RemoveUserOnExit =
2266       make_scope_exit([User]() { User->eraseFromParent(); });
2267 
2268   SmallVector<Instruction *, 1> ToUpdate;
2269   ToUpdate.push_back(DefI);
2270   SmallVector<PHINode *, 16> PHIsToRemove;
2271   SmallVector<PHINode *, 16> InsertedPHIs;
2272   formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove,
2273                            &InsertedPHIs);
2274   for (PHINode *PN : InsertedPHIs)
2275     rememberInstruction(PN);
2276   for (PHINode *PN : PHIsToRemove) {
2277     if (!PN->use_empty())
2278       continue;
2279     InsertedValues.erase(PN);
2280     InsertedPostIncValues.erase(PN);
2281     PN->eraseFromParent();
2282   }
2283 
2284   return User->getOperand(0);
2285 }
2286 
2287 namespace {
2288 // Search for a SCEV subexpression that is not safe to expand.  Any expression
2289 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2290 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2291 // instruction, but the important thing is that we prove the denominator is
2292 // nonzero before expansion.
2293 //
2294 // IVUsers already checks that IV-derived expressions are safe. So this check is
2295 // only needed when the expression includes some subexpression that is not IV
2296 // derived.
2297 //
2298 // Currently, we only allow division by a value provably non-zero here.
2299 //
2300 // We cannot generally expand recurrences unless the step dominates the loop
2301 // header. The expander handles the special case of affine recurrences by
2302 // scaling the recurrence outside the loop, but this technique isn't generally
2303 // applicable. Expanding a nested recurrence outside a loop requires computing
2304 // binomial coefficients. This could be done, but the recurrence has to be in a
2305 // perfectly reduced form, which can't be guaranteed.
2306 struct SCEVFindUnsafe {
2307   ScalarEvolution &SE;
2308   bool CanonicalMode;
2309   bool IsUnsafe = false;
2310 
2311   SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
2312       : SE(SE), CanonicalMode(CanonicalMode) {}
2313 
2314   bool follow(const SCEV *S) {
2315     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2316       if (!SE.isKnownNonZero(D->getRHS())) {
2317         IsUnsafe = true;
2318         return false;
2319       }
2320     }
2321     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2322       // For non-affine addrecs or in non-canonical mode we need a preheader
2323       // to insert into.
2324       if (!AR->getLoop()->getLoopPreheader() &&
2325           (!CanonicalMode || !AR->isAffine())) {
2326         IsUnsafe = true;
2327         return false;
2328       }
2329     }
2330     return true;
2331   }
2332   bool isDone() const { return IsUnsafe; }
2333 };
2334 } // namespace
2335 
2336 bool SCEVExpander::isSafeToExpand(const SCEV *S) const {
2337   SCEVFindUnsafe Search(SE, CanonicalMode);
2338   visitAll(S, Search);
2339   return !Search.IsUnsafe;
2340 }
2341 
2342 bool SCEVExpander::isSafeToExpandAt(const SCEV *S,
2343                                     const Instruction *InsertionPoint) const {
2344   if (!isSafeToExpand(S))
2345     return false;
2346   // We have to prove that the expanded site of S dominates InsertionPoint.
2347   // This is easy when not in the same block, but hard when S is an instruction
2348   // to be expanded somewhere inside the same block as our insertion point.
2349   // What we really need here is something analogous to an OrderedBasicBlock,
2350   // but for the moment, we paper over the problem by handling two common and
2351   // cheap to check cases.
2352   if (SE.properlyDominates(S, InsertionPoint->getParent()))
2353     return true;
2354   if (SE.dominates(S, InsertionPoint->getParent())) {
2355     if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2356       return true;
2357     if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2358       if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
2359         return true;
2360   }
2361   return false;
2362 }
2363 
2364 void SCEVExpanderCleaner::cleanup() {
2365   // Result is used, nothing to remove.
2366   if (ResultUsed)
2367     return;
2368 
2369   // Restore original poison flags.
2370   for (auto [I, Flags] : Expander.OrigFlags)
2371     Flags.apply(I);
2372 
2373   auto InsertedInstructions = Expander.getAllInsertedInstructions();
2374 #ifndef NDEBUG
2375   SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
2376                                             InsertedInstructions.end());
2377   (void)InsertedSet;
2378 #endif
2379   // Remove sets with value handles.
2380   Expander.clear();
2381 
2382   // Remove all inserted instructions.
2383   for (Instruction *I : reverse(InsertedInstructions)) {
2384 #ifndef NDEBUG
2385     assert(all_of(I->users(),
2386                   [&InsertedSet](Value *U) {
2387                     return InsertedSet.contains(cast<Instruction>(U));
2388                   }) &&
2389            "removed instruction should only be used by instructions inserted "
2390            "during expansion");
2391 #endif
2392     assert(!I->getType()->isVoidTy() &&
2393            "inserted instruction should have non-void types");
2394     I->replaceAllUsesWith(PoisonValue::get(I->getType()));
2395     I->eraseFromParent();
2396   }
2397 }
2398