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