[ScalarEvolutionExpander] Properly insert no-op casts + EH Pads
[oota-llvm.git] / lib / Analysis / ScalarEvolutionExpander.cpp
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution expander,
11 // which is used to generate the code corresponding to a given scalar evolution
12 // expression.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30
31 using namespace llvm;
32 using namespace PatternMatch;
33
34 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
35 /// reusing an existing cast if a suitable one exists, moving an existing
36 /// cast if a suitable one exists but isn't in the right place, or
37 /// creating a new one.
38 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
39                                        Instruction::CastOps Op,
40                                        BasicBlock::iterator IP) {
41   // This function must be called with the builder having a valid insertion
42   // point. It doesn't need to be the actual IP where the uses of the returned
43   // cast will be added, but it must dominate such IP.
44   // We use this precondition to produce a cast that will dominate all its
45   // uses. In particular, this is crucial for the case where the builder's
46   // insertion point *is* the point where we were asked to put the cast.
47   // Since we don't know the builder's insertion point is actually
48   // where the uses will be added (only that it dominates it), we are
49   // not allowed to move it.
50   BasicBlock::iterator BIP = Builder.GetInsertPoint();
51
52   Instruction *Ret = nullptr;
53
54   // Check to see if there is already a cast!
55   for (User *U : V->users())
56     if (U->getType() == Ty)
57       if (CastInst *CI = dyn_cast<CastInst>(U))
58         if (CI->getOpcode() == Op) {
59           // If the cast isn't where we want it, create a new cast at IP.
60           // Likewise, do not reuse a cast at BIP because it must dominate
61           // instructions that might be inserted before BIP.
62           if (BasicBlock::iterator(CI) != IP || BIP == IP) {
63             // Create a new cast, and leave the old cast in place in case
64             // it is being used as an insert point. Clear its operand
65             // so that it doesn't hold anything live.
66             Ret = CastInst::Create(Op, V, Ty, "", &*IP);
67             Ret->takeName(CI);
68             CI->replaceAllUsesWith(Ret);
69             CI->setOperand(0, UndefValue::get(V->getType()));
70             break;
71           }
72           Ret = CI;
73           break;
74         }
75
76   // Create a new cast.
77   if (!Ret)
78     Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
79
80   // We assert at the end of the function since IP might point to an
81   // instruction with different dominance properties than a cast
82   // (an invoke for example) and not dominate BIP (but the cast does).
83   assert(SE.DT.dominates(Ret, &*BIP));
84
85   rememberInstruction(Ret);
86   return Ret;
87 }
88
89 static BasicBlock::iterator findInsertPointAfter(Instruction *I,
90                                                  DominatorTree &DT,
91                                                  BasicBlock *MustDominate) {
92   BasicBlock::iterator IP = ++I->getIterator();
93   if (auto *II = dyn_cast<InvokeInst>(I))
94     IP = II->getNormalDest()->begin();
95   if (auto *CPI = dyn_cast<CatchPadInst>(I))
96     IP = CPI->getNormalDest()->begin();
97
98   while (isa<PHINode>(IP))
99     ++IP;
100
101   while (IP->isEHPad()) {
102     if (isa<LandingPadInst>(IP) || isa<CleanupPadInst>(IP)) {
103       ++IP;
104     } else if (auto *TPI = dyn_cast<TerminatePadInst>(IP)) {
105       IP = TPI->getUnwindDest()->getFirstNonPHI();
106     } else if (auto *CEPI = dyn_cast<CatchEndPadInst>(IP)) {
107       IP = CEPI->getUnwindDest()->getFirstNonPHI();
108     } else if (auto *CEPI = dyn_cast<CleanupEndPadInst>(IP)) {
109       IP = CEPI->getUnwindDest()->getFirstNonPHI();
110     } else if (auto *CPI = dyn_cast<CatchPadInst>(IP)) {
111       BasicBlock *NormalDest = CPI->getNormalDest();
112       if (NormalDest == MustDominate || DT.dominates(NormalDest, MustDominate))
113         IP = NormalDest->getFirstNonPHI();
114       else
115         IP = CPI->getUnwindDest()->getFirstNonPHI();
116     } else {
117       llvm_unreachable("unexpected eh pad!");
118     }
119   }
120
121   return IP;
122 }
123
124 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
125 /// which must be possible with a noop cast, doing what we can to share
126 /// the casts.
127 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
128   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
129   assert((Op == Instruction::BitCast ||
130           Op == Instruction::PtrToInt ||
131           Op == Instruction::IntToPtr) &&
132          "InsertNoopCastOfTo cannot perform non-noop casts!");
133   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
134          "InsertNoopCastOfTo cannot change sizes!");
135
136   // Short-circuit unnecessary bitcasts.
137   if (Op == Instruction::BitCast) {
138     if (V->getType() == Ty)
139       return V;
140     if (CastInst *CI = dyn_cast<CastInst>(V)) {
141       if (CI->getOperand(0)->getType() == Ty)
142         return CI->getOperand(0);
143     }
144   }
145   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
146   if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
147       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
148     if (CastInst *CI = dyn_cast<CastInst>(V))
149       if ((CI->getOpcode() == Instruction::PtrToInt ||
150            CI->getOpcode() == Instruction::IntToPtr) &&
151           SE.getTypeSizeInBits(CI->getType()) ==
152           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
153         return CI->getOperand(0);
154     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
155       if ((CE->getOpcode() == Instruction::PtrToInt ||
156            CE->getOpcode() == Instruction::IntToPtr) &&
157           SE.getTypeSizeInBits(CE->getType()) ==
158           SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
159         return CE->getOperand(0);
160   }
161
162   // Fold a cast of a constant.
163   if (Constant *C = dyn_cast<Constant>(V))
164     return ConstantExpr::getCast(Op, C, Ty);
165
166   // Cast the argument at the beginning of the entry block, after
167   // any bitcasts of other arguments.
168   if (Argument *A = dyn_cast<Argument>(V)) {
169     BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
170     while ((isa<BitCastInst>(IP) &&
171             isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
172             cast<BitCastInst>(IP)->getOperand(0) != A) ||
173            isa<DbgInfoIntrinsic>(IP))
174       ++IP;
175     return ReuseOrCreateCast(A, Ty, Op, IP);
176   }
177
178   // Cast the instruction immediately after the instruction.
179   Instruction *I = cast<Instruction>(V);
180   BasicBlock::iterator IP =
181       findInsertPointAfter(I, SE.DT, Builder.GetInsertBlock());
182   return ReuseOrCreateCast(I, Ty, Op, IP);
183 }
184
185 /// InsertBinop - Insert the specified binary operator, doing a small amount
186 /// of work to avoid inserting an obviously redundant operation.
187 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
188                                  Value *LHS, Value *RHS) {
189   // Fold a binop with constant operands.
190   if (Constant *CLHS = dyn_cast<Constant>(LHS))
191     if (Constant *CRHS = dyn_cast<Constant>(RHS))
192       return ConstantExpr::get(Opcode, CLHS, CRHS);
193
194   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
195   unsigned ScanLimit = 6;
196   BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
197   // Scanning starts from the last instruction before the insertion point.
198   BasicBlock::iterator IP = Builder.GetInsertPoint();
199   if (IP != BlockBegin) {
200     --IP;
201     for (; ScanLimit; --IP, --ScanLimit) {
202       // Don't count dbg.value against the ScanLimit, to avoid perturbing the
203       // generated code.
204       if (isa<DbgInfoIntrinsic>(IP))
205         ScanLimit++;
206       if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
207           IP->getOperand(1) == RHS)
208         return &*IP;
209       if (IP == BlockBegin) break;
210     }
211   }
212
213   // Save the original insertion point so we can restore it when we're done.
214   DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
215   BuilderType::InsertPointGuard Guard(Builder);
216
217   // Move the insertion point out of as many loops as we can.
218   while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
219     if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
220     BasicBlock *Preheader = L->getLoopPreheader();
221     if (!Preheader) break;
222
223     // Ok, move up a level.
224     Builder.SetInsertPoint(Preheader->getTerminator());
225   }
226
227   // If we haven't found this binop, insert it.
228   Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
229   BO->setDebugLoc(Loc);
230   rememberInstruction(BO);
231
232   return BO;
233 }
234
235 /// FactorOutConstant - Test if S is divisible by Factor, using signed
236 /// division. If so, update S with Factor divided out and return true.
237 /// S need not be evenly divisible if a reasonable remainder can be
238 /// computed.
239 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
240 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
241 /// check to see if the divide was folded.
242 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
243                               const SCEV *Factor, ScalarEvolution &SE,
244                               const DataLayout &DL) {
245   // Everything is divisible by one.
246   if (Factor->isOne())
247     return true;
248
249   // x/x == 1.
250   if (S == Factor) {
251     S = SE.getConstant(S->getType(), 1);
252     return true;
253   }
254
255   // For a Constant, check for a multiple of the given factor.
256   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
257     // 0/x == 0.
258     if (C->isZero())
259       return true;
260     // Check for divisibility.
261     if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
262       ConstantInt *CI =
263         ConstantInt::get(SE.getContext(),
264                          C->getValue()->getValue().sdiv(
265                                                    FC->getValue()->getValue()));
266       // If the quotient is zero and the remainder is non-zero, reject
267       // the value at this scale. It will be considered for subsequent
268       // smaller scales.
269       if (!CI->isZero()) {
270         const SCEV *Div = SE.getConstant(CI);
271         S = Div;
272         Remainder =
273           SE.getAddExpr(Remainder,
274                         SE.getConstant(C->getValue()->getValue().srem(
275                                                   FC->getValue()->getValue())));
276         return true;
277       }
278     }
279   }
280
281   // In a Mul, check if there is a constant operand which is a multiple
282   // of the given factor.
283   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
284     // Size is known, check if there is a constant operand which is a multiple
285     // of the given factor. If so, we can factor it.
286     const SCEVConstant *FC = cast<SCEVConstant>(Factor);
287     if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
288       if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
289         SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
290         NewMulOps[0] = SE.getConstant(
291             C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
292         S = SE.getMulExpr(NewMulOps);
293         return true;
294       }
295   }
296
297   // In an AddRec, check if both start and step are divisible.
298   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
299     const SCEV *Step = A->getStepRecurrence(SE);
300     const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
301     if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
302       return false;
303     if (!StepRem->isZero())
304       return false;
305     const SCEV *Start = A->getStart();
306     if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
307       return false;
308     S = SE.getAddRecExpr(Start, Step, A->getLoop(),
309                          A->getNoWrapFlags(SCEV::FlagNW));
310     return true;
311   }
312
313   return false;
314 }
315
316 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
317 /// is the number of SCEVAddRecExprs present, which are kept at the end of
318 /// the list.
319 ///
320 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
321                                 Type *Ty,
322                                 ScalarEvolution &SE) {
323   unsigned NumAddRecs = 0;
324   for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
325     ++NumAddRecs;
326   // Group Ops into non-addrecs and addrecs.
327   SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
328   SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
329   // Let ScalarEvolution sort and simplify the non-addrecs list.
330   const SCEV *Sum = NoAddRecs.empty() ?
331                     SE.getConstant(Ty, 0) :
332                     SE.getAddExpr(NoAddRecs);
333   // If it returned an add, use the operands. Otherwise it simplified
334   // the sum into a single value, so just use that.
335   Ops.clear();
336   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
337     Ops.append(Add->op_begin(), Add->op_end());
338   else if (!Sum->isZero())
339     Ops.push_back(Sum);
340   // Then append the addrecs.
341   Ops.append(AddRecs.begin(), AddRecs.end());
342 }
343
344 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
345 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
346 /// This helps expose more opportunities for folding parts of the expressions
347 /// into GEP indices.
348 ///
349 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
350                          Type *Ty,
351                          ScalarEvolution &SE) {
352   // Find the addrecs.
353   SmallVector<const SCEV *, 8> AddRecs;
354   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
355     while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
356       const SCEV *Start = A->getStart();
357       if (Start->isZero()) break;
358       const SCEV *Zero = SE.getConstant(Ty, 0);
359       AddRecs.push_back(SE.getAddRecExpr(Zero,
360                                          A->getStepRecurrence(SE),
361                                          A->getLoop(),
362                                          A->getNoWrapFlags(SCEV::FlagNW)));
363       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
364         Ops[i] = Zero;
365         Ops.append(Add->op_begin(), Add->op_end());
366         e += Add->getNumOperands();
367       } else {
368         Ops[i] = Start;
369       }
370     }
371   if (!AddRecs.empty()) {
372     // Add the addrecs onto the end of the list.
373     Ops.append(AddRecs.begin(), AddRecs.end());
374     // Resort the operand list, moving any constants to the front.
375     SimplifyAddOperands(Ops, Ty, SE);
376   }
377 }
378
379 /// expandAddToGEP - Expand an addition expression with a pointer type into
380 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
381 /// BasicAliasAnalysis and other passes analyze the result. See the rules
382 /// for getelementptr vs. inttoptr in
383 /// http://llvm.org/docs/LangRef.html#pointeraliasing
384 /// for details.
385 ///
386 /// Design note: The correctness of using getelementptr here depends on
387 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
388 /// they may introduce pointer arithmetic which may not be safely converted
389 /// into getelementptr.
390 ///
391 /// Design note: It might seem desirable for this function to be more
392 /// loop-aware. If some of the indices are loop-invariant while others
393 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
394 /// loop-invariant portions of the overall computation outside the loop.
395 /// However, there are a few reasons this is not done here. Hoisting simple
396 /// arithmetic is a low-level optimization that often isn't very
397 /// important until late in the optimization process. In fact, passes
398 /// like InstructionCombining will combine GEPs, even if it means
399 /// pushing loop-invariant computation down into loops, so even if the
400 /// GEPs were split here, the work would quickly be undone. The
401 /// LoopStrengthReduction pass, which is usually run quite late (and
402 /// after the last InstructionCombining pass), takes care of hoisting
403 /// loop-invariant portions of expressions, after considering what
404 /// can be folded using target addressing modes.
405 ///
406 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
407                                     const SCEV *const *op_end,
408                                     PointerType *PTy,
409                                     Type *Ty,
410                                     Value *V) {
411   Type *OriginalElTy = PTy->getElementType();
412   Type *ElTy = OriginalElTy;
413   SmallVector<Value *, 4> GepIndices;
414   SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
415   bool AnyNonZeroIndices = false;
416
417   // Split AddRecs up into parts as either of the parts may be usable
418   // without the other.
419   SplitAddRecs(Ops, Ty, SE);
420
421   Type *IntPtrTy = DL.getIntPtrType(PTy);
422
423   // Descend down the pointer's type and attempt to convert the other
424   // operands into GEP indices, at each level. The first index in a GEP
425   // indexes into the array implied by the pointer operand; the rest of
426   // the indices index into the element or field type selected by the
427   // preceding index.
428   for (;;) {
429     // If the scale size is not 0, attempt to factor out a scale for
430     // array indexing.
431     SmallVector<const SCEV *, 8> ScaledOps;
432     if (ElTy->isSized()) {
433       const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
434       if (!ElSize->isZero()) {
435         SmallVector<const SCEV *, 8> NewOps;
436         for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
437           const SCEV *Op = Ops[i];
438           const SCEV *Remainder = SE.getConstant(Ty, 0);
439           if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
440             // Op now has ElSize factored out.
441             ScaledOps.push_back(Op);
442             if (!Remainder->isZero())
443               NewOps.push_back(Remainder);
444             AnyNonZeroIndices = true;
445           } else {
446             // The operand was not divisible, so add it to the list of operands
447             // we'll scan next iteration.
448             NewOps.push_back(Ops[i]);
449           }
450         }
451         // If we made any changes, update Ops.
452         if (!ScaledOps.empty()) {
453           Ops = NewOps;
454           SimplifyAddOperands(Ops, Ty, SE);
455         }
456       }
457     }
458
459     // Record the scaled array index for this level of the type. If
460     // we didn't find any operands that could be factored, tentatively
461     // assume that element zero was selected (since the zero offset
462     // would obviously be folded away).
463     Value *Scaled = ScaledOps.empty() ?
464                     Constant::getNullValue(Ty) :
465                     expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
466     GepIndices.push_back(Scaled);
467
468     // Collect struct field index operands.
469     while (StructType *STy = dyn_cast<StructType>(ElTy)) {
470       bool FoundFieldNo = false;
471       // An empty struct has no fields.
472       if (STy->getNumElements() == 0) break;
473       // Field offsets are known. See if a constant offset falls within any of
474       // the struct fields.
475       if (Ops.empty())
476         break;
477       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
478         if (SE.getTypeSizeInBits(C->getType()) <= 64) {
479           const StructLayout &SL = *DL.getStructLayout(STy);
480           uint64_t FullOffset = C->getValue()->getZExtValue();
481           if (FullOffset < SL.getSizeInBytes()) {
482             unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
483             GepIndices.push_back(
484                 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
485             ElTy = STy->getTypeAtIndex(ElIdx);
486             Ops[0] =
487                 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
488             AnyNonZeroIndices = true;
489             FoundFieldNo = true;
490           }
491         }
492       // If no struct field offsets were found, tentatively assume that
493       // field zero was selected (since the zero offset would obviously
494       // be folded away).
495       if (!FoundFieldNo) {
496         ElTy = STy->getTypeAtIndex(0u);
497         GepIndices.push_back(
498           Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
499       }
500     }
501
502     if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
503       ElTy = ATy->getElementType();
504     else
505       break;
506   }
507
508   // If none of the operands were convertible to proper GEP indices, cast
509   // the base to i8* and do an ugly getelementptr with that. It's still
510   // better than ptrtoint+arithmetic+inttoptr at least.
511   if (!AnyNonZeroIndices) {
512     // Cast the base to i8*.
513     V = InsertNoopCastOfTo(V,
514        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
515
516     assert(!isa<Instruction>(V) ||
517            SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
518
519     // Expand the operands for a plain byte offset.
520     Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
521
522     // Fold a GEP with constant operands.
523     if (Constant *CLHS = dyn_cast<Constant>(V))
524       if (Constant *CRHS = dyn_cast<Constant>(Idx))
525         return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
526                                               CLHS, CRHS);
527
528     // Do a quick scan to see if we have this GEP nearby.  If so, reuse it.
529     unsigned ScanLimit = 6;
530     BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
531     // Scanning starts from the last instruction before the insertion point.
532     BasicBlock::iterator IP = Builder.GetInsertPoint();
533     if (IP != BlockBegin) {
534       --IP;
535       for (; ScanLimit; --IP, --ScanLimit) {
536         // Don't count dbg.value against the ScanLimit, to avoid perturbing the
537         // generated code.
538         if (isa<DbgInfoIntrinsic>(IP))
539           ScanLimit++;
540         if (IP->getOpcode() == Instruction::GetElementPtr &&
541             IP->getOperand(0) == V && IP->getOperand(1) == Idx)
542           return &*IP;
543         if (IP == BlockBegin) break;
544       }
545     }
546
547     // Save the original insertion point so we can restore it when we're done.
548     BuilderType::InsertPointGuard Guard(Builder);
549
550     // Move the insertion point out of as many loops as we can.
551     while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
552       if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
553       BasicBlock *Preheader = L->getLoopPreheader();
554       if (!Preheader) break;
555
556       // Ok, move up a level.
557       Builder.SetInsertPoint(Preheader->getTerminator());
558     }
559
560     // Emit a GEP.
561     Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
562     rememberInstruction(GEP);
563
564     return GEP;
565   }
566
567   // Save the original insertion point so we can restore it when we're done.
568   BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
569
570   // Move the insertion point out of as many loops as we can.
571   while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
572     if (!L->isLoopInvariant(V)) break;
573
574     bool AnyIndexNotLoopInvariant = false;
575     for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
576          E = GepIndices.end(); I != E; ++I)
577       if (!L->isLoopInvariant(*I)) {
578         AnyIndexNotLoopInvariant = true;
579         break;
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,
598                                  GepIndices,
599                                  "scevgep");
600   Ops.push_back(SE.getUnknown(GEP));
601   rememberInstruction(GEP);
602
603   // Restore the original insert point.
604   Builder.restoreIP(SaveInsertPt);
605
606   return expand(SE.getAddExpr(Ops));
607 }
608
609 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
610 /// SCEV expansion. If they are nested, this is the most nested. If they are
611 /// neighboring, pick the later.
612 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
613                                         DominatorTree &DT) {
614   if (!A) return B;
615   if (!B) return A;
616   if (A->contains(B)) return B;
617   if (B->contains(A)) return A;
618   if (DT.dominates(A->getHeader(), B->getHeader())) return B;
619   if (DT.dominates(B->getHeader(), A->getHeader())) return A;
620   return A; // Arbitrarily break the tie.
621 }
622
623 /// getRelevantLoop - Get the most relevant loop associated with the given
624 /// expression, according to PickMostRelevantLoop.
625 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
626   // Test whether we've already computed the most relevant loop for this SCEV.
627   std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
628     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 (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
646          I != E; ++I)
647       L = PickMostRelevantLoop(L, getRelevantLoop(*I), SE.DT);
648     return RelevantLoops[N] = L;
649   }
650   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
651     const Loop *Result = getRelevantLoop(C->getOperand());
652     return RelevantLoops[C] = Result;
653   }
654   if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
655     const Loop *Result = PickMostRelevantLoop(
656         getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
657     return RelevantLoops[D] = Result;
658   }
659   llvm_unreachable("Unexpected SCEV type!");
660 }
661
662 namespace {
663
664 /// LoopCompare - Compare loops by PickMostRelevantLoop.
665 class LoopCompare {
666   DominatorTree &DT;
667 public:
668   explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
669
670   bool operator()(std::pair<const Loop *, const SCEV *> LHS,
671                   std::pair<const Loop *, const SCEV *> RHS) const {
672     // Keep pointer operands sorted at the end.
673     if (LHS.second->getType()->isPointerTy() !=
674         RHS.second->getType()->isPointerTy())
675       return LHS.second->getType()->isPointerTy();
676
677     // Compare loops with PickMostRelevantLoop.
678     if (LHS.first != RHS.first)
679       return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
680
681     // If one operand is a non-constant negative and the other is not,
682     // put the non-constant negative on the right so that a sub can
683     // be used instead of a negate and add.
684     if (LHS.second->isNonConstantNegative()) {
685       if (!RHS.second->isNonConstantNegative())
686         return false;
687     } else if (RHS.second->isNonConstantNegative())
688       return true;
689
690     // Otherwise they are equivalent according to this comparison.
691     return false;
692   }
693 };
694
695 }
696
697 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
698   Type *Ty = SE.getEffectiveSCEVType(S->getType());
699
700   // Collect all the add operands in a loop, along with their associated loops.
701   // Iterate in reverse so that constants are emitted last, all else equal, and
702   // so that pointer operands are inserted first, which the code below relies on
703   // to form more involved GEPs.
704   SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
705   for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
706        E(S->op_begin()); I != E; ++I)
707     OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
708
709   // Sort by loop. Use a stable sort so that constants follow non-constants and
710   // pointer operands precede non-pointer operands.
711   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
712
713   // Emit instructions to add all the operands. Hoist as much as possible
714   // out of loops, and form meaningful getelementptrs where possible.
715   Value *Sum = nullptr;
716   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
717        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
718     const Loop *CurLoop = I->first;
719     const SCEV *Op = I->second;
720     if (!Sum) {
721       // This is the first operand. Just expand it.
722       Sum = expand(Op);
723       ++I;
724     } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
725       // The running sum expression is a pointer. Try to form a getelementptr
726       // at this level with that as the base.
727       SmallVector<const SCEV *, 4> NewOps;
728       for (; I != E && I->first == CurLoop; ++I) {
729         // If the operand is SCEVUnknown and not instructions, peek through
730         // it, to enable more of it to be folded into the GEP.
731         const SCEV *X = I->second;
732         if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
733           if (!isa<Instruction>(U->getValue()))
734             X = SE.getSCEV(U->getValue());
735         NewOps.push_back(X);
736       }
737       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
738     } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
739       // The running sum is an integer, and there's a pointer at this level.
740       // Try to form a getelementptr. If the running sum is instructions,
741       // use a SCEVUnknown to avoid re-analyzing them.
742       SmallVector<const SCEV *, 4> NewOps;
743       NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
744                                                SE.getSCEV(Sum));
745       for (++I; I != E && I->first == CurLoop; ++I)
746         NewOps.push_back(I->second);
747       Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
748     } else if (Op->isNonConstantNegative()) {
749       // Instead of doing a negate and add, just do a subtract.
750       Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
751       Sum = InsertNoopCastOfTo(Sum, Ty);
752       Sum = InsertBinop(Instruction::Sub, Sum, W);
753       ++I;
754     } else {
755       // A simple add.
756       Value *W = expandCodeFor(Op, Ty);
757       Sum = InsertNoopCastOfTo(Sum, Ty);
758       // Canonicalize a constant to the RHS.
759       if (isa<Constant>(Sum)) std::swap(Sum, W);
760       Sum = InsertBinop(Instruction::Add, Sum, W);
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   std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), 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   for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
785        I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ++I) {
786     const SCEV *Op = I->second;
787     if (!Prod) {
788       // This is the first operand. Just expand it.
789       Prod = expand(Op);
790     } else if (Op->isAllOnesValue()) {
791       // Instead of doing a multiply by negative one, just do a negate.
792       Prod = InsertNoopCastOfTo(Prod, Ty);
793       Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
794     } else {
795       // A simple mul.
796       Value *W = expandCodeFor(Op, Ty);
797       Prod = InsertNoopCastOfTo(Prod, Ty);
798       // Canonicalize a constant to the RHS.
799       if (isa<Constant>(Prod)) std::swap(Prod, W);
800       const APInt *RHS;
801       if (match(W, m_Power2(RHS))) {
802         // Canonicalize Prod*(1<<C) to Prod<<C.
803         assert(!Ty->isVectorTy() && "vector types are not SCEVable");
804         Prod = InsertBinop(Instruction::Shl, Prod,
805                            ConstantInt::get(Ty, RHS->logBase2()));
806       } else {
807         Prod = InsertBinop(Instruction::Mul, Prod, W);
808       }
809     }
810   }
811
812   return Prod;
813 }
814
815 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
816   Type *Ty = SE.getEffectiveSCEVType(S->getType());
817
818   Value *LHS = expandCodeFor(S->getLHS(), Ty);
819   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
820     const APInt &RHS = SC->getValue()->getValue();
821     if (RHS.isPowerOf2())
822       return InsertBinop(Instruction::LShr, LHS,
823                          ConstantInt::get(Ty, RHS.logBase2()));
824   }
825
826   Value *RHS = expandCodeFor(S->getRHS(), Ty);
827   return InsertBinop(Instruction::UDiv, LHS, RHS);
828 }
829
830 /// Move parts of Base into Rest to leave Base with the minimal
831 /// expression that provides a pointer operand suitable for a
832 /// GEP expansion.
833 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
834                               ScalarEvolution &SE) {
835   while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
836     Base = A->getStart();
837     Rest = SE.getAddExpr(Rest,
838                          SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
839                                           A->getStepRecurrence(SE),
840                                           A->getLoop(),
841                                           A->getNoWrapFlags(SCEV::FlagNW)));
842   }
843   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
844     Base = A->getOperand(A->getNumOperands()-1);
845     SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
846     NewAddOps.back() = Rest;
847     Rest = SE.getAddExpr(NewAddOps);
848     ExposePointerBase(Base, Rest, SE);
849   }
850 }
851
852 /// Determine if this is a well-behaved chain of instructions leading back to
853 /// the PHI. If so, it may be reused by expanded expressions.
854 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
855                                          const Loop *L) {
856   if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
857       (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
858     return false;
859   // If any of the operands don't dominate the insert position, bail.
860   // Addrec operands are always loop-invariant, so this can only happen
861   // if there are instructions which haven't been hoisted.
862   if (L == IVIncInsertLoop) {
863     for (User::op_iterator OI = IncV->op_begin()+1,
864            OE = IncV->op_end(); OI != OE; ++OI)
865       if (Instruction *OInst = dyn_cast<Instruction>(OI))
866         if (!SE.DT.dominates(OInst, IVIncInsertPos))
867           return false;
868   }
869   // Advance to the next instruction.
870   IncV = dyn_cast<Instruction>(IncV->getOperand(0));
871   if (!IncV)
872     return false;
873
874   if (IncV->mayHaveSideEffects())
875     return false;
876
877   if (IncV != PN)
878     return true;
879
880   return isNormalAddRecExprPHI(PN, IncV, L);
881 }
882
883 /// getIVIncOperand returns an induction variable increment's induction
884 /// variable operand.
885 ///
886 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
887 /// operands dominate InsertPos.
888 ///
889 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
890 /// simple patterns generated by getAddRecExprPHILiterally and
891 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
892 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
893                                            Instruction *InsertPos,
894                                            bool allowScale) {
895   if (IncV == InsertPos)
896     return nullptr;
897
898   switch (IncV->getOpcode()) {
899   default:
900     return nullptr;
901   // Check for a simple Add/Sub or GEP of a loop invariant step.
902   case Instruction::Add:
903   case Instruction::Sub: {
904     Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
905     if (!OInst || SE.DT.dominates(OInst, InsertPos))
906       return dyn_cast<Instruction>(IncV->getOperand(0));
907     return nullptr;
908   }
909   case Instruction::BitCast:
910     return dyn_cast<Instruction>(IncV->getOperand(0));
911   case Instruction::GetElementPtr:
912     for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
913          I != E; ++I) {
914       if (isa<Constant>(*I))
915         continue;
916       if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
917         if (!SE.DT.dominates(OInst, InsertPos))
918           return nullptr;
919       }
920       if (allowScale) {
921         // allow any kind of GEP as long as it can be hoisted.
922         continue;
923       }
924       // This must be a pointer addition of constants (pretty), which is already
925       // handled, or some number of address-size elements (ugly). Ugly geps
926       // have 2 operands. i1* is used by the expander to represent an
927       // address-size element.
928       if (IncV->getNumOperands() != 2)
929         return nullptr;
930       unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
931       if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
932           && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
933         return nullptr;
934       break;
935     }
936     return dyn_cast<Instruction>(IncV->getOperand(0));
937   }
938 }
939
940 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
941 /// it available to other uses in this loop. Recursively hoist any operands,
942 /// until we reach a value that dominates InsertPos.
943 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
944   if (SE.DT.dominates(IncV, InsertPos))
945       return true;
946
947   // InsertPos must itself dominate IncV so that IncV's new position satisfies
948   // its existing users.
949   if (isa<PHINode>(InsertPos) ||
950       !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
951     return false;
952
953   // Check that the chain of IV operands leading back to Phi can be hoisted.
954   SmallVector<Instruction*, 4> IVIncs;
955   for(;;) {
956     Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
957     if (!Oper)
958       return false;
959     // IncV is safe to hoist.
960     IVIncs.push_back(IncV);
961     IncV = Oper;
962     if (SE.DT.dominates(IncV, InsertPos))
963       break;
964   }
965   for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
966          E = IVIncs.rend(); I != E; ++I) {
967     (*I)->moveBefore(InsertPos);
968   }
969   return true;
970 }
971
972 /// Determine if this cyclic phi is in a form that would have been generated by
973 /// LSR. We don't care if the phi was actually expanded in this pass, as long
974 /// as it is in a low-cost form, for example, no implied multiplication. This
975 /// should match any patterns generated by getAddRecExprPHILiterally and
976 /// expandAddtoGEP.
977 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
978                                            const Loop *L) {
979   for(Instruction *IVOper = IncV;
980       (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
981                                 /*allowScale=*/false));) {
982     if (IVOper == PN)
983       return true;
984   }
985   return false;
986 }
987
988 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
989 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
990 /// need to materialize IV increments elsewhere to handle difficult situations.
991 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
992                                  Type *ExpandTy, Type *IntTy,
993                                  bool useSubtract) {
994   Value *IncV;
995   // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
996   if (ExpandTy->isPointerTy()) {
997     PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
998     // If the step isn't constant, don't use an implicitly scaled GEP, because
999     // that would require a multiply inside the loop.
1000     if (!isa<ConstantInt>(StepV))
1001       GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1002                                   GEPPtrTy->getAddressSpace());
1003     const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
1004     IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
1005     if (IncV->getType() != PN->getType()) {
1006       IncV = Builder.CreateBitCast(IncV, PN->getType());
1007       rememberInstruction(IncV);
1008     }
1009   } else {
1010     IncV = useSubtract ?
1011       Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1012       Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1013     rememberInstruction(IncV);
1014   }
1015   return IncV;
1016 }
1017
1018 /// \brief Hoist the addrec instruction chain rooted in the loop phi above the
1019 /// position. This routine assumes that this is possible (has been checked).
1020 static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1021                            Instruction *Pos, PHINode *LoopPhi) {
1022   do {
1023     if (DT->dominates(InstToHoist, Pos))
1024       break;
1025     // Make sure the increment is where we want it. But don't move it
1026     // down past a potential existing post-inc user.
1027     InstToHoist->moveBefore(Pos);
1028     Pos = InstToHoist;
1029     InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1030   } while (InstToHoist != LoopPhi);
1031 }
1032
1033 /// \brief Check whether we can cheaply express the requested SCEV in terms of
1034 /// the available PHI SCEV by truncation and/or inversion of the step.
1035 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1036                                     const SCEVAddRecExpr *Phi,
1037                                     const SCEVAddRecExpr *Requested,
1038                                     bool &InvertStep) {
1039   Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1040   Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1041
1042   if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1043     return false;
1044
1045   // Try truncate it if necessary.
1046   Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1047   if (!Phi)
1048     return false;
1049
1050   // Check whether truncation will help.
1051   if (Phi == Requested) {
1052     InvertStep = false;
1053     return true;
1054   }
1055
1056   // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1057   if (SE.getAddExpr(Requested->getStart(),
1058                     SE.getNegativeSCEV(Requested)) == Phi) {
1059     InvertStep = true;
1060     return true;
1061   }
1062
1063   return false;
1064 }
1065
1066 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1067   if (!isa<IntegerType>(AR->getType()))
1068     return false;
1069
1070   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1071   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1072   const SCEV *Step = AR->getStepRecurrence(SE);
1073   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1074                                             SE.getSignExtendExpr(AR, WideTy));
1075   const SCEV *ExtendAfterOp =
1076     SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1077   return ExtendAfterOp == OpAfterExtend;
1078 }
1079
1080 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1081   if (!isa<IntegerType>(AR->getType()))
1082     return false;
1083
1084   unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1085   Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1086   const SCEV *Step = AR->getStepRecurrence(SE);
1087   const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1088                                             SE.getZeroExtendExpr(AR, WideTy));
1089   const SCEV *ExtendAfterOp =
1090     SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1091   return ExtendAfterOp == OpAfterExtend;
1092 }
1093
1094 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1095 /// the base addrec, which is the addrec without any non-loop-dominating
1096 /// values, and return the PHI.
1097 PHINode *
1098 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1099                                         const Loop *L,
1100                                         Type *ExpandTy,
1101                                         Type *IntTy,
1102                                         Type *&TruncTy,
1103                                         bool &InvertStep) {
1104   assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1105
1106   // Reuse a previously-inserted PHI, if present.
1107   BasicBlock *LatchBlock = L->getLoopLatch();
1108   if (LatchBlock) {
1109     PHINode *AddRecPhiMatch = nullptr;
1110     Instruction *IncV = nullptr;
1111     TruncTy = nullptr;
1112     InvertStep = false;
1113
1114     // Only try partially matching scevs that need truncation and/or
1115     // step-inversion if we know this loop is outside the current loop.
1116     bool TryNonMatchingSCEV =
1117         IVIncInsertLoop &&
1118         SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1119
1120     for (BasicBlock::iterator I = L->getHeader()->begin();
1121          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1122       if (!SE.isSCEVable(PN->getType()))
1123         continue;
1124
1125       const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1126       if (!PhiSCEV)
1127         continue;
1128
1129       bool IsMatchingSCEV = PhiSCEV == Normalized;
1130       // We only handle truncation and inversion of phi recurrences for the
1131       // expanded expression if the expanded expression's loop dominates the
1132       // loop we insert to. Check now, so we can bail out early.
1133       if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1134           continue;
1135
1136       Instruction *TempIncV =
1137           cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1138
1139       // Check whether we can reuse this PHI node.
1140       if (LSRMode) {
1141         if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
1142           continue;
1143         if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1144           continue;
1145       } else {
1146         if (!isNormalAddRecExprPHI(PN, TempIncV, L))
1147           continue;
1148       }
1149
1150       // Stop if we have found an exact match SCEV.
1151       if (IsMatchingSCEV) {
1152         IncV = TempIncV;
1153         TruncTy = nullptr;
1154         InvertStep = false;
1155         AddRecPhiMatch = PN;
1156         break;
1157       }
1158
1159       // Try whether the phi can be translated into the requested form
1160       // (truncated and/or offset by a constant).
1161       if ((!TruncTy || InvertStep) &&
1162           canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1163         // Record the phi node. But don't stop we might find an exact match
1164         // later.
1165         AddRecPhiMatch = PN;
1166         IncV = TempIncV;
1167         TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1168       }
1169     }
1170
1171     if (AddRecPhiMatch) {
1172       // Potentially, move the increment. We have made sure in
1173       // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1174       if (L == IVIncInsertLoop)
1175         hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1176
1177       // Ok, the add recurrence looks usable.
1178       // Remember this PHI, even in post-inc mode.
1179       InsertedValues.insert(AddRecPhiMatch);
1180       // Remember the increment.
1181       rememberInstruction(IncV);
1182       return AddRecPhiMatch;
1183     }
1184   }
1185
1186   // Save the original insertion point so we can restore it when we're done.
1187   BuilderType::InsertPointGuard Guard(Builder);
1188
1189   // Another AddRec may need to be recursively expanded below. For example, if
1190   // this AddRec is quadratic, the StepV may itself be an AddRec in this
1191   // loop. Remove this loop from the PostIncLoops set before expanding such
1192   // AddRecs. Otherwise, we cannot find a valid position for the step
1193   // (i.e. StepV can never dominate its loop header).  Ideally, we could do
1194   // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1195   // so it's not worth implementing SmallPtrSet::swap.
1196   PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1197   PostIncLoops.clear();
1198
1199   // Expand code for the start value.
1200   Value *StartV =
1201       expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
1202
1203   // StartV must be hoisted into L's preheader to dominate the new phi.
1204   assert(!isa<Instruction>(StartV) ||
1205          SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1206                                  L->getHeader()));
1207
1208   // Expand code for the step value. Do this before creating the PHI so that PHI
1209   // reuse code doesn't see an incomplete PHI.
1210   const SCEV *Step = Normalized->getStepRecurrence(SE);
1211   // If the stride is negative, insert a sub instead of an add for the increment
1212   // (unless it's a constant, because subtracts of constants are canonicalized
1213   // to adds).
1214   bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1215   if (useSubtract)
1216     Step = SE.getNegativeSCEV(Step);
1217   // Expand the step somewhere that dominates the loop header.
1218   Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1219
1220   // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1221   // we actually do emit an addition.  It does not apply if we emit a
1222   // subtraction.
1223   bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1224   bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1225
1226   // Create the PHI.
1227   BasicBlock *Header = L->getHeader();
1228   Builder.SetInsertPoint(Header, Header->begin());
1229   pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1230   PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1231                                   Twine(IVName) + ".iv");
1232   rememberInstruction(PN);
1233
1234   // Create the step instructions and populate the PHI.
1235   for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1236     BasicBlock *Pred = *HPI;
1237
1238     // Add a start value.
1239     if (!L->contains(Pred)) {
1240       PN->addIncoming(StartV, Pred);
1241       continue;
1242     }
1243
1244     // Create a step value and add it to the PHI.
1245     // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1246     // instructions at IVIncInsertPos.
1247     Instruction *InsertPos = L == IVIncInsertLoop ?
1248       IVIncInsertPos : Pred->getTerminator();
1249     Builder.SetInsertPoint(InsertPos);
1250     Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1251
1252     if (isa<OverflowingBinaryOperator>(IncV)) {
1253       if (IncrementIsNUW)
1254         cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1255       if (IncrementIsNSW)
1256         cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1257     }
1258     PN->addIncoming(IncV, Pred);
1259   }
1260
1261   // After expanding subexpressions, restore the PostIncLoops set so the caller
1262   // can ensure that IVIncrement dominates the current uses.
1263   PostIncLoops = SavedPostIncLoops;
1264
1265   // Remember this PHI, even in post-inc mode.
1266   InsertedValues.insert(PN);
1267
1268   return PN;
1269 }
1270
1271 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1272   Type *STy = S->getType();
1273   Type *IntTy = SE.getEffectiveSCEVType(STy);
1274   const Loop *L = S->getLoop();
1275
1276   // Determine a normalized form of this expression, which is the expression
1277   // before any post-inc adjustment is made.
1278   const SCEVAddRecExpr *Normalized = S;
1279   if (PostIncLoops.count(L)) {
1280     PostIncLoopSet Loops;
1281     Loops.insert(L);
1282     Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1283         Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
1284   }
1285
1286   // Strip off any non-loop-dominating component from the addrec start.
1287   const SCEV *Start = Normalized->getStart();
1288   const SCEV *PostLoopOffset = nullptr;
1289   if (!SE.properlyDominates(Start, L->getHeader())) {
1290     PostLoopOffset = Start;
1291     Start = SE.getConstant(Normalized->getType(), 0);
1292     Normalized = cast<SCEVAddRecExpr>(
1293       SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1294                        Normalized->getLoop(),
1295                        Normalized->getNoWrapFlags(SCEV::FlagNW)));
1296   }
1297
1298   // Strip off any non-loop-dominating component from the addrec step.
1299   const SCEV *Step = Normalized->getStepRecurrence(SE);
1300   const SCEV *PostLoopScale = nullptr;
1301   if (!SE.dominates(Step, L->getHeader())) {
1302     PostLoopScale = Step;
1303     Step = SE.getConstant(Normalized->getType(), 1);
1304     Normalized =
1305       cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1306                              Start, Step, Normalized->getLoop(),
1307                              Normalized->getNoWrapFlags(SCEV::FlagNW)));
1308   }
1309
1310   // Expand the core addrec. If we need post-loop scaling, force it to
1311   // expand to an integer type to avoid the need for additional casting.
1312   Type *ExpandTy = PostLoopScale ? IntTy : STy;
1313   // In some cases, we decide to reuse an existing phi node but need to truncate
1314   // it and/or invert the step.
1315   Type *TruncTy = nullptr;
1316   bool InvertStep = false;
1317   PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1318                                           TruncTy, InvertStep);
1319
1320   // Accommodate post-inc mode, if necessary.
1321   Value *Result;
1322   if (!PostIncLoops.count(L))
1323     Result = PN;
1324   else {
1325     // In PostInc mode, use the post-incremented value.
1326     BasicBlock *LatchBlock = L->getLoopLatch();
1327     assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1328     Result = PN->getIncomingValueForBlock(LatchBlock);
1329
1330     // For an expansion to use the postinc form, the client must call
1331     // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1332     // or dominated by IVIncInsertPos.
1333     if (isa<Instruction>(Result) &&
1334         !SE.DT.dominates(cast<Instruction>(Result),
1335                          &*Builder.GetInsertPoint())) {
1336       // The induction variable's postinc expansion does not dominate this use.
1337       // IVUsers tries to prevent this case, so it is rare. However, it can
1338       // happen when an IVUser outside the loop is not dominated by the latch
1339       // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1340       // all cases. Consider a phi outide whose operand is replaced during
1341       // expansion with the value of the postinc user. Without fundamentally
1342       // changing the way postinc users are tracked, the only remedy is
1343       // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1344       // but hopefully expandCodeFor handles that.
1345       bool useSubtract =
1346         !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1347       if (useSubtract)
1348         Step = SE.getNegativeSCEV(Step);
1349       Value *StepV;
1350       {
1351         // Expand the step somewhere that dominates the loop header.
1352         BuilderType::InsertPointGuard Guard(Builder);
1353         StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1354       }
1355       Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1356     }
1357   }
1358
1359   // We have decided to reuse an induction variable of a dominating loop. Apply
1360   // truncation and/or invertion of the step.
1361   if (TruncTy) {
1362     Type *ResTy = Result->getType();
1363     // Normalize the result type.
1364     if (ResTy != SE.getEffectiveSCEVType(ResTy))
1365       Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1366     // Truncate the result.
1367     if (TruncTy != Result->getType()) {
1368       Result = Builder.CreateTrunc(Result, TruncTy);
1369       rememberInstruction(Result);
1370     }
1371     // Invert the result.
1372     if (InvertStep) {
1373       Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1374                                  Result);
1375       rememberInstruction(Result);
1376     }
1377   }
1378
1379   // Re-apply any non-loop-dominating scale.
1380   if (PostLoopScale) {
1381     assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1382     Result = InsertNoopCastOfTo(Result, IntTy);
1383     Result = Builder.CreateMul(Result,
1384                                expandCodeFor(PostLoopScale, IntTy));
1385     rememberInstruction(Result);
1386   }
1387
1388   // Re-apply any non-loop-dominating offset.
1389   if (PostLoopOffset) {
1390     if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1391       const SCEV *const OffsetArray[1] = { PostLoopOffset };
1392       Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1393     } else {
1394       Result = InsertNoopCastOfTo(Result, IntTy);
1395       Result = Builder.CreateAdd(Result,
1396                                  expandCodeFor(PostLoopOffset, IntTy));
1397       rememberInstruction(Result);
1398     }
1399   }
1400
1401   return Result;
1402 }
1403
1404 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1405   if (!CanonicalMode) return expandAddRecExprLiterally(S);
1406
1407   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1408   const Loop *L = S->getLoop();
1409
1410   // First check for an existing canonical IV in a suitable type.
1411   PHINode *CanonicalIV = nullptr;
1412   if (PHINode *PN = L->getCanonicalInductionVariable())
1413     if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1414       CanonicalIV = PN;
1415
1416   // Rewrite an AddRec in terms of the canonical induction variable, if
1417   // its type is more narrow.
1418   if (CanonicalIV &&
1419       SE.getTypeSizeInBits(CanonicalIV->getType()) >
1420       SE.getTypeSizeInBits(Ty)) {
1421     SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1422     for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1423       NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1424     Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1425                                        S->getNoWrapFlags(SCEV::FlagNW)));
1426     BasicBlock::iterator NewInsertPt = findInsertPointAfter(
1427         cast<Instruction>(V), SE.DT, Builder.GetInsertBlock());
1428     V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1429                       &*NewInsertPt);
1430     return V;
1431   }
1432
1433   // {X,+,F} --> X + {0,+,F}
1434   if (!S->getStart()->isZero()) {
1435     SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1436     NewOps[0] = SE.getConstant(Ty, 0);
1437     const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1438                                         S->getNoWrapFlags(SCEV::FlagNW));
1439
1440     // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1441     // comments on expandAddToGEP for details.
1442     const SCEV *Base = S->getStart();
1443     const SCEV *RestArray[1] = { Rest };
1444     // Dig into the expression to find the pointer base for a GEP.
1445     ExposePointerBase(Base, RestArray[0], SE);
1446     // If we found a pointer, expand the AddRec with a GEP.
1447     if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1448       // Make sure the Base isn't something exotic, such as a multiplied
1449       // or divided pointer value. In those cases, the result type isn't
1450       // actually a pointer type.
1451       if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1452         Value *StartV = expand(Base);
1453         assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1454         return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1455       }
1456     }
1457
1458     // Just do a normal add. Pre-expand the operands to suppress folding.
1459     return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1460                                 SE.getUnknown(expand(Rest))));
1461   }
1462
1463   // If we don't yet have a canonical IV, create one.
1464   if (!CanonicalIV) {
1465     // Create and insert the PHI node for the induction variable in the
1466     // specified loop.
1467     BasicBlock *Header = L->getHeader();
1468     pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1469     CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1470                                   &Header->front());
1471     rememberInstruction(CanonicalIV);
1472
1473     SmallSet<BasicBlock *, 4> PredSeen;
1474     Constant *One = ConstantInt::get(Ty, 1);
1475     for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1476       BasicBlock *HP = *HPI;
1477       if (!PredSeen.insert(HP).second) {
1478         // There must be an incoming value for each predecessor, even the
1479         // duplicates!
1480         CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1481         continue;
1482       }
1483
1484       if (L->contains(HP)) {
1485         // Insert a unit add instruction right before the terminator
1486         // corresponding to the back-edge.
1487         Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1488                                                      "indvar.next",
1489                                                      HP->getTerminator());
1490         Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1491         rememberInstruction(Add);
1492         CanonicalIV->addIncoming(Add, HP);
1493       } else {
1494         CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1495       }
1496     }
1497   }
1498
1499   // {0,+,1} --> Insert a canonical induction variable into the loop!
1500   if (S->isAffine() && S->getOperand(1)->isOne()) {
1501     assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1502            "IVs with types different from the canonical IV should "
1503            "already have been handled!");
1504     return CanonicalIV;
1505   }
1506
1507   // {0,+,F} --> {0,+,1} * F
1508
1509   // If this is a simple linear addrec, emit it now as a special case.
1510   if (S->isAffine())    // {0,+,F} --> i*F
1511     return
1512       expand(SE.getTruncateOrNoop(
1513         SE.getMulExpr(SE.getUnknown(CanonicalIV),
1514                       SE.getNoopOrAnyExtend(S->getOperand(1),
1515                                             CanonicalIV->getType())),
1516         Ty));
1517
1518   // If this is a chain of recurrences, turn it into a closed form, using the
1519   // folders, then expandCodeFor the closed form.  This allows the folders to
1520   // simplify the expression without having to build a bunch of special code
1521   // into this folder.
1522   const SCEV *IH = SE.getUnknown(CanonicalIV);   // Get I as a "symbolic" SCEV.
1523
1524   // Promote S up to the canonical IV type, if the cast is foldable.
1525   const SCEV *NewS = S;
1526   const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1527   if (isa<SCEVAddRecExpr>(Ext))
1528     NewS = Ext;
1529
1530   const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1531   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
1532
1533   // Truncate the result down to the original type, if needed.
1534   const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1535   return expand(T);
1536 }
1537
1538 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1539   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1540   Value *V = expandCodeFor(S->getOperand(),
1541                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
1542   Value *I = Builder.CreateTrunc(V, Ty);
1543   rememberInstruction(I);
1544   return I;
1545 }
1546
1547 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1548   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1549   Value *V = expandCodeFor(S->getOperand(),
1550                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
1551   Value *I = Builder.CreateZExt(V, Ty);
1552   rememberInstruction(I);
1553   return I;
1554 }
1555
1556 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1557   Type *Ty = SE.getEffectiveSCEVType(S->getType());
1558   Value *V = expandCodeFor(S->getOperand(),
1559                            SE.getEffectiveSCEVType(S->getOperand()->getType()));
1560   Value *I = Builder.CreateSExt(V, Ty);
1561   rememberInstruction(I);
1562   return I;
1563 }
1564
1565 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1566   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1567   Type *Ty = LHS->getType();
1568   for (int i = S->getNumOperands()-2; i >= 0; --i) {
1569     // In the case of mixed integer and pointer types, do the
1570     // rest of the comparisons as integer.
1571     if (S->getOperand(i)->getType() != Ty) {
1572       Ty = SE.getEffectiveSCEVType(Ty);
1573       LHS = InsertNoopCastOfTo(LHS, Ty);
1574     }
1575     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1576     Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1577     rememberInstruction(ICmp);
1578     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1579     rememberInstruction(Sel);
1580     LHS = Sel;
1581   }
1582   // In the case of mixed integer and pointer types, cast the
1583   // final result back to the pointer type.
1584   if (LHS->getType() != S->getType())
1585     LHS = InsertNoopCastOfTo(LHS, S->getType());
1586   return LHS;
1587 }
1588
1589 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1590   Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1591   Type *Ty = LHS->getType();
1592   for (int i = S->getNumOperands()-2; i >= 0; --i) {
1593     // In the case of mixed integer and pointer types, do the
1594     // rest of the comparisons as integer.
1595     if (S->getOperand(i)->getType() != Ty) {
1596       Ty = SE.getEffectiveSCEVType(Ty);
1597       LHS = InsertNoopCastOfTo(LHS, Ty);
1598     }
1599     Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1600     Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1601     rememberInstruction(ICmp);
1602     Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1603     rememberInstruction(Sel);
1604     LHS = Sel;
1605   }
1606   // In the case of mixed integer and pointer types, cast the
1607   // final result back to the pointer type.
1608   if (LHS->getType() != S->getType())
1609     LHS = InsertNoopCastOfTo(LHS, S->getType());
1610   return LHS;
1611 }
1612
1613 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1614                                    Instruction *IP) {
1615   assert(IP);
1616   Builder.SetInsertPoint(IP);
1617   return expandCodeFor(SH, Ty);
1618 }
1619
1620 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1621   // Expand the code for this SCEV.
1622   Value *V = expand(SH);
1623   if (Ty) {
1624     assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1625            "non-trivial casts should be done with the SCEVs directly!");
1626     V = InsertNoopCastOfTo(V, Ty);
1627   }
1628   return V;
1629 }
1630
1631 Value *SCEVExpander::expand(const SCEV *S) {
1632   // Compute an insertion point for this SCEV object. Hoist the instructions
1633   // as far out in the loop nest as possible.
1634   Instruction *InsertPt = &*Builder.GetInsertPoint();
1635   for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1636        L = L->getParentLoop())
1637     if (SE.isLoopInvariant(S, L)) {
1638       if (!L) break;
1639       if (BasicBlock *Preheader = L->getLoopPreheader())
1640         InsertPt = Preheader->getTerminator();
1641       else {
1642         // LSR sets the insertion point for AddRec start/step values to the
1643         // block start to simplify value reuse, even though it's an invalid
1644         // position. SCEVExpander must correct for this in all cases.
1645         InsertPt = &*L->getHeader()->getFirstInsertionPt();
1646       }
1647     } else {
1648       // If the SCEV is computable at this level, insert it into the header
1649       // after the PHIs (and after any other instructions that we've inserted
1650       // there) so that it is guaranteed to dominate any user inside the loop.
1651       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1652         InsertPt = &*L->getHeader()->getFirstInsertionPt();
1653       while (InsertPt != Builder.GetInsertPoint()
1654              && (isInsertedInstruction(InsertPt)
1655                  || isa<DbgInfoIntrinsic>(InsertPt))) {
1656         InsertPt = &*std::next(InsertPt->getIterator());
1657       }
1658       break;
1659     }
1660
1661   // Check to see if we already expanded this here.
1662   std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1663     I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1664   if (I != InsertedExpressions.end())
1665     return I->second;
1666
1667   BuilderType::InsertPointGuard Guard(Builder);
1668   Builder.SetInsertPoint(InsertPt);
1669
1670   // Expand the expression into instructions.
1671   Value *V = visit(S);
1672
1673   // Remember the expanded value for this SCEV at this location.
1674   //
1675   // This is independent of PostIncLoops. The mapped value simply materializes
1676   // the expression at this insertion point. If the mapped value happened to be
1677   // a postinc expansion, it could be reused by a non-postinc user, but only if
1678   // its insertion point was already at the head of the loop.
1679   InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1680   return V;
1681 }
1682
1683 void SCEVExpander::rememberInstruction(Value *I) {
1684   if (!PostIncLoops.empty())
1685     InsertedPostIncValues.insert(I);
1686   else
1687     InsertedValues.insert(I);
1688 }
1689
1690 /// getOrInsertCanonicalInductionVariable - This method returns the
1691 /// canonical induction variable of the specified type for the specified
1692 /// loop (inserting one if there is none).  A canonical induction variable
1693 /// starts at zero and steps by one on each iteration.
1694 PHINode *
1695 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1696                                                     Type *Ty) {
1697   assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1698
1699   // Build a SCEV for {0,+,1}<L>.
1700   // Conservatively use FlagAnyWrap for now.
1701   const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1702                                    SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1703
1704   // Emit code for it.
1705   BuilderType::InsertPointGuard Guard(Builder);
1706   PHINode *V =
1707       cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1708
1709   return V;
1710 }
1711
1712 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1713 /// replace them with their most canonical representative. Return the number of
1714 /// phis eliminated.
1715 ///
1716 /// This does not depend on any SCEVExpander state but should be used in
1717 /// the same context that SCEVExpander is used.
1718 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1719                                            SmallVectorImpl<WeakVH> &DeadInsts,
1720                                            const TargetTransformInfo *TTI) {
1721   // Find integer phis in order of increasing width.
1722   SmallVector<PHINode*, 8> Phis;
1723   for (BasicBlock::iterator I = L->getHeader()->begin();
1724        PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1725     Phis.push_back(Phi);
1726   }
1727   if (TTI)
1728     std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1729       // Put pointers at the back and make sure pointer < pointer = false.
1730       if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1731         return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1732       return RHS->getType()->getPrimitiveSizeInBits() <
1733              LHS->getType()->getPrimitiveSizeInBits();
1734     });
1735
1736   unsigned NumElim = 0;
1737   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1738   // Process phis from wide to narrow. Map wide phis to their truncation
1739   // so narrow phis can reuse them.
1740   for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1741          PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1742     PHINode *Phi = *PIter;
1743
1744     // Fold constant phis. They may be congruent to other constant phis and
1745     // would confuse the logic below that expects proper IVs.
1746     if (Value *V = SimplifyInstruction(Phi, DL, &SE.TLI, &SE.DT, &SE.AC)) {
1747       Phi->replaceAllUsesWith(V);
1748       DeadInsts.emplace_back(Phi);
1749       ++NumElim;
1750       DEBUG_WITH_TYPE(DebugType, dbgs()
1751                       << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1752       continue;
1753     }
1754
1755     if (!SE.isSCEVable(Phi->getType()))
1756       continue;
1757
1758     PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1759     if (!OrigPhiRef) {
1760       OrigPhiRef = Phi;
1761       if (Phi->getType()->isIntegerTy() && TTI
1762           && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1763         // This phi can be freely truncated to the narrowest phi type. Map the
1764         // truncated expression to it so it will be reused for narrow types.
1765         const SCEV *TruncExpr =
1766           SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1767         ExprToIVMap[TruncExpr] = Phi;
1768       }
1769       continue;
1770     }
1771
1772     // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1773     // sense.
1774     if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1775       continue;
1776
1777     if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1778       Instruction *OrigInc =
1779         cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1780       Instruction *IsomorphicInc =
1781         cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1782
1783       // If this phi has the same width but is more canonical, replace the
1784       // original with it. As part of the "more canonical" determination,
1785       // respect a prior decision to use an IV chain.
1786       if (OrigPhiRef->getType() == Phi->getType()
1787           && !(ChainedPhis.count(Phi)
1788                || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1789           && (ChainedPhis.count(Phi)
1790               || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1791         std::swap(OrigPhiRef, Phi);
1792         std::swap(OrigInc, IsomorphicInc);
1793       }
1794       // Replacing the congruent phi is sufficient because acyclic redundancy
1795       // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1796       // that a phi is congruent, it's often the head of an IV user cycle that
1797       // is isomorphic with the original phi. It's worth eagerly cleaning up the
1798       // common case of a single IV increment so that DeleteDeadPHIs can remove
1799       // cycles that had postinc uses.
1800       const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1801                                                    IsomorphicInc->getType());
1802       if (OrigInc != IsomorphicInc
1803           && TruncExpr == SE.getSCEV(IsomorphicInc)
1804           && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1805               || hoistIVInc(OrigInc, IsomorphicInc))) {
1806         DEBUG_WITH_TYPE(DebugType, dbgs()
1807                         << "INDVARS: Eliminated congruent iv.inc: "
1808                         << *IsomorphicInc << '\n');
1809         Value *NewInc = OrigInc;
1810         if (OrigInc->getType() != IsomorphicInc->getType()) {
1811           Instruction *IP = nullptr;
1812           if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1813             IP = &*PN->getParent()->getFirstInsertionPt();
1814           else
1815             IP = OrigInc->getNextNode();
1816
1817           IRBuilder<> Builder(IP);
1818           Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1819           NewInc = Builder.
1820             CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1821         }
1822         IsomorphicInc->replaceAllUsesWith(NewInc);
1823         DeadInsts.emplace_back(IsomorphicInc);
1824       }
1825     }
1826     DEBUG_WITH_TYPE(DebugType, dbgs()
1827                     << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1828     ++NumElim;
1829     Value *NewIV = OrigPhiRef;
1830     if (OrigPhiRef->getType() != Phi->getType()) {
1831       IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
1832       Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1833       NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1834     }
1835     Phi->replaceAllUsesWith(NewIV);
1836     DeadInsts.emplace_back(Phi);
1837   }
1838   return NumElim;
1839 }
1840
1841 Value *SCEVExpander::findExistingExpansion(const SCEV *S,
1842                                            const Instruction *At, Loop *L) {
1843   using namespace llvm::PatternMatch;
1844
1845   SmallVector<BasicBlock *, 4> ExitingBlocks;
1846   L->getExitingBlocks(ExitingBlocks);
1847
1848   // Look for suitable value in simple conditions at the loop exits.
1849   for (BasicBlock *BB : ExitingBlocks) {
1850     ICmpInst::Predicate Pred;
1851     Instruction *LHS, *RHS;
1852     BasicBlock *TrueBB, *FalseBB;
1853
1854     if (!match(BB->getTerminator(),
1855                m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1856                     TrueBB, FalseBB)))
1857       continue;
1858
1859     if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1860       return LHS;
1861
1862     if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1863       return RHS;
1864   }
1865
1866   // There is potential to make this significantly smarter, but this simple
1867   // heuristic already gets some interesting cases.
1868
1869   // Can not find suitable value.
1870   return nullptr;
1871 }
1872
1873 bool SCEVExpander::isHighCostExpansionHelper(
1874     const SCEV *S, Loop *L, const Instruction *At,
1875     SmallPtrSetImpl<const SCEV *> &Processed) {
1876
1877   // If we can find an existing value for this scev avaliable at the point "At"
1878   // then consider the expression cheap.
1879   if (At && findExistingExpansion(S, At, L) != nullptr)
1880     return false;
1881
1882   // Zero/One operand expressions
1883   switch (S->getSCEVType()) {
1884   case scUnknown:
1885   case scConstant:
1886     return false;
1887   case scTruncate:
1888     return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1889                                      L, At, Processed);
1890   case scZeroExtend:
1891     return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1892                                      L, At, Processed);
1893   case scSignExtend:
1894     return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1895                                      L, At, Processed);
1896   }
1897
1898   if (!Processed.insert(S).second)
1899     return false;
1900
1901   if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1902     // If the divisor is a power of two and the SCEV type fits in a native
1903     // integer, consider the division cheap irrespective of whether it occurs in
1904     // the user code since it can be lowered into a right shift.
1905     if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1906       if (SC->getValue()->getValue().isPowerOf2()) {
1907         const DataLayout &DL =
1908             L->getHeader()->getParent()->getParent()->getDataLayout();
1909         unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1910         return DL.isIllegalInteger(Width);
1911       }
1912
1913     // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1914     // HowManyLessThans produced to compute a precise expression, rather than a
1915     // UDiv from the user's code. If we can't find a UDiv in the code with some
1916     // simple searching, assume the former consider UDivExpr expensive to
1917     // compute.
1918     BasicBlock *ExitingBB = L->getExitingBlock();
1919     if (!ExitingBB)
1920       return true;
1921
1922     // At the beginning of this function we already tried to find existing value
1923     // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1924     // involving division. This is just a simple search heuristic.
1925     if (!At)
1926       At = &ExitingBB->back();
1927     if (!findExistingExpansion(
1928             SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
1929       return true;
1930   }
1931
1932   // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1933   // the exit condition.
1934   if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1935     return true;
1936
1937   // Recurse past nary expressions, which commonly occur in the
1938   // BackedgeTakenCount. They may already exist in program code, and if not,
1939   // they are not too expensive rematerialize.
1940   if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1941     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
1942          I != E; ++I) {
1943       if (isHighCostExpansionHelper(*I, L, At, Processed))
1944         return true;
1945     }
1946   }
1947
1948   // If we haven't recognized an expensive SCEV pattern, assume it's an
1949   // expression produced by program code.
1950   return false;
1951 }
1952
1953 namespace {
1954 // Search for a SCEV subexpression that is not safe to expand.  Any expression
1955 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1956 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
1957 // instruction, but the important thing is that we prove the denominator is
1958 // nonzero before expansion.
1959 //
1960 // IVUsers already checks that IV-derived expressions are safe. So this check is
1961 // only needed when the expression includes some subexpression that is not IV
1962 // derived.
1963 //
1964 // Currently, we only allow division by a nonzero constant here. If this is
1965 // inadequate, we could easily allow division by SCEVUnknown by using
1966 // ValueTracking to check isKnownNonZero().
1967 //
1968 // We cannot generally expand recurrences unless the step dominates the loop
1969 // header. The expander handles the special case of affine recurrences by
1970 // scaling the recurrence outside the loop, but this technique isn't generally
1971 // applicable. Expanding a nested recurrence outside a loop requires computing
1972 // binomial coefficients. This could be done, but the recurrence has to be in a
1973 // perfectly reduced form, which can't be guaranteed.
1974 struct SCEVFindUnsafe {
1975   ScalarEvolution &SE;
1976   bool IsUnsafe;
1977
1978   SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
1979
1980   bool follow(const SCEV *S) {
1981     if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1982       const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1983       if (!SC || SC->getValue()->isZero()) {
1984         IsUnsafe = true;
1985         return false;
1986       }
1987     }
1988     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1989       const SCEV *Step = AR->getStepRecurrence(SE);
1990       if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
1991         IsUnsafe = true;
1992         return false;
1993       }
1994     }
1995     return true;
1996   }
1997   bool isDone() const { return IsUnsafe; }
1998 };
1999 }
2000
2001 namespace llvm {
2002 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2003   SCEVFindUnsafe Search(SE);
2004   visitAll(S, Search);
2005   return !Search.IsUnsafe;
2006 }
2007 }