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