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