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