LLVM  9.0.0svn
ScalarEvolutionExpander.cpp
Go to the documentation of this file.
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution expander,
10 // which is used to generate the code corresponding to a given scalar evolution
11 // expression.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Support/Debug.h"
29 
30 using namespace llvm;
31 using namespace PatternMatch;
32 
33 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
34 /// reusing an existing cast if a suitable one exists, moving an existing
35 /// cast if a suitable one exists but isn't in the right place, or
36 /// creating a new one.
37 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
40  // This function must be called with the builder having a valid insertion
41  // point. It doesn't need to be the actual IP where the uses of the returned
42  // cast will be added, but it must dominate such IP.
43  // We use this precondition to produce a cast that will dominate all its
44  // uses. In particular, this is crucial for the case where the builder's
45  // insertion point *is* the point where we were asked to put the cast.
46  // Since we don't know the builder's insertion point is actually
47  // where the uses will be added (only that it dominates it), we are
48  // not allowed to move it.
49  BasicBlock::iterator BIP = Builder.GetInsertPoint();
50 
51  Instruction *Ret = nullptr;
52 
53  // Check to see if there is already a cast!
54  for (User *U : V->users())
55  if (U->getType() == Ty)
56  if (CastInst *CI = dyn_cast<CastInst>(U))
57  if (CI->getOpcode() == Op) {
58  // If the cast isn't where we want it, create a new cast at IP.
59  // Likewise, do not reuse a cast at BIP because it must dominate
60  // instructions that might be inserted before BIP.
61  if (BasicBlock::iterator(CI) != IP || BIP == IP) {
62  // Create a new cast, and leave the old cast in place in case
63  // it is being used as an insert point. Clear its operand
64  // so that it doesn't hold anything live.
65  Ret = CastInst::Create(Op, V, Ty, "", &*IP);
66  Ret->takeName(CI);
67  CI->replaceAllUsesWith(Ret);
68  CI->setOperand(0, UndefValue::get(V->getType()));
69  break;
70  }
71  Ret = CI;
72  break;
73  }
74 
75  // Create a new cast.
76  if (!Ret)
77  Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
78 
79  // We assert at the end of the function since IP might point to an
80  // instruction with different dominance properties than a cast
81  // (an invoke for example) and not dominate BIP (but the cast does).
82  assert(SE.DT.dominates(Ret, &*BIP));
83 
84  rememberInstruction(Ret);
85  return Ret;
86 }
87 
89  BasicBlock *MustDominate) {
91  if (auto *II = dyn_cast<InvokeInst>(I))
92  IP = II->getNormalDest()->begin();
93 
94  while (isa<PHINode>(IP))
95  ++IP;
96 
97  if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
98  ++IP;
99  } else if (isa<CatchSwitchInst>(IP)) {
100  IP = MustDominate->getFirstInsertionPt();
101  } else {
102  assert(!IP->isEHPad() && "unexpected eh pad!");
103  }
104 
105  return IP;
106 }
107 
108 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
109 /// which must be possible with a noop cast, doing what we can to share
110 /// the casts.
111 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
112  Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
113  assert((Op == Instruction::BitCast ||
114  Op == Instruction::PtrToInt ||
115  Op == Instruction::IntToPtr) &&
116  "InsertNoopCastOfTo cannot perform non-noop casts!");
117  assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
118  "InsertNoopCastOfTo cannot change sizes!");
119 
120  // Short-circuit unnecessary bitcasts.
121  if (Op == Instruction::BitCast) {
122  if (V->getType() == Ty)
123  return V;
124  if (CastInst *CI = dyn_cast<CastInst>(V)) {
125  if (CI->getOperand(0)->getType() == Ty)
126  return CI->getOperand(0);
127  }
128  }
129  // Short-circuit unnecessary inttoptr<->ptrtoint casts.
130  if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
131  SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
132  if (CastInst *CI = dyn_cast<CastInst>(V))
133  if ((CI->getOpcode() == Instruction::PtrToInt ||
134  CI->getOpcode() == Instruction::IntToPtr) &&
135  SE.getTypeSizeInBits(CI->getType()) ==
136  SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
137  return CI->getOperand(0);
138  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
139  if ((CE->getOpcode() == Instruction::PtrToInt ||
140  CE->getOpcode() == Instruction::IntToPtr) &&
141  SE.getTypeSizeInBits(CE->getType()) ==
142  SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
143  return CE->getOperand(0);
144  }
145 
146  // Fold a cast of a constant.
147  if (Constant *C = dyn_cast<Constant>(V))
148  return ConstantExpr::getCast(Op, C, Ty);
149 
150  // Cast the argument at the beginning of the entry block, after
151  // any bitcasts of other arguments.
152  if (Argument *A = dyn_cast<Argument>(V)) {
153  BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
154  while ((isa<BitCastInst>(IP) &&
155  isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
156  cast<BitCastInst>(IP)->getOperand(0) != A) ||
157  isa<DbgInfoIntrinsic>(IP))
158  ++IP;
159  return ReuseOrCreateCast(A, Ty, Op, IP);
160  }
161 
162  // Cast the instruction immediately after the instruction.
163  Instruction *I = cast<Instruction>(V);
164  BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
165  return ReuseOrCreateCast(I, Ty, Op, IP);
166 }
167 
168 /// InsertBinop - Insert the specified binary operator, doing a small amount
169 /// of work to avoid inserting an obviously redundant operation, and hoisting
170 /// to an outer loop when the opportunity is there and it is safe.
171 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
172  Value *LHS, Value *RHS, bool IsSafeToHoist) {
173  // Fold a binop with constant operands.
174  if (Constant *CLHS = dyn_cast<Constant>(LHS))
175  if (Constant *CRHS = dyn_cast<Constant>(RHS))
176  return ConstantExpr::get(Opcode, CLHS, CRHS);
177 
178  // Do a quick scan to see if we have this binop nearby. If so, reuse it.
179  unsigned ScanLimit = 6;
180  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
181  // Scanning starts from the last instruction before the insertion point.
182  BasicBlock::iterator IP = Builder.GetInsertPoint();
183  if (IP != BlockBegin) {
184  --IP;
185  for (; ScanLimit; --IP, --ScanLimit) {
186  // Don't count dbg.value against the ScanLimit, to avoid perturbing the
187  // generated code.
188  if (isa<DbgInfoIntrinsic>(IP))
189  ScanLimit++;
190 
191  // Conservatively, do not use any instruction which has any of wrap/exact
192  // flags installed.
193  // TODO: Instead of simply disable poison instructions we can be clever
194  // here and match SCEV to this instruction.
195  auto canGeneratePoison = [](Instruction *I) {
196  if (isa<OverflowingBinaryOperator>(I) &&
197  (I->hasNoSignedWrap() || I->hasNoUnsignedWrap()))
198  return true;
199  if (isa<PossiblyExactOperator>(I) && I->isExact())
200  return true;
201  return false;
202  };
203  if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
204  IP->getOperand(1) == RHS && !canGeneratePoison(&*IP))
205  return &*IP;
206  if (IP == BlockBegin) break;
207  }
208  }
209 
210  // Save the original insertion point so we can restore it when we're done.
211  DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
212  SCEVInsertPointGuard Guard(Builder, this);
213 
214  if (IsSafeToHoist) {
215  // Move the insertion point out of as many loops as we can.
216  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
217  if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
218  BasicBlock *Preheader = L->getLoopPreheader();
219  if (!Preheader) break;
220 
221  // Ok, move up a level.
222  Builder.SetInsertPoint(Preheader->getTerminator());
223  }
224  }
225 
226  // If we haven't found this binop, insert it.
227  Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
228  BO->setDebugLoc(Loc);
229  rememberInstruction(BO);
230 
231  return BO;
232 }
233 
234 /// FactorOutConstant - Test if S is divisible by Factor, using signed
235 /// division. If so, update S with Factor divided out and return true.
236 /// S need not be evenly divisible if a reasonable remainder can be
237 /// computed.
238 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
239 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
240 /// check to see if the divide was folded.
241 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
242  const SCEV *Factor, ScalarEvolution &SE,
243  const DataLayout &DL) {
244  // Everything is divisible by one.
245  if (Factor->isOne())
246  return true;
247 
248  // x/x == 1.
249  if (S == Factor) {
250  S = SE.getConstant(S->getType(), 1);
251  return true;
252  }
253 
254  // For a Constant, check for a multiple of the given factor.
255  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
256  // 0/x == 0.
257  if (C->isZero())
258  return true;
259  // Check for divisibility.
260  if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
261  ConstantInt *CI =
262  ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
263  // If the quotient is zero and the remainder is non-zero, reject
264  // the value at this scale. It will be considered for subsequent
265  // smaller scales.
266  if (!CI->isZero()) {
267  const SCEV *Div = SE.getConstant(CI);
268  S = Div;
269  Remainder = SE.getAddExpr(
270  Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
271  return true;
272  }
273  }
274  }
275 
276  // In a Mul, check if there is a constant operand which is a multiple
277  // of the given factor.
278  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
279  // Size is known, check if there is a constant operand which is a multiple
280  // of the given factor. If so, we can factor it.
281  const SCEVConstant *FC = cast<SCEVConstant>(Factor);
282  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
283  if (!C->getAPInt().srem(FC->getAPInt())) {
284  SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
285  NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
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 ///
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 ///
344  Type *Ty,
345  ScalarEvolution &SE) {
346  // Find the 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.
426  if (ElTy->isSized()) {
427  const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
428  if (!ElSize->isZero()) {
430  for (const SCEV *Op : Ops) {
431  const SCEV *Remainder = SE.getConstant(Ty, 0);
432  if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
433  // Op now has ElSize factored out.
434  ScaledOps.push_back(Op);
435  if (!Remainder->isZero())
436  NewOps.push_back(Remainder);
437  AnyNonZeroIndices = true;
438  } else {
439  // The operand was not divisible, so add it to the list of operands
440  // we'll scan next iteration.
441  NewOps.push_back(Op);
442  }
443  }
444  // If we made any changes, update Ops.
445  if (!ScaledOps.empty()) {
446  Ops = NewOps;
447  SimplifyAddOperands(Ops, Ty, SE);
448  }
449  }
450  }
451 
452  // Record the scaled array index for this level of the type. If
453  // we didn't find any operands that could be factored, tentatively
454  // assume that element zero was selected (since the zero offset
455  // would obviously be folded away).
456  Value *Scaled = ScaledOps.empty() ?
458  expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
459  GepIndices.push_back(Scaled);
460 
461  // Collect struct field index operands.
462  while (StructType *STy = dyn_cast<StructType>(ElTy)) {
463  bool FoundFieldNo = false;
464  // An empty struct has no fields.
465  if (STy->getNumElements() == 0) break;
466  // Field offsets are known. See if a constant offset falls within any of
467  // the struct fields.
468  if (Ops.empty())
469  break;
470  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
471  if (SE.getTypeSizeInBits(C->getType()) <= 64) {
472  const StructLayout &SL = *DL.getStructLayout(STy);
473  uint64_t FullOffset = C->getValue()->getZExtValue();
474  if (FullOffset < SL.getSizeInBytes()) {
475  unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
476  GepIndices.push_back(
478  ElTy = STy->getTypeAtIndex(ElIdx);
479  Ops[0] =
480  SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
481  AnyNonZeroIndices = true;
482  FoundFieldNo = true;
483  }
484  }
485  // If no struct field offsets were found, tentatively assume that
486  // field zero was selected (since the zero offset would obviously
487  // be folded away).
488  if (!FoundFieldNo) {
489  ElTy = STy->getTypeAtIndex(0u);
490  GepIndices.push_back(
492  }
493  }
494 
495  if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
496  ElTy = ATy->getElementType();
497  else
498  break;
499  }
500 
501  // If none of the operands were convertible to proper GEP indices, cast
502  // the base to i8* and do an ugly getelementptr with that. It's still
503  // better than ptrtoint+arithmetic+inttoptr at least.
504  if (!AnyNonZeroIndices) {
505  // Cast the base to i8*.
506  V = InsertNoopCastOfTo(V,
508 
509  assert(!isa<Instruction>(V) ||
510  SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
511 
512  // Expand the operands for a plain byte offset.
513  Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
514 
515  // Fold a GEP with constant operands.
516  if (Constant *CLHS = dyn_cast<Constant>(V))
517  if (Constant *CRHS = dyn_cast<Constant>(Idx))
519  CLHS, CRHS);
520 
521  // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
522  unsigned ScanLimit = 6;
523  BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
524  // Scanning starts from the last instruction before the insertion point.
525  BasicBlock::iterator IP = Builder.GetInsertPoint();
526  if (IP != BlockBegin) {
527  --IP;
528  for (; ScanLimit; --IP, --ScanLimit) {
529  // Don't count dbg.value against the ScanLimit, to avoid perturbing the
530  // generated code.
531  if (isa<DbgInfoIntrinsic>(IP))
532  ScanLimit++;
533  if (IP->getOpcode() == Instruction::GetElementPtr &&
534  IP->getOperand(0) == V && IP->getOperand(1) == Idx)
535  return &*IP;
536  if (IP == BlockBegin) break;
537  }
538  }
539 
540  // Save the original insertion point so we can restore it when we're done.
541  SCEVInsertPointGuard Guard(Builder, this);
542 
543  // Move the insertion point out of as many loops as we can.
544  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
545  if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
546  BasicBlock *Preheader = L->getLoopPreheader();
547  if (!Preheader) break;
548 
549  // Ok, move up a level.
550  Builder.SetInsertPoint(Preheader->getTerminator());
551  }
552 
553  // Emit a GEP.
554  Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
555  rememberInstruction(GEP);
556 
557  return GEP;
558  }
559 
560  {
561  SCEVInsertPointGuard Guard(Builder, this);
562 
563  // Move the insertion point out of as many loops as we can.
564  while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
565  if (!L->isLoopInvariant(V)) break;
566 
567  bool AnyIndexNotLoopInvariant = any_of(
568  GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
569 
570  if (AnyIndexNotLoopInvariant)
571  break;
572 
573  BasicBlock *Preheader = L->getLoopPreheader();
574  if (!Preheader) break;
575 
576  // Ok, move up a level.
577  Builder.SetInsertPoint(Preheader->getTerminator());
578  }
579 
580  // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
581  // because ScalarEvolution may have changed the address arithmetic to
582  // compute a value which is beyond the end of the allocated object.
583  Value *Casted = V;
584  if (V->getType() != PTy)
585  Casted = InsertNoopCastOfTo(Casted, PTy);
586  Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
587  Ops.push_back(SE.getUnknown(GEP));
588  rememberInstruction(GEP);
589  }
590 
591  return expand(SE.getAddExpr(Ops));
592 }
593 
594 Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
595  Value *V) {
596  const SCEV *const Ops[1] = {Op};
597  return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
598 }
599 
600 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
601 /// SCEV expansion. If they are nested, this is the most nested. If they are
602 /// neighboring, pick the later.
603 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
604  DominatorTree &DT) {
605  if (!A) return B;
606  if (!B) return A;
607  if (A->contains(B)) return B;
608  if (B->contains(A)) return A;
609  if (DT.dominates(A->getHeader(), B->getHeader())) return B;
610  if (DT.dominates(B->getHeader(), A->getHeader())) return A;
611  return A; // Arbitrarily break the tie.
612 }
613 
614 /// getRelevantLoop - Get the most relevant loop associated with the given
615 /// expression, according to PickMostRelevantLoop.
616 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
617  // Test whether we've already computed the most relevant loop for this SCEV.
618  auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
619  if (!Pair.second)
620  return Pair.first->second;
621 
622  if (isa<SCEVConstant>(S))
623  // A constant has no relevant loops.
624  return nullptr;
625  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
626  if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
627  return Pair.first->second = SE.LI.getLoopFor(I->getParent());
628  // A non-instruction has no relevant loops.
629  return nullptr;
630  }
631  if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
632  const Loop *L = nullptr;
633  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
634  L = AR->getLoop();
635  for (const SCEV *Op : N->operands())
636  L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
637  return RelevantLoops[N] = L;
638  }
639  if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
640  const Loop *Result = getRelevantLoop(C->getOperand());
641  return RelevantLoops[C] = Result;
642  }
643  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
644  const Loop *Result = PickMostRelevantLoop(
645  getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
646  return RelevantLoops[D] = Result;
647  }
648  llvm_unreachable("Unexpected SCEV type!");
649 }
650 
651 namespace {
652 
653 /// LoopCompare - Compare loops by PickMostRelevantLoop.
654 class LoopCompare {
655  DominatorTree &DT;
656 public:
657  explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
658 
659  bool operator()(std::pair<const Loop *, const SCEV *> LHS,
660  std::pair<const Loop *, const SCEV *> RHS) const {
661  // Keep pointer operands sorted at the end.
662  if (LHS.second->getType()->isPointerTy() !=
663  RHS.second->getType()->isPointerTy())
664  return LHS.second->getType()->isPointerTy();
665 
666  // Compare loops with PickMostRelevantLoop.
667  if (LHS.first != RHS.first)
668  return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
669 
670  // If one operand is a non-constant negative and the other is not,
671  // put the non-constant negative on the right so that a sub can
672  // be used instead of a negate and add.
673  if (LHS.second->isNonConstantNegative()) {
674  if (!RHS.second->isNonConstantNegative())
675  return false;
676  } else if (RHS.second->isNonConstantNegative())
677  return true;
678 
679  // Otherwise they are equivalent according to this comparison.
680  return false;
681  }
682 };
683 
684 }
685 
686 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
687  Type *Ty = SE.getEffectiveSCEVType(S->getType());
688 
689  // Collect all the add operands in a loop, along with their associated loops.
690  // Iterate in reverse so that constants are emitted last, all else equal, and
691  // so that pointer operands are inserted first, which the code below relies on
692  // to form more involved GEPs.
694  for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
695  E(S->op_begin()); I != E; ++I)
696  OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
697 
698  // Sort by loop. Use a stable sort so that constants follow non-constants and
699  // pointer operands precede non-pointer operands.
700  llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
701 
702  // Emit instructions to add all the operands. Hoist as much as possible
703  // out of loops, and form meaningful getelementptrs where possible.
704  Value *Sum = nullptr;
705  for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
706  const Loop *CurLoop = I->first;
707  const SCEV *Op = I->second;
708  if (!Sum) {
709  // This is the first operand. Just expand it.
710  Sum = expand(Op);
711  ++I;
712  } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
713  // The running sum expression is a pointer. Try to form a getelementptr
714  // at this level with that as the base.
716  for (; I != E && I->first == CurLoop; ++I) {
717  // If the operand is SCEVUnknown and not instructions, peek through
718  // it, to enable more of it to be folded into the GEP.
719  const SCEV *X = I->second;
720  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
721  if (!isa<Instruction>(U->getValue()))
722  X = SE.getSCEV(U->getValue());
723  NewOps.push_back(X);
724  }
725  Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
726  } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
727  // The running sum is an integer, and there's a pointer at this level.
728  // Try to form a getelementptr. If the running sum is instructions,
729  // use a SCEVUnknown to avoid re-analyzing them.
731  NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
732  SE.getSCEV(Sum));
733  for (++I; I != E && I->first == CurLoop; ++I)
734  NewOps.push_back(I->second);
735  Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
736  } else if (Op->isNonConstantNegative()) {
737  // Instead of doing a negate and add, just do a subtract.
738  Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
739  Sum = InsertNoopCastOfTo(Sum, Ty);
740  Sum = InsertBinop(Instruction::Sub, Sum, W, /*IsSafeToHoist*/ true);
741  ++I;
742  } else {
743  // A simple add.
744  Value *W = expandCodeFor(Op, Ty);
745  Sum = InsertNoopCastOfTo(Sum, Ty);
746  // Canonicalize a constant to the RHS.
747  if (isa<Constant>(Sum)) std::swap(Sum, W);
748  Sum = InsertBinop(Instruction::Add, Sum, W, /*IsSafeToHoist*/ true);
749  ++I;
750  }
751  }
752 
753  return Sum;
754 }
755 
756 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
757  Type *Ty = SE.getEffectiveSCEVType(S->getType());
758 
759  // Collect all the mul operands in a loop, along with their associated loops.
760  // Iterate in reverse so that constants are emitted last, all else equal.
762  for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
763  E(S->op_begin()); I != E; ++I)
764  OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
765 
766  // Sort by loop. Use a stable sort so that constants follow non-constants.
767  llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
768 
769  // Emit instructions to mul all the operands. Hoist as much as possible
770  // out of loops.
771  Value *Prod = nullptr;
772  auto I = OpsAndLoops.begin();
773 
774  // Expand the calculation of X pow N in the following manner:
775  // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
776  // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
777  const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
778  auto E = I;
779  // Calculate how many times the same operand from the same loop is included
780  // into this power.
781  uint64_t Exponent = 0;
782  const uint64_t MaxExponent = UINT64_MAX >> 1;
783  // No one sane will ever try to calculate such huge exponents, but if we
784  // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
785  // below when the power of 2 exceeds our Exponent, and we want it to be
786  // 1u << 31 at most to not deal with unsigned overflow.
787  while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
788  ++Exponent;
789  ++E;
790  }
791  assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
792 
793  // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
794  // that are needed into the result.
795  Value *P = expandCodeFor(I->second, Ty);
796  Value *Result = nullptr;
797  if (Exponent & 1)
798  Result = P;
799  for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
800  P = InsertBinop(Instruction::Mul, P, P, /*IsSafeToHoist*/ true);
801  if (Exponent & BinExp)
802  Result = Result ? InsertBinop(Instruction::Mul, Result, P,
803  /*IsSafeToHoist*/ true)
804  : P;
805  }
806 
807  I = E;
808  assert(Result && "Nothing was expanded?");
809  return Result;
810  };
811 
812  while (I != OpsAndLoops.end()) {
813  if (!Prod) {
814  // This is the first operand. Just expand it.
815  Prod = ExpandOpBinPowN();
816  } else if (I->second->isAllOnesValue()) {
817  // Instead of doing a multiply by negative one, just do a negate.
818  Prod = InsertNoopCastOfTo(Prod, Ty);
819  Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
820  /*IsSafeToHoist*/ true);
821  ++I;
822  } else {
823  // A simple mul.
824  Value *W = ExpandOpBinPowN();
825  Prod = InsertNoopCastOfTo(Prod, Ty);
826  // Canonicalize a constant to the RHS.
827  if (isa<Constant>(Prod)) std::swap(Prod, W);
828  const APInt *RHS;
829  if (match(W, m_Power2(RHS))) {
830  // Canonicalize Prod*(1<<C) to Prod<<C.
831  assert(!Ty->isVectorTy() && "vector types are not SCEVable");
832  Prod = InsertBinop(Instruction::Shl, Prod,
833  ConstantInt::get(Ty, RHS->logBase2()),
834  /*IsSafeToHoist*/ true);
835  } else {
836  Prod = InsertBinop(Instruction::Mul, Prod, W, /*IsSafeToHoist*/ true);
837  }
838  }
839  }
840 
841  return Prod;
842 }
843 
844 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
845  Type *Ty = SE.getEffectiveSCEVType(S->getType());
846 
847  Value *LHS = expandCodeFor(S->getLHS(), Ty);
848  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
849  const APInt &RHS = SC->getAPInt();
850  if (RHS.isPowerOf2())
851  return InsertBinop(Instruction::LShr, LHS,
852  ConstantInt::get(Ty, RHS.logBase2()),
853  /*IsSafeToHoist*/ true);
854  }
855 
856  Value *RHS = expandCodeFor(S->getRHS(), Ty);
857  return InsertBinop(Instruction::UDiv, LHS, RHS,
858  /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
859 }
860 
861 /// Move parts of Base into Rest to leave Base with the minimal
862 /// expression that provides a pointer operand suitable for a
863 /// GEP expansion.
864 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
865  ScalarEvolution &SE) {
866  while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
867  Base = A->getStart();
868  Rest = SE.getAddExpr(Rest,
869  SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
870  A->getStepRecurrence(SE),
871  A->getLoop(),
872  A->getNoWrapFlags(SCEV::FlagNW)));
873  }
874  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
875  Base = A->getOperand(A->getNumOperands()-1);
876  SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
877  NewAddOps.back() = Rest;
878  Rest = SE.getAddExpr(NewAddOps);
879  ExposePointerBase(Base, Rest, SE);
880  }
881 }
882 
883 /// Determine if this is a well-behaved chain of instructions leading back to
884 /// the PHI. If so, it may be reused by expanded expressions.
885 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
886  const Loop *L) {
887  if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
888  (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
889  return false;
890  // If any of the operands don't dominate the insert position, bail.
891  // Addrec operands are always loop-invariant, so this can only happen
892  // if there are instructions which haven't been hoisted.
893  if (L == IVIncInsertLoop) {
894  for (User::op_iterator OI = IncV->op_begin()+1,
895  OE = IncV->op_end(); OI != OE; ++OI)
896  if (Instruction *OInst = dyn_cast<Instruction>(OI))
897  if (!SE.DT.dominates(OInst, IVIncInsertPos))
898  return false;
899  }
900  // Advance to the next instruction.
901  IncV = dyn_cast<Instruction>(IncV->getOperand(0));
902  if (!IncV)
903  return false;
904 
905  if (IncV->mayHaveSideEffects())
906  return false;
907 
908  if (IncV == PN)
909  return true;
910 
911  return isNormalAddRecExprPHI(PN, IncV, L);
912 }
913 
914 /// getIVIncOperand returns an induction variable increment's induction
915 /// variable operand.
916 ///
917 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
918 /// operands dominate InsertPos.
919 ///
920 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
921 /// simple patterns generated by getAddRecExprPHILiterally and
922 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
924  Instruction *InsertPos,
925  bool allowScale) {
926  if (IncV == InsertPos)
927  return nullptr;
928 
929  switch (IncV->getOpcode()) {
930  default:
931  return nullptr;
932  // Check for a simple Add/Sub or GEP of a loop invariant step.
933  case Instruction::Add:
934  case Instruction::Sub: {
935  Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
936  if (!OInst || SE.DT.dominates(OInst, InsertPos))
937  return dyn_cast<Instruction>(IncV->getOperand(0));
938  return nullptr;
939  }
940  case Instruction::BitCast:
941  return dyn_cast<Instruction>(IncV->getOperand(0));
942  case Instruction::GetElementPtr:
943  for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
944  if (isa<Constant>(*I))
945  continue;
946  if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
947  if (!SE.DT.dominates(OInst, InsertPos))
948  return nullptr;
949  }
950  if (allowScale) {
951  // allow any kind of GEP as long as it can be hoisted.
952  continue;
953  }
954  // This must be a pointer addition of constants (pretty), which is already
955  // handled, or some number of address-size elements (ugly). Ugly geps
956  // have 2 operands. i1* is used by the expander to represent an
957  // address-size element.
958  if (IncV->getNumOperands() != 2)
959  return nullptr;
960  unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
961  if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
962  && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
963  return nullptr;
964  break;
965  }
966  return dyn_cast<Instruction>(IncV->getOperand(0));
967  }
968 }
969 
970 /// If the insert point of the current builder or any of the builders on the
971 /// stack of saved builders has 'I' as its insert point, update it to point to
972 /// the instruction after 'I'. This is intended to be used when the instruction
973 /// 'I' is being moved. If this fixup is not done and 'I' is moved to a
974 /// different block, the inconsistent insert point (with a mismatched
975 /// Instruction and Block) can lead to an instruction being inserted in a block
976 /// other than its parent.
977 void SCEVExpander::fixupInsertPoints(Instruction *I) {
978  BasicBlock::iterator It(*I);
979  BasicBlock::iterator NewInsertPt = std::next(It);
980  if (Builder.GetInsertPoint() == It)
981  Builder.SetInsertPoint(&*NewInsertPt);
982  for (auto *InsertPtGuard : InsertPointGuards)
983  if (InsertPtGuard->GetInsertPoint() == It)
984  InsertPtGuard->SetInsertPoint(NewInsertPt);
985 }
986 
987 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
988 /// it available to other uses in this loop. Recursively hoist any operands,
989 /// until we reach a value that dominates InsertPos.
991  if (SE.DT.dominates(IncV, InsertPos))
992  return true;
993 
994  // InsertPos must itself dominate IncV so that IncV's new position satisfies
995  // its existing users.
996  if (isa<PHINode>(InsertPos) ||
997  !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
998  return false;
999 
1000  if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
1001  return false;
1002 
1003  // Check that the chain of IV operands leading back to Phi can be hoisted.
1005  for(;;) {
1006  Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
1007  if (!Oper)
1008  return false;
1009  // IncV is safe to hoist.
1010  IVIncs.push_back(IncV);
1011  IncV = Oper;
1012  if (SE.DT.dominates(IncV, InsertPos))
1013  break;
1014  }
1015  for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
1016  fixupInsertPoints(*I);
1017  (*I)->moveBefore(InsertPos);
1018  }
1019  return true;
1020 }
1021 
1022 /// Determine if this cyclic phi is in a form that would have been generated by
1023 /// LSR. We don't care if the phi was actually expanded in this pass, as long
1024 /// as it is in a low-cost form, for example, no implied multiplication. This
1025 /// should match any patterns generated by getAddRecExprPHILiterally and
1026 /// expandAddtoGEP.
1027 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
1028  const Loop *L) {
1029  for(Instruction *IVOper = IncV;
1030  (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
1031  /*allowScale=*/false));) {
1032  if (IVOper == PN)
1033  return true;
1034  }
1035  return false;
1036 }
1037 
1038 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
1039 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
1040 /// need to materialize IV increments elsewhere to handle difficult situations.
1041 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
1042  Type *ExpandTy, Type *IntTy,
1043  bool useSubtract) {
1044  Value *IncV;
1045  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1046  if (ExpandTy->isPointerTy()) {
1047  PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1048  // If the step isn't constant, don't use an implicitly scaled GEP, because
1049  // that would require a multiply inside the loop.
1050  if (!isa<ConstantInt>(StepV))
1051  GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1052  GEPPtrTy->getAddressSpace());
1053  IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
1054  if (IncV->getType() != PN->getType()) {
1055  IncV = Builder.CreateBitCast(IncV, PN->getType());
1056  rememberInstruction(IncV);
1057  }
1058  } else {
1059  IncV = useSubtract ?
1060  Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1061  Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1062  rememberInstruction(IncV);
1063  }
1064  return IncV;
1065 }
1066 
1067 /// Hoist the addrec instruction chain rooted in the loop phi above the
1068 /// position. This routine assumes that this is possible (has been checked).
1069 void SCEVExpander::hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1070  Instruction *Pos, PHINode *LoopPhi) {
1071  do {
1072  if (DT->dominates(InstToHoist, Pos))
1073  break;
1074  // Make sure the increment is where we want it. But don't move it
1075  // down past a potential existing post-inc user.
1076  fixupInsertPoints(InstToHoist);
1077  InstToHoist->moveBefore(Pos);
1078  Pos = InstToHoist;
1079  InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1080  } while (InstToHoist != LoopPhi);
1081 }
1082 
1083 /// Check whether we can cheaply express the requested SCEV in terms of
1084 /// the available PHI SCEV by truncation and/or inversion of the step.
1086  const SCEVAddRecExpr *Phi,
1087  const SCEVAddRecExpr *Requested,
1088  bool &InvertStep) {
1089  Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1090  Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1091 
1092  if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1093  return false;
1094 
1095  // Try truncate it if necessary.
1096  Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1097  if (!Phi)
1098  return false;
1099 
1100  // Check whether truncation will help.
1101  if (Phi == Requested) {
1102  InvertStep = false;
1103  return true;
1104  }
1105 
1106  // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1107  if (SE.getAddExpr(Requested->getStart(),
1108  SE.getNegativeSCEV(Requested)) == Phi) {
1109  InvertStep = true;
1110  return true;
1111  }
1112 
1113  return false;
1114 }
1115 
1116 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1117  if (!isa<IntegerType>(AR->getType()))
1118  return false;
1119 
1120  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1121  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1122  const SCEV *Step = AR->getStepRecurrence(SE);
1123  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1124  SE.getSignExtendExpr(AR, WideTy));
1125  const SCEV *ExtendAfterOp =
1126  SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1127  return ExtendAfterOp == OpAfterExtend;
1128 }
1129 
1130 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1131  if (!isa<IntegerType>(AR->getType()))
1132  return false;
1133 
1134  unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1135  Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1136  const SCEV *Step = AR->getStepRecurrence(SE);
1137  const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1138  SE.getZeroExtendExpr(AR, WideTy));
1139  const SCEV *ExtendAfterOp =
1140  SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1141  return ExtendAfterOp == OpAfterExtend;
1142 }
1143 
1144 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1145 /// the base addrec, which is the addrec without any non-loop-dominating
1146 /// values, and return the PHI.
1147 PHINode *
1148 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1149  const Loop *L,
1150  Type *ExpandTy,
1151  Type *IntTy,
1152  Type *&TruncTy,
1153  bool &InvertStep) {
1154  assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1155 
1156  // Reuse a previously-inserted PHI, if present.
1157  BasicBlock *LatchBlock = L->getLoopLatch();
1158  if (LatchBlock) {
1159  PHINode *AddRecPhiMatch = nullptr;
1160  Instruction *IncV = nullptr;
1161  TruncTy = nullptr;
1162  InvertStep = false;
1163 
1164  // Only try partially matching scevs that need truncation and/or
1165  // step-inversion if we know this loop is outside the current loop.
1166  bool TryNonMatchingSCEV =
1167  IVIncInsertLoop &&
1168  SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1169 
1170  for (PHINode &PN : L->getHeader()->phis()) {
1171  if (!SE.isSCEVable(PN.getType()))
1172  continue;
1173 
1174  const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1175  if (!PhiSCEV)
1176  continue;
1177 
1178  bool IsMatchingSCEV = PhiSCEV == Normalized;
1179  // We only handle truncation and inversion of phi recurrences for the
1180  // expanded expression if the expanded expression's loop dominates the
1181  // loop we insert to. Check now, so we can bail out early.
1182  if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1183  continue;
1184 
1185  // TODO: this possibly can be reworked to avoid this cast at all.
1186  Instruction *TempIncV =
1188  if (!TempIncV)
1189  continue;
1190 
1191  // Check whether we can reuse this PHI node.
1192  if (LSRMode) {
1193  if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1194  continue;
1195  if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1196  continue;
1197  } else {
1198  if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1199  continue;
1200  }
1201 
1202  // Stop if we have found an exact match SCEV.
1203  if (IsMatchingSCEV) {
1204  IncV = TempIncV;
1205  TruncTy = nullptr;
1206  InvertStep = false;
1207  AddRecPhiMatch = &PN;
1208  break;
1209  }
1210 
1211  // Try whether the phi can be translated into the requested form
1212  // (truncated and/or offset by a constant).
1213  if ((!TruncTy || InvertStep) &&
1214  canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1215  // Record the phi node. But don't stop we might find an exact match
1216  // later.
1217  AddRecPhiMatch = &PN;
1218  IncV = TempIncV;
1219  TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1220  }
1221  }
1222 
1223  if (AddRecPhiMatch) {
1224  // Potentially, move the increment. We have made sure in
1225  // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1226  if (L == IVIncInsertLoop)
1227  hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1228 
1229  // Ok, the add recurrence looks usable.
1230  // Remember this PHI, even in post-inc mode.
1231  InsertedValues.insert(AddRecPhiMatch);
1232  // Remember the increment.
1233  rememberInstruction(IncV);
1234  return AddRecPhiMatch;
1235  }
1236  }
1237 
1238  // Save the original insertion point so we can restore it when we're done.
1239  SCEVInsertPointGuard Guard(Builder, this);
1240 
1241  // Another AddRec may need to be recursively expanded below. For example, if
1242  // this AddRec is quadratic, the StepV may itself be an AddRec in this
1243  // loop. Remove this loop from the PostIncLoops set before expanding such
1244  // AddRecs. Otherwise, we cannot find a valid position for the step
1245  // (i.e. StepV can never dominate its loop header). Ideally, we could do
1246  // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1247  // so it's not worth implementing SmallPtrSet::swap.
1248  PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1249  PostIncLoops.clear();
1250 
1251  // Expand code for the start value into the loop preheader.
1252  assert(L->getLoopPreheader() &&
1253  "Can't expand add recurrences without a loop preheader!");
1254  Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1256 
1257  // StartV must have been be inserted into L's preheader to dominate the new
1258  // phi.
1259  assert(!isa<Instruction>(StartV) ||
1260  SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1261  L->getHeader()));
1262 
1263  // Expand code for the step value. Do this before creating the PHI so that PHI
1264  // reuse code doesn't see an incomplete PHI.
1265  const SCEV *Step = Normalized->getStepRecurrence(SE);
1266  // If the stride is negative, insert a sub instead of an add for the increment
1267  // (unless it's a constant, because subtracts of constants are canonicalized
1268  // to adds).
1269  bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1270  if (useSubtract)
1271  Step = SE.getNegativeSCEV(Step);
1272  // Expand the step somewhere that dominates the loop header.
1273  Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1274 
1275  // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1276  // we actually do emit an addition. It does not apply if we emit a
1277  // subtraction.
1278  bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1279  bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1280 
1281  // Create the PHI.
1282  BasicBlock *Header = L->getHeader();
1283  Builder.SetInsertPoint(Header, Header->begin());
1284  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1285  PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1286  Twine(IVName) + ".iv");
1287  rememberInstruction(PN);
1288 
1289  // Create the step instructions and populate the PHI.
1290  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1291  BasicBlock *Pred = *HPI;
1292 
1293  // Add a start value.
1294  if (!L->contains(Pred)) {
1295  PN->addIncoming(StartV, Pred);
1296  continue;
1297  }
1298 
1299  // Create a step value and add it to the PHI.
1300  // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1301  // instructions at IVIncInsertPos.
1302  Instruction *InsertPos = L == IVIncInsertLoop ?
1303  IVIncInsertPos : Pred->getTerminator();
1304  Builder.SetInsertPoint(InsertPos);
1305  Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1306 
1307  if (isa<OverflowingBinaryOperator>(IncV)) {
1308  if (IncrementIsNUW)
1309  cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1310  if (IncrementIsNSW)
1311  cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1312  }
1313  PN->addIncoming(IncV, Pred);
1314  }
1315 
1316  // After expanding subexpressions, restore the PostIncLoops set so the caller
1317  // can ensure that IVIncrement dominates the current uses.
1318  PostIncLoops = SavedPostIncLoops;
1319 
1320  // Remember this PHI, even in post-inc mode.
1321  InsertedValues.insert(PN);
1322 
1323  return PN;
1324 }
1325 
1326 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1327  Type *STy = S->getType();
1328  Type *IntTy = SE.getEffectiveSCEVType(STy);
1329  const Loop *L = S->getLoop();
1330 
1331  // Determine a normalized form of this expression, which is the expression
1332  // before any post-inc adjustment is made.
1333  const SCEVAddRecExpr *Normalized = S;
1334  if (PostIncLoops.count(L)) {
1336  Loops.insert(L);
1337  Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
1338  }
1339 
1340  // Strip off any non-loop-dominating component from the addrec start.
1341  const SCEV *Start = Normalized->getStart();
1342  const SCEV *PostLoopOffset = nullptr;
1343  if (!SE.properlyDominates(Start, L->getHeader())) {
1344  PostLoopOffset = Start;
1345  Start = SE.getConstant(Normalized->getType(), 0);
1346  Normalized = cast<SCEVAddRecExpr>(
1347  SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1348  Normalized->getLoop(),
1349  Normalized->getNoWrapFlags(SCEV::FlagNW)));
1350  }
1351 
1352  // Strip off any non-loop-dominating component from the addrec step.
1353  const SCEV *Step = Normalized->getStepRecurrence(SE);
1354  const SCEV *PostLoopScale = nullptr;
1355  if (!SE.dominates(Step, L->getHeader())) {
1356  PostLoopScale = Step;
1357  Step = SE.getConstant(Normalized->getType(), 1);
1358  if (!Start->isZero()) {
1359  // The normalization below assumes that Start is constant zero, so if
1360  // it isn't re-associate Start to PostLoopOffset.
1361  assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1362  PostLoopOffset = Start;
1363  Start = SE.getConstant(Normalized->getType(), 0);
1364  }
1365  Normalized =
1366  cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1367  Start, Step, Normalized->getLoop(),
1368  Normalized->getNoWrapFlags(SCEV::FlagNW)));
1369  }
1370 
1371  // Expand the core addrec. If we need post-loop scaling, force it to
1372  // expand to an integer type to avoid the need for additional casting.
1373  Type *ExpandTy = PostLoopScale ? IntTy : STy;
1374  // We can't use a pointer type for the addrec if the pointer type is
1375  // non-integral.
1376  Type *AddRecPHIExpandTy =
1377  DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
1378 
1379  // In some cases, we decide to reuse an existing phi node but need to truncate
1380  // it and/or invert the step.
1381  Type *TruncTy = nullptr;
1382  bool InvertStep = false;
1383  PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
1384  IntTy, TruncTy, InvertStep);
1385 
1386  // Accommodate post-inc mode, if necessary.
1387  Value *Result;
1388  if (!PostIncLoops.count(L))
1389  Result = PN;
1390  else {
1391  // In PostInc mode, use the post-incremented value.
1392  BasicBlock *LatchBlock = L->getLoopLatch();
1393  assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1394  Result = PN->getIncomingValueForBlock(LatchBlock);
1395 
1396  // For an expansion to use the postinc form, the client must call
1397  // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1398  // or dominated by IVIncInsertPos.
1399  if (isa<Instruction>(Result) &&
1400  !SE.DT.dominates(cast<Instruction>(Result),
1401  &*Builder.GetInsertPoint())) {
1402  // The induction variable's postinc expansion does not dominate this use.
1403  // IVUsers tries to prevent this case, so it is rare. However, it can
1404  // happen when an IVUser outside the loop is not dominated by the latch
1405  // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1406  // all cases. Consider a phi outside whose operand is replaced during
1407  // expansion with the value of the postinc user. Without fundamentally
1408  // changing the way postinc users are tracked, the only remedy is
1409  // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1410  // but hopefully expandCodeFor handles that.
1411  bool useSubtract =
1412  !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1413  if (useSubtract)
1414  Step = SE.getNegativeSCEV(Step);
1415  Value *StepV;
1416  {
1417  // Expand the step somewhere that dominates the loop header.
1418  SCEVInsertPointGuard Guard(Builder, this);
1419  StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1420  }
1421  Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1422  }
1423  }
1424 
1425  // We have decided to reuse an induction variable of a dominating loop. Apply
1426  // truncation and/or inversion of the step.
1427  if (TruncTy) {
1428  Type *ResTy = Result->getType();
1429  // Normalize the result type.
1430  if (ResTy != SE.getEffectiveSCEVType(ResTy))
1431  Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1432  // Truncate the result.
1433  if (TruncTy != Result->getType()) {
1434  Result = Builder.CreateTrunc(Result, TruncTy);
1435  rememberInstruction(Result);
1436  }
1437  // Invert the result.
1438  if (InvertStep) {
1439  Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1440  Result);
1441  rememberInstruction(Result);
1442  }
1443  }
1444 
1445  // Re-apply any non-loop-dominating scale.
1446  if (PostLoopScale) {
1447  assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1448  Result = InsertNoopCastOfTo(Result, IntTy);
1449  Result = Builder.CreateMul(Result,
1450  expandCodeFor(PostLoopScale, IntTy));
1451  rememberInstruction(Result);
1452  }
1453 
1454  // Re-apply any non-loop-dominating offset.
1455  if (PostLoopOffset) {
1456  if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1457  if (Result->getType()->isIntegerTy()) {
1458  Value *Base = expandCodeFor(PostLoopOffset, ExpandTy);
1459  Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
1460  } else {
1461  Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
1462  }
1463  } else {
1464  Result = InsertNoopCastOfTo(Result, IntTy);
1465  Result = Builder.CreateAdd(Result,
1466  expandCodeFor(PostLoopOffset, IntTy));
1467  rememberInstruction(Result);
1468  }
1469  }
1470 
1471  return Result;
1472 }
1473 
1474 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1475  if (!CanonicalMode) return expandAddRecExprLiterally(S);
1476 
1477  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1478  const Loop *L = S->getLoop();
1479 
1480  // First check for an existing canonical IV in a suitable type.
1481  PHINode *CanonicalIV = nullptr;
1482  if (PHINode *PN = L->getCanonicalInductionVariable())
1483  if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1484  CanonicalIV = PN;
1485 
1486  // Rewrite an AddRec in terms of the canonical induction variable, if
1487  // its type is more narrow.
1488  if (CanonicalIV &&
1489  SE.getTypeSizeInBits(CanonicalIV->getType()) >
1490  SE.getTypeSizeInBits(Ty)) {
1492  for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1493  NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1494  Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1496  BasicBlock::iterator NewInsertPt =
1497  findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1498  V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1499  &*NewInsertPt);
1500  return V;
1501  }
1502 
1503  // {X,+,F} --> X + {0,+,F}
1504  if (!S->getStart()->isZero()) {
1505  SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1506  NewOps[0] = SE.getConstant(Ty, 0);
1507  const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1509 
1510  // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1511  // comments on expandAddToGEP for details.
1512  const SCEV *Base = S->getStart();
1513  // Dig into the expression to find the pointer base for a GEP.
1514  const SCEV *ExposedRest = Rest;
1515  ExposePointerBase(Base, ExposedRest, SE);
1516  // If we found a pointer, expand the AddRec with a GEP.
1517  if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1518  // Make sure the Base isn't something exotic, such as a multiplied
1519  // or divided pointer value. In those cases, the result type isn't
1520  // actually a pointer type.
1521  if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1522  Value *StartV = expand(Base);
1523  assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1524  return expandAddToGEP(ExposedRest, PTy, Ty, StartV);
1525  }
1526  }
1527 
1528  // Just do a normal add. Pre-expand the operands to suppress folding.
1529  //
1530  // The LHS and RHS values are factored out of the expand call to make the
1531  // output independent of the argument evaluation order.
1532  const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1533  const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1534  return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1535  }
1536 
1537  // If we don't yet have a canonical IV, create one.
1538  if (!CanonicalIV) {
1539  // Create and insert the PHI node for the induction variable in the
1540  // specified loop.
1541  BasicBlock *Header = L->getHeader();
1542  pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1543  CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1544  &Header->front());
1545  rememberInstruction(CanonicalIV);
1546 
1547  SmallSet<BasicBlock *, 4> PredSeen;
1548  Constant *One = ConstantInt::get(Ty, 1);
1549  for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1550  BasicBlock *HP = *HPI;
1551  if (!PredSeen.insert(HP).second) {
1552  // There must be an incoming value for each predecessor, even the
1553  // duplicates!
1554  CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1555  continue;
1556  }
1557 
1558  if (L->contains(HP)) {
1559  // Insert a unit add instruction right before the terminator
1560  // corresponding to the back-edge.
1561  Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1562  "indvar.next",
1563  HP->getTerminator());
1564  Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1565  rememberInstruction(Add);
1566  CanonicalIV->addIncoming(Add, HP);
1567  } else {
1568  CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1569  }
1570  }
1571  }
1572 
1573  // {0,+,1} --> Insert a canonical induction variable into the loop!
1574  if (S->isAffine() && S->getOperand(1)->isOne()) {
1575  assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1576  "IVs with types different from the canonical IV should "
1577  "already have been handled!");
1578  return CanonicalIV;
1579  }
1580 
1581  // {0,+,F} --> {0,+,1} * F
1582 
1583  // If this is a simple linear addrec, emit it now as a special case.
1584  if (S->isAffine()) // {0,+,F} --> i*F
1585  return
1586  expand(SE.getTruncateOrNoop(
1587  SE.getMulExpr(SE.getUnknown(CanonicalIV),
1588  SE.getNoopOrAnyExtend(S->getOperand(1),
1589  CanonicalIV->getType())),
1590  Ty));
1591 
1592  // If this is a chain of recurrences, turn it into a closed form, using the
1593  // folders, then expandCodeFor the closed form. This allows the folders to
1594  // simplify the expression without having to build a bunch of special code
1595  // into this folder.
1596  const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1597 
1598  // Promote S up to the canonical IV type, if the cast is foldable.
1599  const SCEV *NewS = S;
1600  const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1601  if (isa<SCEVAddRecExpr>(Ext))
1602  NewS = Ext;
1603 
1604  const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1605  //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1606 
1607  // Truncate the result down to the original type, if needed.
1608  const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1609  return expand(T);
1610 }
1611 
1612 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1613  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1614  Value *V = expandCodeFor(S->getOperand(),
1615  SE.getEffectiveSCEVType(S->getOperand()->getType()));
1616  Value *I = Builder.CreateTrunc(V, Ty);
1617  rememberInstruction(I);
1618  return I;
1619 }
1620 
1621 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1622  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1623  Value *V = expandCodeFor(S->getOperand(),
1624  SE.getEffectiveSCEVType(S->getOperand()->getType()));
1625  Value *I = Builder.CreateZExt(V, Ty);
1626  rememberInstruction(I);
1627  return I;
1628 }
1629 
1630 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1631  Type *Ty = SE.getEffectiveSCEVType(S->getType());
1632  Value *V = expandCodeFor(S->getOperand(),
1633  SE.getEffectiveSCEVType(S->getOperand()->getType()));
1634  Value *I = Builder.CreateSExt(V, Ty);
1635  rememberInstruction(I);
1636  return I;
1637 }
1638 
1639 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1640  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1641  Type *Ty = LHS->getType();
1642  for (int i = S->getNumOperands()-2; i >= 0; --i) {
1643  // In the case of mixed integer and pointer types, do the
1644  // rest of the comparisons as integer.
1645  Type *OpTy = S->getOperand(i)->getType();
1646  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1647  Ty = SE.getEffectiveSCEVType(Ty);
1648  LHS = InsertNoopCastOfTo(LHS, Ty);
1649  }
1650  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1651  Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1652  rememberInstruction(ICmp);
1653  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1654  rememberInstruction(Sel);
1655  LHS = Sel;
1656  }
1657  // In the case of mixed integer and pointer types, cast the
1658  // final result back to the pointer type.
1659  if (LHS->getType() != S->getType())
1660  LHS = InsertNoopCastOfTo(LHS, S->getType());
1661  return LHS;
1662 }
1663 
1664 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1665  Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1666  Type *Ty = LHS->getType();
1667  for (int i = S->getNumOperands()-2; i >= 0; --i) {
1668  // In the case of mixed integer and pointer types, do the
1669  // rest of the comparisons as integer.
1670  Type *OpTy = S->getOperand(i)->getType();
1671  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1672  Ty = SE.getEffectiveSCEVType(Ty);
1673  LHS = InsertNoopCastOfTo(LHS, Ty);
1674  }
1675  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1676  Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1677  rememberInstruction(ICmp);
1678  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1679  rememberInstruction(Sel);
1680  LHS = Sel;
1681  }
1682  // In the case of mixed integer and pointer types, cast the
1683  // final result back to the pointer type.
1684  if (LHS->getType() != S->getType())
1685  LHS = InsertNoopCastOfTo(LHS, S->getType());
1686  return LHS;
1687 }
1688 
1689 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
1690  Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1691  Type *Ty = LHS->getType();
1692  for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1693  // In the case of mixed integer and pointer types, do the
1694  // rest of the comparisons as integer.
1695  Type *OpTy = S->getOperand(i)->getType();
1696  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1697  Ty = SE.getEffectiveSCEVType(Ty);
1698  LHS = InsertNoopCastOfTo(LHS, Ty);
1699  }
1700  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1701  Value *ICmp = Builder.CreateICmpSLT(LHS, RHS);
1702  rememberInstruction(ICmp);
1703  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smin");
1704  rememberInstruction(Sel);
1705  LHS = Sel;
1706  }
1707  // In the case of mixed integer and pointer types, cast the
1708  // final result back to the pointer type.
1709  if (LHS->getType() != S->getType())
1710  LHS = InsertNoopCastOfTo(LHS, S->getType());
1711  return LHS;
1712 }
1713 
1714 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
1715  Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1716  Type *Ty = LHS->getType();
1717  for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1718  // In the case of mixed integer and pointer types, do the
1719  // rest of the comparisons as integer.
1720  Type *OpTy = S->getOperand(i)->getType();
1721  if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
1722  Ty = SE.getEffectiveSCEVType(Ty);
1723  LHS = InsertNoopCastOfTo(LHS, Ty);
1724  }
1725  Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1726  Value *ICmp = Builder.CreateICmpULT(LHS, RHS);
1727  rememberInstruction(ICmp);
1728  Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umin");
1729  rememberInstruction(Sel);
1730  LHS = Sel;
1731  }
1732  // In the case of mixed integer and pointer types, cast the
1733  // final result back to the pointer type.
1734  if (LHS->getType() != S->getType())
1735  LHS = InsertNoopCastOfTo(LHS, S->getType());
1736  return LHS;
1737 }
1738 
1740  Instruction *IP) {
1741  setInsertPoint(IP);
1742  return expandCodeFor(SH, Ty);
1743 }
1744 
1746  // Expand the code for this SCEV.
1747  Value *V = expand(SH);
1748  if (Ty) {
1749  assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1750  "non-trivial casts should be done with the SCEVs directly!");
1751  V = InsertNoopCastOfTo(V, Ty);
1752  }
1753  return V;
1754 }
1755 
1756 ScalarEvolution::ValueOffsetPair
1757 SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1758  const Instruction *InsertPt) {
1759  SetVector<ScalarEvolution::ValueOffsetPair> *Set = SE.getSCEVValues(S);
1760  // If the expansion is not in CanonicalMode, and the SCEV contains any
1761  // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1762  if (CanonicalMode || !SE.containsAddRecurrence(S)) {
1763  // If S is scConstant, it may be worse to reuse an existing Value.
1764  if (S->getSCEVType() != scConstant && Set) {
1765  // Choose a Value from the set which dominates the insertPt.
1766  // insertPt should be inside the Value's parent loop so as not to break
1767  // the LCSSA form.
1768  for (auto const &VOPair : *Set) {
1769  Value *V = VOPair.first;
1770  ConstantInt *Offset = VOPair.second;
1771  Instruction *EntInst = nullptr;
1772  if (V && isa<Instruction>(V) && (EntInst = cast<Instruction>(V)) &&
1773  S->getType() == V->getType() &&
1774  EntInst->getFunction() == InsertPt->getFunction() &&
1775  SE.DT.dominates(EntInst, InsertPt) &&
1776  (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1777  SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1778  return {V, Offset};
1779  }
1780  }
1781  }
1782  return {nullptr, nullptr};
1783 }
1784 
1785 // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1786 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1787 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1788 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1789 // the expansion will try to reuse Value from ExprValueMap, and only when it
1790 // fails, expand the SCEV literally.
1791 Value *SCEVExpander::expand(const SCEV *S) {
1792  // Compute an insertion point for this SCEV object. Hoist the instructions
1793  // as far out in the loop nest as possible.
1794  Instruction *InsertPt = &*Builder.GetInsertPoint();
1795 
1796  // We can move insertion point only if there is no div or rem operations
1797  // otherwise we are risky to move it over the check for zero denominator.
1798  auto SafeToHoist = [](const SCEV *S) {
1799  return !SCEVExprContains(S, [](const SCEV *S) {
1800  if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1801  if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1802  // Division by non-zero constants can be hoisted.
1803  return SC->getValue()->isZero();
1804  // All other divisions should not be moved as they may be
1805  // divisions by zero and should be kept within the
1806  // conditions of the surrounding loops that guard their
1807  // execution (see PR35406).
1808  return true;
1809  }
1810  return false;
1811  });
1812  };
1813  if (SafeToHoist(S)) {
1814  for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1815  L = L->getParentLoop()) {
1816  if (SE.isLoopInvariant(S, L)) {
1817  if (!L) break;
1818  if (BasicBlock *Preheader = L->getLoopPreheader())
1819  InsertPt = Preheader->getTerminator();
1820  else
1821  // LSR sets the insertion point for AddRec start/step values to the
1822  // block start to simplify value reuse, even though it's an invalid
1823  // position. SCEVExpander must correct for this in all cases.
1824  InsertPt = &*L->getHeader()->getFirstInsertionPt();
1825  } else {
1826  // If the SCEV is computable at this level, insert it into the header
1827  // after the PHIs (and after any other instructions that we've inserted
1828  // there) so that it is guaranteed to dominate any user inside the loop.
1829  if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1830  InsertPt = &*L->getHeader()->getFirstInsertionPt();
1831  while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1832  (isInsertedInstruction(InsertPt) ||
1833  isa<DbgInfoIntrinsic>(InsertPt)))
1834  InsertPt = &*std::next(InsertPt->getIterator());
1835  break;
1836  }
1837  }
1838  }
1839 
1840  // IndVarSimplify sometimes sets the insertion point at the block start, even
1841  // when there are PHIs at that point. We must correct for this.
1842  if (isa<PHINode>(*InsertPt))
1843  InsertPt = &*InsertPt->getParent()->getFirstInsertionPt();
1844 
1845  // Check to see if we already expanded this here.
1846  auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1847  if (I != InsertedExpressions.end())
1848  return I->second;
1849 
1850  SCEVInsertPointGuard Guard(Builder, this);
1851  Builder.SetInsertPoint(InsertPt);
1852 
1853  // Expand the expression into instructions.
1854  ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
1855  Value *V = VO.first;
1856 
1857  if (!V)
1858  V = visit(S);
1859  else if (VO.second) {
1860  if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) {
1861  Type *Ety = Vty->getPointerElementType();
1862  int64_t Offset = VO.second->getSExtValue();
1863  int64_t ESize = SE.getTypeSizeInBits(Ety);
1864  if ((Offset * 8) % ESize == 0) {
1865  ConstantInt *Idx =
1866  ConstantInt::getSigned(VO.second->getType(), -(Offset * 8) / ESize);
1867  V = Builder.CreateGEP(Ety, V, Idx, "scevgep");
1868  } else {
1869  ConstantInt *Idx =
1870  ConstantInt::getSigned(VO.second->getType(), -Offset);
1871  unsigned AS = Vty->getAddressSpace();
1872  V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS));
1873  V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx,
1874  "uglygep");
1875  V = Builder.CreateBitCast(V, Vty);
1876  }
1877  } else {
1878  V = Builder.CreateSub(V, VO.second);
1879  }
1880  }
1881  // Remember the expanded value for this SCEV at this location.
1882  //
1883  // This is independent of PostIncLoops. The mapped value simply materializes
1884  // the expression at this insertion point. If the mapped value happened to be
1885  // a postinc expansion, it could be reused by a non-postinc user, but only if
1886  // its insertion point was already at the head of the loop.
1887  InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1888  return V;
1889 }
1890 
1891 void SCEVExpander::rememberInstruction(Value *I) {
1892  if (!PostIncLoops.empty())
1893  InsertedPostIncValues.insert(I);
1894  else
1895  InsertedValues.insert(I);
1896 }
1897 
1898 /// getOrInsertCanonicalInductionVariable - This method returns the
1899 /// canonical induction variable of the specified type for the specified
1900 /// loop (inserting one if there is none). A canonical induction variable
1901 /// starts at zero and steps by one on each iteration.
1902 PHINode *
1904  Type *Ty) {
1905  assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1906 
1907  // Build a SCEV for {0,+,1}<L>.
1908  // Conservatively use FlagAnyWrap for now.
1909  const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1910  SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1911 
1912  // Emit code for it.
1913  SCEVInsertPointGuard Guard(Builder, this);
1914  PHINode *V =
1915  cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1916 
1917  return V;
1918 }
1919 
1920 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1921 /// replace them with their most canonical representative. Return the number of
1922 /// phis eliminated.
1923 ///
1924 /// This does not depend on any SCEVExpander state but should be used in
1925 /// the same context that SCEVExpander is used.
1926 unsigned
1929  const TargetTransformInfo *TTI) {
1930  // Find integer phis in order of increasing width.
1932  for (PHINode &PN : L->getHeader()->phis())
1933  Phis.push_back(&PN);
1934 
1935  if (TTI)
1936  llvm::sort(Phis, [](Value *LHS, Value *RHS) {
1937  // Put pointers at the back and make sure pointer < pointer = false.
1938  if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1939  return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1940  return RHS->getType()->getPrimitiveSizeInBits() <
1941  LHS->getType()->getPrimitiveSizeInBits();
1942  });
1943 
1944  unsigned NumElim = 0;
1946  // Process phis from wide to narrow. Map wide phis to their truncation
1947  // so narrow phis can reuse them.
1948  for (PHINode *Phi : Phis) {
1949  auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1950  if (Value *V = SimplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1951  return V;
1952  if (!SE.isSCEVable(PN->getType()))
1953  return nullptr;
1954  auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1955  if (!Const)
1956  return nullptr;
1957  return Const->getValue();
1958  };
1959 
1960  // Fold constant phis. They may be congruent to other constant phis and
1961  // would confuse the logic below that expects proper IVs.
1962  if (Value *V = SimplifyPHINode(Phi)) {
1963  if (V->getType() != Phi->getType())
1964  continue;
1965  Phi->replaceAllUsesWith(V);
1966  DeadInsts.emplace_back(Phi);
1967  ++NumElim;
1969  << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1970  continue;
1971  }
1972 
1973  if (!SE.isSCEVable(Phi->getType()))
1974  continue;
1975 
1976  PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1977  if (!OrigPhiRef) {
1978  OrigPhiRef = Phi;
1979  if (Phi->getType()->isIntegerTy() && TTI &&
1980  TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1981  // This phi can be freely truncated to the narrowest phi type. Map the
1982  // truncated expression to it so it will be reused for narrow types.
1983  const SCEV *TruncExpr =
1984  SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1985  ExprToIVMap[TruncExpr] = Phi;
1986  }
1987  continue;
1988  }
1989 
1990  // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1991  // sense.
1992  if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1993  continue;
1994 
1995  if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1996  Instruction *OrigInc = dyn_cast<Instruction>(
1997  OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1998  Instruction *IsomorphicInc =
1999  dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
2000 
2001  if (OrigInc && IsomorphicInc) {
2002  // If this phi has the same width but is more canonical, replace the
2003  // original with it. As part of the "more canonical" determination,
2004  // respect a prior decision to use an IV chain.
2005  if (OrigPhiRef->getType() == Phi->getType() &&
2006  !(ChainedPhis.count(Phi) ||
2007  isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
2008  (ChainedPhis.count(Phi) ||
2009  isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
2010  std::swap(OrigPhiRef, Phi);
2011  std::swap(OrigInc, IsomorphicInc);
2012  }
2013  // Replacing the congruent phi is sufficient because acyclic
2014  // redundancy elimination, CSE/GVN, should handle the
2015  // rest. However, once SCEV proves that a phi is congruent,
2016  // it's often the head of an IV user cycle that is isomorphic
2017  // with the original phi. It's worth eagerly cleaning up the
2018  // common case of a single IV increment so that DeleteDeadPHIs
2019  // can remove cycles that had postinc uses.
2020  const SCEV *TruncExpr =
2021  SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
2022  if (OrigInc != IsomorphicInc &&
2023  TruncExpr == SE.getSCEV(IsomorphicInc) &&
2024  SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
2025  hoistIVInc(OrigInc, IsomorphicInc)) {
2027  dbgs() << "INDVARS: Eliminated congruent iv.inc: "
2028  << *IsomorphicInc << '\n');
2029  Value *NewInc = OrigInc;
2030  if (OrigInc->getType() != IsomorphicInc->getType()) {
2031  Instruction *IP = nullptr;
2032  if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
2033  IP = &*PN->getParent()->getFirstInsertionPt();
2034  else
2035  IP = OrigInc->getNextNode();
2036 
2037  IRBuilder<> Builder(IP);
2038  Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
2039  NewInc = Builder.CreateTruncOrBitCast(
2040  OrigInc, IsomorphicInc->getType(), IVName);
2041  }
2042  IsomorphicInc->replaceAllUsesWith(NewInc);
2043  DeadInsts.emplace_back(IsomorphicInc);
2044  }
2045  }
2046  }
2047  DEBUG_WITH_TYPE(DebugType, dbgs() << "INDVARS: Eliminated congruent iv: "
2048  << *Phi << '\n');
2049  ++NumElim;
2050  Value *NewIV = OrigPhiRef;
2051  if (OrigPhiRef->getType() != Phi->getType()) {
2052  IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
2053  Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
2054  NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
2055  }
2056  Phi->replaceAllUsesWith(NewIV);
2057  DeadInsts.emplace_back(Phi);
2058  }
2059  return NumElim;
2060 }
2061 
2063  const Instruction *At, Loop *L) {
2065  getRelatedExistingExpansion(S, At, L);
2066  if (VO && VO.getValue().second == nullptr)
2067  return VO.getValue().first;
2068  return nullptr;
2069 }
2070 
2073  Loop *L) {
2074  using namespace llvm::PatternMatch;
2075 
2076  SmallVector<BasicBlock *, 4> ExitingBlocks;
2077  L->getExitingBlocks(ExitingBlocks);
2078 
2079  // Look for suitable value in simple conditions at the loop exits.
2080  for (BasicBlock *BB : ExitingBlocks) {
2081  ICmpInst::Predicate Pred;
2082  Instruction *LHS, *RHS;
2083  BasicBlock *TrueBB, *FalseBB;
2084 
2085  if (!match(BB->getTerminator(),
2086  m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
2087  TrueBB, FalseBB)))
2088  continue;
2089 
2090  if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
2091  return ScalarEvolution::ValueOffsetPair(LHS, nullptr);
2092 
2093  if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2094  return ScalarEvolution::ValueOffsetPair(RHS, nullptr);
2095  }
2096 
2097  // Use expand's logic which is used for reusing a previous Value in
2098  // ExprValueMap.
2099  ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
2100  if (VO.first)
2101  return VO;
2102 
2103  // There is potential to make this significantly smarter, but this simple
2104  // heuristic already gets some interesting cases.
2105 
2106  // Can not find suitable value.
2107  return None;
2108 }
2109 
2110 bool SCEVExpander::isHighCostExpansionHelper(
2111  const SCEV *S, Loop *L, const Instruction *At,
2112  SmallPtrSetImpl<const SCEV *> &Processed) {
2113 
2114  // If we can find an existing value for this scev available at the point "At"
2115  // then consider the expression cheap.
2116  if (At && getRelatedExistingExpansion(S, At, L))
2117  return false;
2118 
2119  // Zero/One operand expressions
2120  switch (S->getSCEVType()) {
2121  case scUnknown:
2122  case scConstant:
2123  return false;
2124  case scTruncate:
2125  return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
2126  L, At, Processed);
2127  case scZeroExtend:
2128  return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
2129  L, At, Processed);
2130  case scSignExtend:
2131  return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
2132  L, At, Processed);
2133  }
2134 
2135  if (!Processed.insert(S).second)
2136  return false;
2137 
2138  if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
2139  // If the divisor is a power of two and the SCEV type fits in a native
2140  // integer (and the LHS not expensive), consider the division cheap
2141  // irrespective of whether it occurs in the user code since it can be
2142  // lowered into a right shift.
2143  if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
2144  if (SC->getAPInt().isPowerOf2()) {
2145  if (isHighCostExpansionHelper(UDivExpr->getLHS(), L, At, Processed))
2146  return true;
2147  const DataLayout &DL =
2149  unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
2150  return DL.isIllegalInteger(Width);
2151  }
2152 
2153  // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2154  // HowManyLessThans produced to compute a precise expression, rather than a
2155  // UDiv from the user's code. If we can't find a UDiv in the code with some
2156  // simple searching, assume the former consider UDivExpr expensive to
2157  // compute.
2158  BasicBlock *ExitingBB = L->getExitingBlock();
2159  if (!ExitingBB)
2160  return true;
2161 
2162  // At the beginning of this function we already tried to find existing value
2163  // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
2164  // involving division. This is just a simple search heuristic.
2165  if (!At)
2166  At = &ExitingBB->back();
2167  if (!getRelatedExistingExpansion(
2168  SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
2169  return true;
2170  }
2171 
2172  // HowManyLessThans uses a Max expression whenever the loop is not guarded by
2173  // the exit condition.
2174  if (isa<SCEVMinMaxExpr>(S))
2175  return true;
2176 
2177  // Recurse past nary expressions, which commonly occur in the
2178  // BackedgeTakenCount. They may already exist in program code, and if not,
2179  // they are not too expensive rematerialize.
2180  if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
2181  for (auto *Op : NAry->operands())
2182  if (isHighCostExpansionHelper(Op, L, At, Processed))
2183  return true;
2184  }
2185 
2186  // If we haven't recognized an expensive SCEV pattern, assume it's an
2187  // expression produced by program code.
2188  return false;
2189 }
2190 
2192  Instruction *IP) {
2193  assert(IP);
2194  switch (Pred->getKind()) {
2196  return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2198  return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
2199  case SCEVPredicate::P_Wrap: {
2200  auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2201  return expandWrapPredicate(AddRecPred, IP);
2202  }
2203  }
2204  llvm_unreachable("Unknown SCEV predicate type");
2205 }
2206 
2208  Instruction *IP) {
2209  Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
2210  Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
2211 
2212  Builder.SetInsertPoint(IP);
2213  auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
2214  return I;
2215 }
2216 
2218  Instruction *Loc, bool Signed) {
2219  assert(AR->isAffine() && "Cannot generate RT check for "
2220  "non-affine expression");
2221 
2222  SCEVUnionPredicate Pred;
2223  const SCEV *ExitCount =
2224  SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
2225 
2226  assert(ExitCount != SE.getCouldNotCompute() && "Invalid loop count");
2227 
2228  const SCEV *Step = AR->getStepRecurrence(SE);
2229  const SCEV *Start = AR->getStart();
2230 
2231  Type *ARTy = AR->getType();
2232  unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2233  unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2234 
2235  // The expression {Start,+,Step} has nusw/nssw if
2236  // Step < 0, Start - |Step| * Backedge <= Start
2237  // Step >= 0, Start + |Step| * Backedge > Start
2238  // and |Step| * Backedge doesn't unsigned overflow.
2239 
2240  IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2241  Builder.SetInsertPoint(Loc);
2242  Value *TripCountVal = expandCodeFor(ExitCount, CountTy, Loc);
2243 
2244  IntegerType *Ty =
2245  IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2246  Type *ARExpandTy = DL.isNonIntegralPointerType(ARTy) ? ARTy : Ty;
2247 
2248  Value *StepValue = expandCodeFor(Step, Ty, Loc);
2249  Value *NegStepValue = expandCodeFor(SE.getNegativeSCEV(Step), Ty, Loc);
2250  Value *StartValue = expandCodeFor(Start, ARExpandTy, Loc);
2251 
2252  ConstantInt *Zero =
2254 
2255  Builder.SetInsertPoint(Loc);
2256  // Compute |Step|
2257  Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2258  Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2259 
2260  // Get the backedge taken count and truncate or extended to the AR type.
2261  Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2262  auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2263  Intrinsic::umul_with_overflow, Ty);
2264 
2265  // Compute |Step| * Backedge
2266  CallInst *Mul = Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2267  Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2268  Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2269 
2270  // Compute:
2271  // Start + |Step| * Backedge < Start
2272  // Start - |Step| * Backedge > Start
2273  Value *Add = nullptr, *Sub = nullptr;
2274  if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARExpandTy)) {
2275  const SCEV *MulS = SE.getSCEV(MulV);
2276  const SCEV *NegMulS = SE.getNegativeSCEV(MulS);
2277  Add = Builder.CreateBitCast(expandAddToGEP(MulS, ARPtrTy, Ty, StartValue),
2278  ARPtrTy);
2279  Sub = Builder.CreateBitCast(
2280  expandAddToGEP(NegMulS, ARPtrTy, Ty, StartValue), ARPtrTy);
2281  } else {
2282  Add = Builder.CreateAdd(StartValue, MulV);
2283  Sub = Builder.CreateSub(StartValue, MulV);
2284  }
2285 
2286  Value *EndCompareGT = Builder.CreateICmp(
2287  Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2288 
2289  Value *EndCompareLT = Builder.CreateICmp(
2290  Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2291 
2292  // Select the answer based on the sign of Step.
2293  Value *EndCheck =
2294  Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2295 
2296  // If the backedge taken count type is larger than the AR type,
2297  // check that we don't drop any bits by truncating it. If we are
2298  // dropping bits, then we have overflow (unless the step is zero).
2299  if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2300  auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2301  auto *BackedgeCheck =
2302  Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2303  ConstantInt::get(Loc->getContext(), MaxVal));
2304  BackedgeCheck = Builder.CreateAnd(
2305  BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2306 
2307  EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2308  }
2309 
2310  EndCheck = Builder.CreateOr(EndCheck, OfMul);
2311  return EndCheck;
2312 }
2313 
2315  Instruction *IP) {
2316  const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2317  Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2318 
2319  // Add a check for NUSW
2321  NUSWCheck = generateOverflowCheck(A, IP, false);
2322 
2323  // Add a check for NSSW
2325  NSSWCheck = generateOverflowCheck(A, IP, true);
2326 
2327  if (NUSWCheck && NSSWCheck)
2328  return Builder.CreateOr(NUSWCheck, NSSWCheck);
2329 
2330  if (NUSWCheck)
2331  return NUSWCheck;
2332 
2333  if (NSSWCheck)
2334  return NSSWCheck;
2335 
2336  return ConstantInt::getFalse(IP->getContext());
2337 }
2338 
2340  Instruction *IP) {
2341  auto *BoolType = IntegerType::get(IP->getContext(), 1);
2342  Value *Check = ConstantInt::getNullValue(BoolType);
2343 
2344  // Loop over all checks in this set.
2345  for (auto Pred : Union->getPredicates()) {
2346  auto *NextCheck = expandCodeForPredicate(Pred, IP);
2347  Builder.SetInsertPoint(IP);
2348  Check = Builder.CreateOr(Check, NextCheck);
2349  }
2350 
2351  return Check;
2352 }
2353 
2354 namespace {
2355 // Search for a SCEV subexpression that is not safe to expand. Any expression
2356 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2357 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2358 // instruction, but the important thing is that we prove the denominator is
2359 // nonzero before expansion.
2360 //
2361 // IVUsers already checks that IV-derived expressions are safe. So this check is
2362 // only needed when the expression includes some subexpression that is not IV
2363 // derived.
2364 //
2365 // Currently, we only allow division by a nonzero constant here. If this is
2366 // inadequate, we could easily allow division by SCEVUnknown by using
2367 // ValueTracking to check isKnownNonZero().
2368 //
2369 // We cannot generally expand recurrences unless the step dominates the loop
2370 // header. The expander handles the special case of affine recurrences by
2371 // scaling the recurrence outside the loop, but this technique isn't generally
2372 // applicable. Expanding a nested recurrence outside a loop requires computing
2373 // binomial coefficients. This could be done, but the recurrence has to be in a
2374 // perfectly reduced form, which can't be guaranteed.
2375 struct SCEVFindUnsafe {
2376  ScalarEvolution &SE;
2377  bool IsUnsafe;
2378 
2379  SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
2380 
2381  bool follow(const SCEV *S) {
2382  if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2383  const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2384  if (!SC || SC->getValue()->isZero()) {
2385  IsUnsafe = true;
2386  return false;
2387  }
2388  }
2389  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2390  const SCEV *Step = AR->getStepRecurrence(SE);
2391  if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2392  IsUnsafe = true;
2393  return false;
2394  }
2395  }
2396  return true;
2397  }
2398  bool isDone() const { return IsUnsafe; }
2399 };
2400 }
2401 
2402 namespace llvm {
2403 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2404  SCEVFindUnsafe Search(SE);
2405  visitAll(S, Search);
2406  return !Search.IsUnsafe;
2407 }
2408 
2409 bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint,
2410  ScalarEvolution &SE) {
2411  if (!isSafeToExpand(S, SE))
2412  return false;
2413  // We have to prove that the expanded site of S dominates InsertionPoint.
2414  // This is easy when not in the same block, but hard when S is an instruction
2415  // to be expanded somewhere inside the same block as our insertion point.
2416  // What we really need here is something analogous to an OrderedBasicBlock,
2417  // but for the moment, we paper over the problem by handling two common and
2418  // cheap to check cases.
2419  if (SE.properlyDominates(S, InsertionPoint->getParent()))
2420  return true;
2421  if (SE.dominates(S, InsertionPoint->getParent())) {
2422  if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2423  return true;
2424  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2425  for (const Value *V : InsertionPoint->operand_values())
2426  if (V == U->getValue())
2427  return true;
2428  }
2429  return false;
2430 }
2431 }
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static bool Check(DecodeStatus &Out, DecodeStatus In)
const NoneType None
Definition: None.h:23
uint64_t CallInst * C
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos)
Utility for hoisting an IV increment.
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:594
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:645
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:172
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:224
Value * getExactExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find existing LLVM IR value for S available at the point At.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
const SCEV * getConstant(ConstantInt *V)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1153
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:264
bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are d...
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Normalize S to be post-increment for all loops present in Loops.
The main scalar evolution driver.
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:857
bool isZero() const
Return true if the expression is a constant zero.
This class represents a function call, abstracting a target machine&#39;s calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:173
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:629
unsigned less than
Definition: InstrTypes.h:734
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block...
Optional< ScalarEvolution::ValueOffsetPair > getRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Try to find the ValueOffsetPair for S.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:709
This class represents a truncation of an integer value to a smaller integer value.
Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
A debug info location.
Definition: DebugLoc.h:33
const SCEV * getOperand() const
Hexagon Common GEP
static void SimplifyAddOperands(SmallVectorImpl< const SCEV *> &Ops, Type *Ty, ScalarEvolution &SE)
SimplifyAddOperands - Sort and simplify a list of add operands.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
op_iterator op_begin()
Definition: User.h:229
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
Definition: DataLayout.cpp:83
This is the base class for unary cast operator classes.
return AArch64::GPR64RegClass contains(Reg)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:129
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:274
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:554
Hexagon Hardware Loops
Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
Type * getPointerElementType() const
Definition: Type.h:375
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
static const Loop * PickMostRelevantLoop(const Loop *A, const Loop *B, DominatorTree &DT)
PickMostRelevantLoop - Given two loops pick the one that&#39;s most relevant for SCEV expansion...
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:416
Class to represent struct types.
Definition: DerivedTypes.h:232
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
LLVMContext & getContext() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
This node represents multiplication of some number of SCEVs.
Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
const APInt & getAPInt() const
BlockT * getHeader() const
Definition: LoopInfo.h:100
ConstantInt * getValue() const
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
#define UINT64_MAX
Definition: DataTypes.h:83
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool isTruncateFree(Type *Ty1, Type *Ty2) const
Return true if it&#39;s free to truncate a value of type Ty1 to type Ty2.
This node represents a polynomial recurrence on the trip count of the specified loop.
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:255
Class to represent array types.
Definition: DerivedTypes.h:400
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
op_iterator op_begin() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:150
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:384
This class represents a signed minimum selection.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1022
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
Definition: User.h:169
Class to represent pointers.
Definition: DerivedTypes.h:498
#define P(N)
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
const SCEV * getOperand(unsigned i) const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:216
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:318
SCEVPredicateKind getKind() const
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
This class represents a binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an unsigned minimum selection.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
const Instruction & front() const
Definition: BasicBlock.h:280
#define H(x, y, z)
Definition: MD5.cpp:57
const SCEV * getExpr() const override
Implementation of the SCEVPredicate interface.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Definition: Instruction.h:572
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getLHS() const
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
op_iterator op_end()
Definition: User.h:231
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1192
const Instruction & back() const
Definition: BasicBlock.h:282
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:709
static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder, const SCEV *Factor, ScalarEvolution &SE, const DataLayout &DL)
FactorOutConstant - Test if S is divisible by Factor, using signed division.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:526
self_iterator getIterator()
Definition: ilist_node.h:81
Class to represent integer types.
Definition: DerivedTypes.h:39
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
static Expected< BitVector > expand(StringRef S, StringRef Original)
Definition: GlobPattern.cpp:27
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:59
const SCEV * getLHS() const
Returns the left hand side of the equality.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
Definition: LoopInfoImpl.h:34
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1424
const SCEV * getRHS() const
Returns the right hand side of the equality.
size_t size() const
Definition: SmallVector.h:52
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:219
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static void SplitAddRecs(SmallVectorImpl< const SCEV *> &Ops, Type *Ty, ScalarEvolution &SE)
SplitAddRecs - Flatten a list of add operands, moving addrec start values out to the top level...
signed greater than
Definition: InstrTypes.h:736
This class represents an assumption made using SCEV expressions which can be checked at run-time...
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1115
static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest, ScalarEvolution &SE)
Move parts of Base into Rest to leave Base with the minimal expression that provides a pointer operan...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:239
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
unsigned getSCEVType() const
bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
unsigned getNumOperands() const
Definition: User.h:191
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:215
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
Type * getType() const
Return the LLVM type of this SCEV expression.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
PHINode * getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty)
This method returns the canonical induction variable of the specified type for the specified loop (in...
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:248
Module.h This file contains the declarations for the Module class.
signed less than
Definition: InstrTypes.h:738
uint64_t getSizeInBytes() const
Definition: DataLayout.h:562
CHAIN = SC CHAIN, Imm128 - System call.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:631
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.cpp:645
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
unsigned logBase2() const
Definition: APInt.h:1747
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Definition: LoopInfo.cpp:144
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
Class for arbitrary precision integers.
Definition: APInt.h:69
This node represents an addition of some number of SCEVs.
static BasicBlock::iterator findInsertPointAfter(Instruction *I, BasicBlock *MustDominate)
bool isPowerOf2() const
Check if this APInt&#39;s value is a power of two greater than zero.
Definition: APInt.h:463
This class represents a signed maximum selection.
iterator_range< user_iterator > users()
Definition: Value.h:399
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:89
Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1539
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition: APInt.h:529
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
This class represents a zero extension of a small integer value to a larger integer value...
Value * CreateTruncOrBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1795
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
LoopT * getParentLoop() const
Definition: LoopInfo.h:101
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass&#39;s ...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:321
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:576
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
unsigned getIntegerBitWidth() const
Definition: DerivedTypes.h:96
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:465
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:192
iterator_range< value_op_iterator > operand_values()
Definition: User.h:261
This class represents a sign extension of a small integer value to a larger integer value...
This class represents an unsigned maximum selection.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment&#39;s IV operand.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:324
const SCEV * getRHS() const
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
const SmallVectorImpl< const SCEVPredicate * > & getPredicates() const
DebugType
Definition: COFF.h:645
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents a composition of other SCEV predicates, and is the class that most clients will...
bool isOne() const
Return true if the expression is a constant one.
void stable_sort(R &&Range)
Definition: STLExtras.h:1309
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
Value * expandEqualPredicate(const SCEVEqualPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM Value Representation.
Definition: Value.h:72
A vector that has set insertion semantics.
Definition: SetVector.h:40
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:86
static Value * SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q)
See if we can fold the given phi. If not, returns null.
bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block...
unsigned greater than
Definition: InstrTypes.h:732
This pass exposes codegen information to IR-level passes.
bool isIllegalInteger(uint64_t Width) const
Definition: DataLayout.h:261
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:568
This node is a base class providing common functionality for n&#39;ary operators.
This class represents an assumption made on an AddRec expression.
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Definition: LoopInfoImpl.h:49
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
This class represents an assumption that two SCEV expressions are equal, and this can be checked at r...
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
Type * getElementType() const
Definition: DerivedTypes.h:517
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:478
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const BasicBlock * getParent() const
Definition: Instruction.h:66
static bool canBeCheaplyTransformed(ScalarEvolution &SE, const SCEVAddRecExpr *Phi, const SCEVAddRecExpr *Requested, bool &InvertStep)
Check whether we can cheaply express the requested SCEV in terms of the available PHI SCEV by truncat...
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1815