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