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