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
15 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/LoopUtils.h"
29
30 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
31 #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
32 #else
33 #define SCEV_DEBUG_WITH_TYPE(TYPE, X)
34 #endif
35
36 using namespace llvm;
37
38 cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
39 "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
40 cl::desc("When performing SCEV expansion only if it is cheap to do, this "
41 "controls the budget that is considered cheap (default = 4)"));
42
43 using namespace PatternMatch;
44
45 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
46 /// reusing an existing cast if a suitable one (= dominating IP) exists, or
47 /// creating a new one.
ReuseOrCreateCast(Value * V,Type * Ty,Instruction::CastOps Op,BasicBlock::iterator IP)48 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
49 Instruction::CastOps Op,
50 BasicBlock::iterator IP) {
51 // This function must be called with the builder having a valid insertion
52 // point. It doesn't need to be the actual IP where the uses of the returned
53 // cast will be added, but it must dominate such IP.
54 // We use this precondition to produce a cast that will dominate all its
55 // uses. In particular, this is crucial for the case where the builder's
56 // insertion point *is* the point where we were asked to put the cast.
57 // Since we don't know the builder's insertion point is actually
58 // where the uses will be added (only that it dominates it), we are
59 // not allowed to move it.
60 BasicBlock::iterator BIP = Builder.GetInsertPoint();
61
62 Value *Ret = nullptr;
63
64 // Check to see if there is already a cast!
65 for (User *U : V->users()) {
66 if (U->getType() != Ty)
67 continue;
68 CastInst *CI = dyn_cast<CastInst>(U);
69 if (!CI || CI->getOpcode() != Op)
70 continue;
71
72 // Found a suitable cast that is at IP or comes before IP. Use it. Note that
73 // the cast must also properly dominate the Builder's insertion point.
74 if (IP->getParent() == CI->getParent() && &*BIP != CI &&
75 (&*IP == CI || CI->comesBefore(&*IP))) {
76 Ret = CI;
77 break;
78 }
79 }
80
81 // Create a new cast.
82 if (!Ret) {
83 SCEVInsertPointGuard Guard(Builder, this);
84 Builder.SetInsertPoint(&*IP);
85 Ret = Builder.CreateCast(Op, V, Ty, V->getName());
86 }
87
88 // We assert at the end of the function since IP might point to an
89 // instruction with different dominance properties than a cast
90 // (an invoke for example) and not dominate BIP (but the cast does).
91 assert(!isa<Instruction>(Ret) ||
92 SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
93
94 return Ret;
95 }
96
97 BasicBlock::iterator
findInsertPointAfter(Instruction * I,Instruction * MustDominate) const98 SCEVExpander::findInsertPointAfter(Instruction *I,
99 Instruction *MustDominate) const {
100 BasicBlock::iterator IP = ++I->getIterator();
101 if (auto *II = dyn_cast<InvokeInst>(I))
102 IP = II->getNormalDest()->begin();
103
104 while (isa<PHINode>(IP))
105 ++IP;
106
107 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
108 ++IP;
109 } else if (isa<CatchSwitchInst>(IP)) {
110 IP = MustDominate->getParent()->getFirstInsertionPt();
111 } else {
112 assert(!IP->isEHPad() && "unexpected eh pad!");
113 }
114
115 // Adjust insert point to be after instructions inserted by the expander, so
116 // we can re-use already inserted instructions. Avoid skipping past the
117 // original \p MustDominate, in case it is an inserted instruction.
118 while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
119 ++IP;
120
121 return IP;
122 }
123
124 BasicBlock::iterator
GetOptimalInsertionPointForCastOf(Value * V) const125 SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
126 // Cast the argument at the beginning of the entry block, after
127 // any bitcasts of other arguments.
128 if (Argument *A = dyn_cast<Argument>(V)) {
129 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
130 while ((isa<BitCastInst>(IP) &&
131 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
132 cast<BitCastInst>(IP)->getOperand(0) != A) ||
133 isa<DbgInfoIntrinsic>(IP))
134 ++IP;
135 return IP;
136 }
137
138 // Cast the instruction immediately after the instruction.
139 if (Instruction *I = dyn_cast<Instruction>(V))
140 return findInsertPointAfter(I, &*Builder.GetInsertPoint());
141
142 // Otherwise, this must be some kind of a constant,
143 // so let's plop this cast into the function's entry block.
144 assert(isa<Constant>(V) &&
145 "Expected the cast argument to be a global/constant");
146 return Builder.GetInsertBlock()
147 ->getParent()
148 ->getEntryBlock()
149 .getFirstInsertionPt();
150 }
151
152 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
153 /// which must be possible with a noop cast, doing what we can to share
154 /// the casts.
InsertNoopCastOfTo(Value * V,Type * Ty)155 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
156 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
157 assert((Op == Instruction::BitCast ||
158 Op == Instruction::PtrToInt ||
159 Op == Instruction::IntToPtr) &&
160 "InsertNoopCastOfTo cannot perform non-noop casts!");
161 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
162 "InsertNoopCastOfTo cannot change sizes!");
163
164 // inttoptr only works for integral pointers. For non-integral pointers, we
165 // can create a GEP on i8* null with the integral value as index. Note that
166 // it is safe to use GEP of null instead of inttoptr here, because only
167 // expressions already based on a GEP of null should be converted to pointers
168 // during expansion.
169 if (Op == Instruction::IntToPtr) {
170 auto *PtrTy = cast<PointerType>(Ty);
171 if (DL.isNonIntegralPointerType(PtrTy)) {
172 auto *Int8PtrTy = Builder.getInt8PtrTy(PtrTy->getAddressSpace());
173 assert(DL.getTypeAllocSize(Builder.getInt8Ty()) == 1 &&
174 "alloc size of i8 must by 1 byte for the GEP to be correct");
175 auto *GEP = Builder.CreateGEP(
176 Builder.getInt8Ty(), Constant::getNullValue(Int8PtrTy), V, "uglygep");
177 return Builder.CreateBitCast(GEP, Ty);
178 }
179 }
180 // Short-circuit unnecessary bitcasts.
181 if (Op == Instruction::BitCast) {
182 if (V->getType() == Ty)
183 return V;
184 if (CastInst *CI = dyn_cast<CastInst>(V)) {
185 if (CI->getOperand(0)->getType() == Ty)
186 return CI->getOperand(0);
187 }
188 }
189 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
190 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
191 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
192 if (CastInst *CI = dyn_cast<CastInst>(V))
193 if ((CI->getOpcode() == Instruction::PtrToInt ||
194 CI->getOpcode() == Instruction::IntToPtr) &&
195 SE.getTypeSizeInBits(CI->getType()) ==
196 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
197 return CI->getOperand(0);
198 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
199 if ((CE->getOpcode() == Instruction::PtrToInt ||
200 CE->getOpcode() == Instruction::IntToPtr) &&
201 SE.getTypeSizeInBits(CE->getType()) ==
202 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
203 return CE->getOperand(0);
204 }
205
206 // Fold a cast of a constant.
207 if (Constant *C = dyn_cast<Constant>(V))
208 return ConstantExpr::getCast(Op, C, Ty);
209
210 // Try to reuse existing cast, or insert one.
211 return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
212 }
213
214 /// InsertBinop - Insert the specified binary operator, doing a small amount
215 /// of work to avoid inserting an obviously redundant operation, and hoisting
216 /// to an outer loop when the opportunity is there and it is safe.
InsertBinop(Instruction::BinaryOps Opcode,Value * LHS,Value * RHS,SCEV::NoWrapFlags Flags,bool IsSafeToHoist)217 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
218 Value *LHS, Value *RHS,
219 SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
220 // Fold a binop with constant operands.
221 if (Constant *CLHS = dyn_cast<Constant>(LHS))
222 if (Constant *CRHS = dyn_cast<Constant>(RHS))
223 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, DL))
224 return Res;
225
226 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
227 unsigned ScanLimit = 6;
228 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
229 // Scanning starts from the last instruction before the insertion point.
230 BasicBlock::iterator IP = Builder.GetInsertPoint();
231 if (IP != BlockBegin) {
232 --IP;
233 for (; ScanLimit; --IP, --ScanLimit) {
234 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
235 // generated code.
236 if (isa<DbgInfoIntrinsic>(IP))
237 ScanLimit++;
238
239 auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
240 // Ensure that no-wrap flags match.
241 if (isa<OverflowingBinaryOperator>(I)) {
242 if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
243 return true;
244 if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
245 return true;
246 }
247 // Conservatively, do not use any instruction which has any of exact
248 // flags installed.
249 if (isa<PossiblyExactOperator>(I) && I->isExact())
250 return true;
251 return false;
252 };
253 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
254 IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
255 return &*IP;
256 if (IP == BlockBegin) break;
257 }
258 }
259
260 // Save the original insertion point so we can restore it when we're done.
261 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
262 SCEVInsertPointGuard Guard(Builder, this);
263
264 if (IsSafeToHoist) {
265 // Move the insertion point out of as many loops as we can.
266 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
267 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
268 BasicBlock *Preheader = L->getLoopPreheader();
269 if (!Preheader) break;
270
271 // Ok, move up a level.
272 Builder.SetInsertPoint(Preheader->getTerminator());
273 }
274 }
275
276 // If we haven't found this binop, insert it.
277 // TODO: Use the Builder, which will make CreateBinOp below fold with
278 // InstSimplifyFolder.
279 Instruction *BO = Builder.Insert(BinaryOperator::Create(Opcode, LHS, RHS));
280 BO->setDebugLoc(Loc);
281 if (Flags & SCEV::FlagNUW)
282 BO->setHasNoUnsignedWrap();
283 if (Flags & SCEV::FlagNSW)
284 BO->setHasNoSignedWrap();
285
286 return BO;
287 }
288
289 /// FactorOutConstant - Test if S is divisible by Factor, using signed
290 /// division. If so, update S with Factor divided out and return true.
291 /// S need not be evenly divisible if a reasonable remainder can be
292 /// computed.
FactorOutConstant(const SCEV * & S,const SCEV * & Remainder,const SCEV * Factor,ScalarEvolution & SE,const DataLayout & DL)293 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
294 const SCEV *Factor, ScalarEvolution &SE,
295 const DataLayout &DL) {
296 // Everything is divisible by one.
297 if (Factor->isOne())
298 return true;
299
300 // x/x == 1.
301 if (S == Factor) {
302 S = SE.getConstant(S->getType(), 1);
303 return true;
304 }
305
306 // For a Constant, check for a multiple of the given factor.
307 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
308 // 0/x == 0.
309 if (C->isZero())
310 return true;
311 // Check for divisibility.
312 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
313 ConstantInt *CI =
314 ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
315 // If the quotient is zero and the remainder is non-zero, reject
316 // the value at this scale. It will be considered for subsequent
317 // smaller scales.
318 if (!CI->isZero()) {
319 const SCEV *Div = SE.getConstant(CI);
320 S = Div;
321 Remainder = SE.getAddExpr(
322 Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
323 return true;
324 }
325 }
326 }
327
328 // In a Mul, check if there is a constant operand which is a multiple
329 // of the given factor.
330 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
331 // Size is known, check if there is a constant operand which is a multiple
332 // of the given factor. If so, we can factor it.
333 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor))
334 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
335 if (!C->getAPInt().srem(FC->getAPInt())) {
336 SmallVector<const SCEV *, 4> NewMulOps(M->operands());
337 NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
338 S = SE.getMulExpr(NewMulOps);
339 return true;
340 }
341 }
342
343 // In an AddRec, check if both start and step are divisible.
344 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
345 const SCEV *Step = A->getStepRecurrence(SE);
346 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
347 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
348 return false;
349 if (!StepRem->isZero())
350 return false;
351 const SCEV *Start = A->getStart();
352 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
353 return false;
354 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
355 A->getNoWrapFlags(SCEV::FlagNW));
356 return true;
357 }
358
359 return false;
360 }
361
362 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
363 /// is the number of SCEVAddRecExprs present, which are kept at the end of
364 /// the list.
365 ///
SimplifyAddOperands(SmallVectorImpl<const SCEV * > & Ops,Type * Ty,ScalarEvolution & SE)366 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
367 Type *Ty,
368 ScalarEvolution &SE) {
369 unsigned NumAddRecs = 0;
370 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
371 ++NumAddRecs;
372 // Group Ops into non-addrecs and addrecs.
373 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
374 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
375 // Let ScalarEvolution sort and simplify the non-addrecs list.
376 const SCEV *Sum = NoAddRecs.empty() ?
377 SE.getConstant(Ty, 0) :
378 SE.getAddExpr(NoAddRecs);
379 // If it returned an add, use the operands. Otherwise it simplified
380 // the sum into a single value, so just use that.
381 Ops.clear();
382 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
383 Ops.append(Add->op_begin(), Add->op_end());
384 else if (!Sum->isZero())
385 Ops.push_back(Sum);
386 // Then append the addrecs.
387 Ops.append(AddRecs.begin(), AddRecs.end());
388 }
389
390 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
391 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
392 /// This helps expose more opportunities for folding parts of the expressions
393 /// into GEP indices.
394 ///
SplitAddRecs(SmallVectorImpl<const SCEV * > & Ops,Type * Ty,ScalarEvolution & SE)395 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
396 Type *Ty,
397 ScalarEvolution &SE) {
398 // Find the addrecs.
399 SmallVector<const SCEV *, 8> AddRecs;
400 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
401 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
402 const SCEV *Start = A->getStart();
403 if (Start->isZero()) break;
404 const SCEV *Zero = SE.getConstant(Ty, 0);
405 AddRecs.push_back(SE.getAddRecExpr(Zero,
406 A->getStepRecurrence(SE),
407 A->getLoop(),
408 A->getNoWrapFlags(SCEV::FlagNW)));
409 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
410 Ops[i] = Zero;
411 Ops.append(Add->op_begin(), Add->op_end());
412 e += Add->getNumOperands();
413 } else {
414 Ops[i] = Start;
415 }
416 }
417 if (!AddRecs.empty()) {
418 // Add the addrecs onto the end of the list.
419 Ops.append(AddRecs.begin(), AddRecs.end());
420 // Resort the operand list, moving any constants to the front.
421 SimplifyAddOperands(Ops, Ty, SE);
422 }
423 }
424
425 /// expandAddToGEP - Expand an addition expression with a pointer type into
426 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
427 /// BasicAliasAnalysis and other passes analyze the result. See the rules
428 /// for getelementptr vs. inttoptr in
429 /// http://llvm.org/docs/LangRef.html#pointeraliasing
430 /// for details.
431 ///
432 /// Design note: The correctness of using getelementptr here depends on
433 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
434 /// they may introduce pointer arithmetic which may not be safely converted
435 /// into getelementptr.
436 ///
437 /// Design note: It might seem desirable for this function to be more
438 /// loop-aware. If some of the indices are loop-invariant while others
439 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
440 /// loop-invariant portions of the overall computation outside the loop.
441 /// However, there are a few reasons this is not done here. Hoisting simple
442 /// arithmetic is a low-level optimization that often isn't very
443 /// important until late in the optimization process. In fact, passes
444 /// like InstructionCombining will combine GEPs, even if it means
445 /// pushing loop-invariant computation down into loops, so even if the
446 /// GEPs were split here, the work would quickly be undone. The
447 /// LoopStrengthReduction pass, which is usually run quite late (and
448 /// after the last InstructionCombining pass), takes care of hoisting
449 /// loop-invariant portions of expressions, after considering what
450 /// can be folded using target addressing modes.
451 ///
expandAddToGEP(const SCEV * const * op_begin,const SCEV * const * op_end,PointerType * PTy,Type * Ty,Value * V)452 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
453 const SCEV *const *op_end,
454 PointerType *PTy,
455 Type *Ty,
456 Value *V) {
457 SmallVector<Value *, 4> GepIndices;
458 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
459 bool AnyNonZeroIndices = false;
460
461 // Split AddRecs up into parts as either of the parts may be usable
462 // without the other.
463 SplitAddRecs(Ops, Ty, SE);
464
465 Type *IntIdxTy = DL.getIndexType(PTy);
466
467 // For opaque pointers, always generate i8 GEP.
468 if (!PTy->isOpaque()) {
469 // Descend down the pointer's type and attempt to convert the other
470 // operands into GEP indices, at each level. The first index in a GEP
471 // indexes into the array implied by the pointer operand; the rest of
472 // the indices index into the element or field type selected by the
473 // preceding index.
474 Type *ElTy = PTy->getNonOpaquePointerElementType();
475 for (;;) {
476 // If the scale size is not 0, attempt to factor out a scale for
477 // array indexing.
478 SmallVector<const SCEV *, 8> ScaledOps;
479 if (ElTy->isSized()) {
480 const SCEV *ElSize = SE.getSizeOfExpr(IntIdxTy, ElTy);
481 if (!ElSize->isZero()) {
482 SmallVector<const SCEV *, 8> NewOps;
483 for (const SCEV *Op : Ops) {
484 const SCEV *Remainder = SE.getConstant(Ty, 0);
485 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
486 // Op now has ElSize factored out.
487 ScaledOps.push_back(Op);
488 if (!Remainder->isZero())
489 NewOps.push_back(Remainder);
490 AnyNonZeroIndices = true;
491 } else {
492 // The operand was not divisible, so add it to the list of
493 // operands we'll scan next iteration.
494 NewOps.push_back(Op);
495 }
496 }
497 // If we made any changes, update Ops.
498 if (!ScaledOps.empty()) {
499 Ops = NewOps;
500 SimplifyAddOperands(Ops, Ty, SE);
501 }
502 }
503 }
504
505 // Record the scaled array index for this level of the type. If
506 // we didn't find any operands that could be factored, tentatively
507 // assume that element zero was selected (since the zero offset
508 // would obviously be folded away).
509 Value *Scaled =
510 ScaledOps.empty()
511 ? Constant::getNullValue(Ty)
512 : expandCodeForImpl(SE.getAddExpr(ScaledOps), Ty, false);
513 GepIndices.push_back(Scaled);
514
515 // Collect struct field index operands.
516 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
517 bool FoundFieldNo = false;
518 // An empty struct has no fields.
519 if (STy->getNumElements() == 0) break;
520 // Field offsets are known. See if a constant offset falls within any of
521 // the struct fields.
522 if (Ops.empty())
523 break;
524 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
525 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
526 const StructLayout &SL = *DL.getStructLayout(STy);
527 uint64_t FullOffset = C->getValue()->getZExtValue();
528 if (FullOffset < SL.getSizeInBytes()) {
529 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
530 GepIndices.push_back(
531 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
532 ElTy = STy->getTypeAtIndex(ElIdx);
533 Ops[0] =
534 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
535 AnyNonZeroIndices = true;
536 FoundFieldNo = true;
537 }
538 }
539 // If no struct field offsets were found, tentatively assume that
540 // field zero was selected (since the zero offset would obviously
541 // be folded away).
542 if (!FoundFieldNo) {
543 ElTy = STy->getTypeAtIndex(0u);
544 GepIndices.push_back(
545 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
546 }
547 }
548
549 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
550 ElTy = ATy->getElementType();
551 else
552 // FIXME: Handle VectorType.
553 // E.g., If ElTy is scalable vector, then ElSize is not a compile-time
554 // constant, therefore can not be factored out. The generated IR is less
555 // ideal with base 'V' cast to i8* and do ugly getelementptr over that.
556 break;
557 }
558 }
559
560 // If none of the operands were convertible to proper GEP indices, cast
561 // the base to i8* and do an ugly getelementptr with that. It's still
562 // better than ptrtoint+arithmetic+inttoptr at least.
563 if (!AnyNonZeroIndices) {
564 // Cast the base to i8*.
565 if (!PTy->isOpaque())
566 V = InsertNoopCastOfTo(V,
567 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
568
569 assert(!isa<Instruction>(V) ||
570 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
571
572 // Expand the operands for a plain byte offset.
573 Value *Idx = expandCodeForImpl(SE.getAddExpr(Ops), Ty, false);
574
575 // Fold a GEP with constant operands.
576 if (Constant *CLHS = dyn_cast<Constant>(V))
577 if (Constant *CRHS = dyn_cast<Constant>(Idx))
578 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
579 CLHS, CRHS);
580
581 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
582 unsigned ScanLimit = 6;
583 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
584 // Scanning starts from the last instruction before the insertion point.
585 BasicBlock::iterator IP = Builder.GetInsertPoint();
586 if (IP != BlockBegin) {
587 --IP;
588 for (; ScanLimit; --IP, --ScanLimit) {
589 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
590 // generated code.
591 if (isa<DbgInfoIntrinsic>(IP))
592 ScanLimit++;
593 if (IP->getOpcode() == Instruction::GetElementPtr &&
594 IP->getOperand(0) == V && IP->getOperand(1) == Idx &&
595 cast<GEPOperator>(&*IP)->getSourceElementType() ==
596 Type::getInt8Ty(Ty->getContext()))
597 return &*IP;
598 if (IP == BlockBegin) break;
599 }
600 }
601
602 // Save the original insertion point so we can restore it when we're done.
603 SCEVInsertPointGuard Guard(Builder, this);
604
605 // Move the insertion point out of as many loops as we can.
606 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
607 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
608 BasicBlock *Preheader = L->getLoopPreheader();
609 if (!Preheader) break;
610
611 // Ok, move up a level.
612 Builder.SetInsertPoint(Preheader->getTerminator());
613 }
614
615 // Emit a GEP.
616 return Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
617 }
618
619 {
620 SCEVInsertPointGuard Guard(Builder, this);
621
622 // Move the insertion point out of as many loops as we can.
623 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
624 if (!L->isLoopInvariant(V)) break;
625
626 bool AnyIndexNotLoopInvariant = any_of(
627 GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
628
629 if (AnyIndexNotLoopInvariant)
630 break;
631
632 BasicBlock *Preheader = L->getLoopPreheader();
633 if (!Preheader) break;
634
635 // Ok, move up a level.
636 Builder.SetInsertPoint(Preheader->getTerminator());
637 }
638
639 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
640 // because ScalarEvolution may have changed the address arithmetic to
641 // compute a value which is beyond the end of the allocated object.
642 Value *Casted = V;
643 if (V->getType() != PTy)
644 Casted = InsertNoopCastOfTo(Casted, PTy);
645 Value *GEP = Builder.CreateGEP(PTy->getNonOpaquePointerElementType(),
646 Casted, GepIndices, "scevgep");
647 Ops.push_back(SE.getUnknown(GEP));
648 }
649
650 return expand(SE.getAddExpr(Ops));
651 }
652
expandAddToGEP(const SCEV * Op,PointerType * PTy,Type * Ty,Value * V)653 Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
654 Value *V) {
655 const SCEV *const Ops[1] = {Op};
656 return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
657 }
658
659 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
660 /// SCEV expansion. If they are nested, this is the most nested. If they are
661 /// neighboring, pick the later.
PickMostRelevantLoop(const Loop * A,const Loop * B,DominatorTree & DT)662 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
663 DominatorTree &DT) {
664 if (!A) return B;
665 if (!B) return A;
666 if (A->contains(B)) return B;
667 if (B->contains(A)) return A;
668 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
669 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
670 return A; // Arbitrarily break the tie.
671 }
672
673 /// getRelevantLoop - Get the most relevant loop associated with the given
674 /// expression, according to PickMostRelevantLoop.
getRelevantLoop(const SCEV * S)675 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
676 // Test whether we've already computed the most relevant loop for this SCEV.
677 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
678 if (!Pair.second)
679 return Pair.first->second;
680
681 if (isa<SCEVConstant>(S))
682 // A constant has no relevant loops.
683 return nullptr;
684 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
685 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
686 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
687 // A non-instruction has no relevant loops.
688 return nullptr;
689 }
690 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
691 const Loop *L = nullptr;
692 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
693 L = AR->getLoop();
694 for (const SCEV *Op : N->operands())
695 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
696 return RelevantLoops[N] = L;
697 }
698 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
699 const Loop *Result = getRelevantLoop(C->getOperand());
700 return RelevantLoops[C] = Result;
701 }
702 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
703 const Loop *Result = PickMostRelevantLoop(
704 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
705 return RelevantLoops[D] = Result;
706 }
707 llvm_unreachable("Unexpected SCEV type!");
708 }
709
710 namespace {
711
712 /// LoopCompare - Compare loops by PickMostRelevantLoop.
713 class LoopCompare {
714 DominatorTree &DT;
715 public:
LoopCompare(DominatorTree & dt)716 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
717
operator ()(std::pair<const Loop *,const SCEV * > LHS,std::pair<const Loop *,const SCEV * > RHS) const718 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
719 std::pair<const Loop *, const SCEV *> RHS) const {
720 // Keep pointer operands sorted at the end.
721 if (LHS.second->getType()->isPointerTy() !=
722 RHS.second->getType()->isPointerTy())
723 return LHS.second->getType()->isPointerTy();
724
725 // Compare loops with PickMostRelevantLoop.
726 if (LHS.first != RHS.first)
727 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
728
729 // If one operand is a non-constant negative and the other is not,
730 // put the non-constant negative on the right so that a sub can
731 // be used instead of a negate and add.
732 if (LHS.second->isNonConstantNegative()) {
733 if (!RHS.second->isNonConstantNegative())
734 return false;
735 } else if (RHS.second->isNonConstantNegative())
736 return true;
737
738 // Otherwise they are equivalent according to this comparison.
739 return false;
740 }
741 };
742
743 }
744
visitAddExpr(const SCEVAddExpr * S)745 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
746 Type *Ty = SE.getEffectiveSCEVType(S->getType());
747
748 // Collect all the add operands in a loop, along with their associated loops.
749 // Iterate in reverse so that constants are emitted last, all else equal, and
750 // so that pointer operands are inserted first, which the code below relies on
751 // to form more involved GEPs.
752 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
753 for (const SCEV *Op : reverse(S->operands()))
754 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
755
756 // Sort by loop. Use a stable sort so that constants follow non-constants and
757 // pointer operands precede non-pointer operands.
758 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
759
760 // Emit instructions to add all the operands. Hoist as much as possible
761 // out of loops, and form meaningful getelementptrs where possible.
762 Value *Sum = nullptr;
763 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
764 const Loop *CurLoop = I->first;
765 const SCEV *Op = I->second;
766 if (!Sum) {
767 // This is the first operand. Just expand it.
768 Sum = expand(Op);
769 ++I;
770 continue;
771 }
772
773 assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
774 if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
775 // The running sum expression is a pointer. Try to form a getelementptr
776 // at this level with that as the base.
777 SmallVector<const SCEV *, 4> NewOps;
778 for (; I != E && I->first == CurLoop; ++I) {
779 // If the operand is SCEVUnknown and not instructions, peek through
780 // it, to enable more of it to be folded into the GEP.
781 const SCEV *X = I->second;
782 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
783 if (!isa<Instruction>(U->getValue()))
784 X = SE.getSCEV(U->getValue());
785 NewOps.push_back(X);
786 }
787 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
788 } else if (Op->isNonConstantNegative()) {
789 // Instead of doing a negate and add, just do a subtract.
790 Value *W = expandCodeForImpl(SE.getNegativeSCEV(Op), Ty, false);
791 Sum = InsertNoopCastOfTo(Sum, Ty);
792 Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
793 /*IsSafeToHoist*/ true);
794 ++I;
795 } else {
796 // A simple add.
797 Value *W = expandCodeForImpl(Op, Ty, false);
798 Sum = InsertNoopCastOfTo(Sum, Ty);
799 // Canonicalize a constant to the RHS.
800 if (isa<Constant>(Sum)) std::swap(Sum, W);
801 Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
802 /*IsSafeToHoist*/ true);
803 ++I;
804 }
805 }
806
807 return Sum;
808 }
809
visitMulExpr(const SCEVMulExpr * S)810 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
811 Type *Ty = SE.getEffectiveSCEVType(S->getType());
812
813 // Collect all the mul operands in a loop, along with their associated loops.
814 // Iterate in reverse so that constants are emitted last, all else equal.
815 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
816 for (const SCEV *Op : reverse(S->operands()))
817 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
818
819 // Sort by loop. Use a stable sort so that constants follow non-constants.
820 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
821
822 // Emit instructions to mul all the operands. Hoist as much as possible
823 // out of loops.
824 Value *Prod = nullptr;
825 auto I = OpsAndLoops.begin();
826
827 // Expand the calculation of X pow N in the following manner:
828 // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
829 // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
830 const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
831 auto E = I;
832 // Calculate how many times the same operand from the same loop is included
833 // into this power.
834 uint64_t Exponent = 0;
835 const uint64_t MaxExponent = UINT64_MAX >> 1;
836 // No one sane will ever try to calculate such huge exponents, but if we
837 // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
838 // below when the power of 2 exceeds our Exponent, and we want it to be
839 // 1u << 31 at most to not deal with unsigned overflow.
840 while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
841 ++Exponent;
842 ++E;
843 }
844 assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
845
846 // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
847 // that are needed into the result.
848 Value *P = expandCodeForImpl(I->second, Ty, false);
849 Value *Result = nullptr;
850 if (Exponent & 1)
851 Result = P;
852 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
853 P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
854 /*IsSafeToHoist*/ true);
855 if (Exponent & BinExp)
856 Result = Result ? InsertBinop(Instruction::Mul, Result, P,
857 SCEV::FlagAnyWrap,
858 /*IsSafeToHoist*/ true)
859 : P;
860 }
861
862 I = E;
863 assert(Result && "Nothing was expanded?");
864 return Result;
865 };
866
867 while (I != OpsAndLoops.end()) {
868 if (!Prod) {
869 // This is the first operand. Just expand it.
870 Prod = ExpandOpBinPowN();
871 } else if (I->second->isAllOnesValue()) {
872 // Instead of doing a multiply by negative one, just do a negate.
873 Prod = InsertNoopCastOfTo(Prod, Ty);
874 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
875 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
876 ++I;
877 } else {
878 // A simple mul.
879 Value *W = ExpandOpBinPowN();
880 Prod = InsertNoopCastOfTo(Prod, Ty);
881 // Canonicalize a constant to the RHS.
882 if (isa<Constant>(Prod)) std::swap(Prod, W);
883 const APInt *RHS;
884 if (match(W, m_Power2(RHS))) {
885 // Canonicalize Prod*(1<<C) to Prod<<C.
886 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
887 auto NWFlags = S->getNoWrapFlags();
888 // clear nsw flag if shl will produce poison value.
889 if (RHS->logBase2() == RHS->getBitWidth() - 1)
890 NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
891 Prod = InsertBinop(Instruction::Shl, Prod,
892 ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
893 /*IsSafeToHoist*/ true);
894 } else {
895 Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
896 /*IsSafeToHoist*/ true);
897 }
898 }
899 }
900
901 return Prod;
902 }
903
visitUDivExpr(const SCEVUDivExpr * S)904 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
905 Type *Ty = SE.getEffectiveSCEVType(S->getType());
906
907 Value *LHS = expandCodeForImpl(S->getLHS(), Ty, false);
908 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
909 const APInt &RHS = SC->getAPInt();
910 if (RHS.isPowerOf2())
911 return InsertBinop(Instruction::LShr, LHS,
912 ConstantInt::get(Ty, RHS.logBase2()),
913 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
914 }
915
916 Value *RHS = expandCodeForImpl(S->getRHS(), Ty, false);
917 return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
918 /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
919 }
920
921 /// Determine if this is a well-behaved chain of instructions leading back to
922 /// the PHI. If so, it may be reused by expanded expressions.
isNormalAddRecExprPHI(PHINode * PN,Instruction * IncV,const Loop * L)923 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
924 const Loop *L) {
925 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
926 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
927 return false;
928 // If any of the operands don't dominate the insert position, bail.
929 // Addrec operands are always loop-invariant, so this can only happen
930 // if there are instructions which haven't been hoisted.
931 if (L == IVIncInsertLoop) {
932 for (Use &Op : llvm::drop_begin(IncV->operands()))
933 if (Instruction *OInst = dyn_cast<Instruction>(Op))
934 if (!SE.DT.dominates(OInst, IVIncInsertPos))
935 return false;
936 }
937 // Advance to the next instruction.
938 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
939 if (!IncV)
940 return false;
941
942 if (IncV->mayHaveSideEffects())
943 return false;
944
945 if (IncV == PN)
946 return true;
947
948 return isNormalAddRecExprPHI(PN, IncV, L);
949 }
950
951 /// getIVIncOperand returns an induction variable increment's induction
952 /// variable operand.
953 ///
954 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
955 /// operands dominate InsertPos.
956 ///
957 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
958 /// simple patterns generated by getAddRecExprPHILiterally and
959 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
getIVIncOperand(Instruction * IncV,Instruction * InsertPos,bool allowScale)960 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
961 Instruction *InsertPos,
962 bool allowScale) {
963 if (IncV == InsertPos)
964 return nullptr;
965
966 switch (IncV->getOpcode()) {
967 default:
968 return nullptr;
969 // Check for a simple Add/Sub or GEP of a loop invariant step.
970 case Instruction::Add:
971 case Instruction::Sub: {
972 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
973 if (!OInst || SE.DT.dominates(OInst, InsertPos))
974 return dyn_cast<Instruction>(IncV->getOperand(0));
975 return nullptr;
976 }
977 case Instruction::BitCast:
978 return dyn_cast<Instruction>(IncV->getOperand(0));
979 case Instruction::GetElementPtr:
980 for (Use &U : llvm::drop_begin(IncV->operands())) {
981 if (isa<Constant>(U))
982 continue;
983 if (Instruction *OInst = dyn_cast<Instruction>(U)) {
984 if (!SE.DT.dominates(OInst, InsertPos))
985 return nullptr;
986 }
987 if (allowScale) {
988 // allow any kind of GEP as long as it can be hoisted.
989 continue;
990 }
991 // This must be a pointer addition of constants (pretty), which is already
992 // handled, or some number of address-size elements (ugly). Ugly geps
993 // have 2 operands. i1* is used by the expander to represent an
994 // address-size element.
995 if (IncV->getNumOperands() != 2)
996 return nullptr;
997 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
998 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
999 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
1000 return nullptr;
1001 break;
1002 }
1003 return dyn_cast<Instruction>(IncV->getOperand(0));
1004 }
1005 }
1006
1007 /// If the insert point of the current builder or any of the builders on the
1008 /// stack of saved builders has 'I' as its insert point, update it to point to
1009 /// the instruction after 'I'. This is intended to be used when the instruction
1010 /// 'I' is being moved. If this fixup is not done and 'I' is moved to a
1011 /// different block, the inconsistent insert point (with a mismatched
1012 /// Instruction and Block) can lead to an instruction being inserted in a block
1013 /// other than its parent.
fixupInsertPoints(Instruction * I)1014 void SCEVExpander::fixupInsertPoints(Instruction *I) {
1015 BasicBlock::iterator It(*I);
1016 BasicBlock::iterator NewInsertPt = std::next(It);
1017 if (Builder.GetInsertPoint() == It)
1018 Builder.SetInsertPoint(&*NewInsertPt);
1019 for (auto *InsertPtGuard : InsertPointGuards)
1020 if (InsertPtGuard->GetInsertPoint() == It)
1021 InsertPtGuard->SetInsertPoint(NewInsertPt);
1022 }
1023
1024 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
1025 /// it available to other uses in this loop. Recursively hoist any operands,
1026 /// until we reach a value that dominates InsertPos.
hoistIVInc(Instruction * IncV,Instruction * InsertPos)1027 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
1028 if (SE.DT.dominates(IncV, InsertPos))
1029 return true;
1030
1031 // InsertPos must itself dominate IncV so that IncV's new position satisfies
1032 // its existing users.
1033 if (isa<PHINode>(InsertPos) ||
1034 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
1035 return false;
1036
1037 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
1038 return false;
1039
1040 // Check that the chain of IV operands leading back to Phi can be hoisted.
1041 SmallVector<Instruction*, 4> IVIncs;
1042 for(;;) {
1043 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
1044 if (!Oper)
1045 return false;
1046 // IncV is safe to hoist.
1047 IVIncs.push_back(IncV);
1048 IncV = Oper;
1049 if (SE.DT.dominates(IncV, InsertPos))
1050 break;
1051 }
1052 for (Instruction *I : llvm::reverse(IVIncs)) {
1053 fixupInsertPoints(I);
1054 I->moveBefore(InsertPos);
1055 }
1056 return true;
1057 }
1058
1059 /// Determine if this cyclic phi is in a form that would have been generated by
1060 /// LSR. We don't care if the phi was actually expanded in this pass, as long
1061 /// as it is in a low-cost form, for example, no implied multiplication. This
1062 /// should match any patterns generated by getAddRecExprPHILiterally and
1063 /// expandAddtoGEP.
isExpandedAddRecExprPHI(PHINode * PN,Instruction * IncV,const Loop * L)1064 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
1065 const Loop *L) {
1066 for(Instruction *IVOper = IncV;
1067 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
1068 /*allowScale=*/false));) {
1069 if (IVOper == PN)
1070 return true;
1071 }
1072 return false;
1073 }
1074
1075 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
1076 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
1077 /// need to materialize IV increments elsewhere to handle difficult situations.
expandIVInc(PHINode * PN,Value * StepV,const Loop * L,Type * ExpandTy,Type * IntTy,bool useSubtract)1078 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
1079 Type *ExpandTy, Type *IntTy,
1080 bool useSubtract) {
1081 Value *IncV;
1082 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
1083 if (ExpandTy->isPointerTy()) {
1084 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
1085 // If the step isn't constant, don't use an implicitly scaled GEP, because
1086 // that would require a multiply inside the loop.
1087 if (!isa<ConstantInt>(StepV))
1088 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1089 GEPPtrTy->getAddressSpace());
1090 IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
1091 if (IncV->getType() != PN->getType())
1092 IncV = Builder.CreateBitCast(IncV, PN->getType());
1093 } else {
1094 IncV = useSubtract ?
1095 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1096 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1097 }
1098 return IncV;
1099 }
1100
1101 /// Check whether we can cheaply express the requested SCEV in terms of
1102 /// the available PHI SCEV by truncation and/or inversion of the step.
canBeCheaplyTransformed(ScalarEvolution & SE,const SCEVAddRecExpr * Phi,const SCEVAddRecExpr * Requested,bool & InvertStep)1103 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1104 const SCEVAddRecExpr *Phi,
1105 const SCEVAddRecExpr *Requested,
1106 bool &InvertStep) {
1107 // We can't transform to match a pointer PHI.
1108 if (Phi->getType()->isPointerTy())
1109 return false;
1110
1111 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1112 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1113
1114 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1115 return false;
1116
1117 // Try truncate it if necessary.
1118 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1119 if (!Phi)
1120 return false;
1121
1122 // Check whether truncation will help.
1123 if (Phi == Requested) {
1124 InvertStep = false;
1125 return true;
1126 }
1127
1128 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1129 if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
1130 InvertStep = true;
1131 return true;
1132 }
1133
1134 return false;
1135 }
1136
IsIncrementNSW(ScalarEvolution & SE,const SCEVAddRecExpr * AR)1137 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1138 if (!isa<IntegerType>(AR->getType()))
1139 return false;
1140
1141 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1142 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1143 const SCEV *Step = AR->getStepRecurrence(SE);
1144 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1145 SE.getSignExtendExpr(AR, WideTy));
1146 const SCEV *ExtendAfterOp =
1147 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1148 return ExtendAfterOp == OpAfterExtend;
1149 }
1150
IsIncrementNUW(ScalarEvolution & SE,const SCEVAddRecExpr * AR)1151 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1152 if (!isa<IntegerType>(AR->getType()))
1153 return false;
1154
1155 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1156 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1157 const SCEV *Step = AR->getStepRecurrence(SE);
1158 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1159 SE.getZeroExtendExpr(AR, WideTy));
1160 const SCEV *ExtendAfterOp =
1161 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1162 return ExtendAfterOp == OpAfterExtend;
1163 }
1164
1165 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1166 /// the base addrec, which is the addrec without any non-loop-dominating
1167 /// values, and return the PHI.
1168 PHINode *
getAddRecExprPHILiterally(const SCEVAddRecExpr * Normalized,const Loop * L,Type * ExpandTy,Type * IntTy,Type * & TruncTy,bool & InvertStep)1169 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1170 const Loop *L,
1171 Type *ExpandTy,
1172 Type *IntTy,
1173 Type *&TruncTy,
1174 bool &InvertStep) {
1175 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1176
1177 // Reuse a previously-inserted PHI, if present.
1178 BasicBlock *LatchBlock = L->getLoopLatch();
1179 if (LatchBlock) {
1180 PHINode *AddRecPhiMatch = nullptr;
1181 Instruction *IncV = nullptr;
1182 TruncTy = nullptr;
1183 InvertStep = false;
1184
1185 // Only try partially matching scevs that need truncation and/or
1186 // step-inversion if we know this loop is outside the current loop.
1187 bool TryNonMatchingSCEV =
1188 IVIncInsertLoop &&
1189 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1190
1191 for (PHINode &PN : L->getHeader()->phis()) {
1192 if (!SE.isSCEVable(PN.getType()))
1193 continue;
1194
1195 // We should not look for a incomplete PHI. Getting SCEV for a incomplete
1196 // PHI has no meaning at all.
1197 if (!PN.isComplete()) {
1198 SCEV_DEBUG_WITH_TYPE(
1199 DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
1200 continue;
1201 }
1202
1203 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1204 if (!PhiSCEV)
1205 continue;
1206
1207 bool IsMatchingSCEV = PhiSCEV == Normalized;
1208 // We only handle truncation and inversion of phi recurrences for the
1209 // expanded expression if the expanded expression's loop dominates the
1210 // loop we insert to. Check now, so we can bail out early.
1211 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1212 continue;
1213
1214 // TODO: this possibly can be reworked to avoid this cast at all.
1215 Instruction *TempIncV =
1216 dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
1217 if (!TempIncV)
1218 continue;
1219
1220 // Check whether we can reuse this PHI node.
1221 if (LSRMode) {
1222 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1223 continue;
1224 } else {
1225 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1226 continue;
1227 }
1228
1229 // Stop if we have found an exact match SCEV.
1230 if (IsMatchingSCEV) {
1231 IncV = TempIncV;
1232 TruncTy = nullptr;
1233 InvertStep = false;
1234 AddRecPhiMatch = &PN;
1235 break;
1236 }
1237
1238 // Try whether the phi can be translated into the requested form
1239 // (truncated and/or offset by a constant).
1240 if ((!TruncTy || InvertStep) &&
1241 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1242 // Record the phi node. But don't stop we might find an exact match
1243 // later.
1244 AddRecPhiMatch = &PN;
1245 IncV = TempIncV;
1246 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1247 }
1248 }
1249
1250 if (AddRecPhiMatch) {
1251 // Ok, the add recurrence looks usable.
1252 // Remember this PHI, even in post-inc mode.
1253 InsertedValues.insert(AddRecPhiMatch);
1254 // Remember the increment.
1255 rememberInstruction(IncV);
1256 // Those values were not actually inserted but re-used.
1257 ReusedValues.insert(AddRecPhiMatch);
1258 ReusedValues.insert(IncV);
1259 return AddRecPhiMatch;
1260 }
1261 }
1262
1263 // Save the original insertion point so we can restore it when we're done.
1264 SCEVInsertPointGuard Guard(Builder, this);
1265
1266 // Another AddRec may need to be recursively expanded below. For example, if
1267 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1268 // loop. Remove this loop from the PostIncLoops set before expanding such
1269 // AddRecs. Otherwise, we cannot find a valid position for the step
1270 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1271 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1272 // so it's not worth implementing SmallPtrSet::swap.
1273 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1274 PostIncLoops.clear();
1275
1276 // Expand code for the start value into the loop preheader.
1277 assert(L->getLoopPreheader() &&
1278 "Can't expand add recurrences without a loop preheader!");
1279 Value *StartV =
1280 expandCodeForImpl(Normalized->getStart(), ExpandTy,
1281 L->getLoopPreheader()->getTerminator(), false);
1282
1283 // StartV must have been be inserted into L's preheader to dominate the new
1284 // phi.
1285 assert(!isa<Instruction>(StartV) ||
1286 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1287 L->getHeader()));
1288
1289 // Expand code for the step value. Do this before creating the PHI so that PHI
1290 // reuse code doesn't see an incomplete PHI.
1291 const SCEV *Step = Normalized->getStepRecurrence(SE);
1292 // If the stride is negative, insert a sub instead of an add for the increment
1293 // (unless it's a constant, because subtracts of constants are canonicalized
1294 // to adds).
1295 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1296 if (useSubtract)
1297 Step = SE.getNegativeSCEV(Step);
1298 // Expand the step somewhere that dominates the loop header.
1299 Value *StepV = expandCodeForImpl(
1300 Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
1301
1302 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1303 // we actually do emit an addition. It does not apply if we emit a
1304 // subtraction.
1305 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1306 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1307
1308 // Create the PHI.
1309 BasicBlock *Header = L->getHeader();
1310 Builder.SetInsertPoint(Header, Header->begin());
1311 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1312 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1313 Twine(IVName) + ".iv");
1314
1315 // Create the step instructions and populate the PHI.
1316 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1317 BasicBlock *Pred = *HPI;
1318
1319 // Add a start value.
1320 if (!L->contains(Pred)) {
1321 PN->addIncoming(StartV, Pred);
1322 continue;
1323 }
1324
1325 // Create a step value and add it to the PHI.
1326 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1327 // instructions at IVIncInsertPos.
1328 Instruction *InsertPos = L == IVIncInsertLoop ?
1329 IVIncInsertPos : Pred->getTerminator();
1330 Builder.SetInsertPoint(InsertPos);
1331 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1332
1333 if (isa<OverflowingBinaryOperator>(IncV)) {
1334 if (IncrementIsNUW)
1335 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1336 if (IncrementIsNSW)
1337 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1338 }
1339 PN->addIncoming(IncV, Pred);
1340 }
1341
1342 // After expanding subexpressions, restore the PostIncLoops set so the caller
1343 // can ensure that IVIncrement dominates the current uses.
1344 PostIncLoops = SavedPostIncLoops;
1345
1346 // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
1347 // effective when we are able to use an IV inserted here, so record it.
1348 InsertedValues.insert(PN);
1349 InsertedIVs.push_back(PN);
1350 return PN;
1351 }
1352
expandAddRecExprLiterally(const SCEVAddRecExpr * S)1353 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1354 Type *STy = S->getType();
1355 Type *IntTy = SE.getEffectiveSCEVType(STy);
1356 const Loop *L = S->getLoop();
1357
1358 // Determine a normalized form of this expression, which is the expression
1359 // before any post-inc adjustment is made.
1360 const SCEVAddRecExpr *Normalized = S;
1361 if (PostIncLoops.count(L)) {
1362 PostIncLoopSet Loops;
1363 Loops.insert(L);
1364 Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
1365 }
1366
1367 // Strip off any non-loop-dominating component from the addrec start.
1368 const SCEV *Start = Normalized->getStart();
1369 const SCEV *PostLoopOffset = nullptr;
1370 if (!SE.properlyDominates(Start, L->getHeader())) {
1371 PostLoopOffset = Start;
1372 Start = SE.getConstant(Normalized->getType(), 0);
1373 Normalized = cast<SCEVAddRecExpr>(
1374 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1375 Normalized->getLoop(),
1376 Normalized->getNoWrapFlags(SCEV::FlagNW)));
1377 }
1378
1379 // Strip off any non-loop-dominating component from the addrec step.
1380 const SCEV *Step = Normalized->getStepRecurrence(SE);
1381 const SCEV *PostLoopScale = nullptr;
1382 if (!SE.dominates(Step, L->getHeader())) {
1383 PostLoopScale = Step;
1384 Step = SE.getConstant(Normalized->getType(), 1);
1385 if (!Start->isZero()) {
1386 // The normalization below assumes that Start is constant zero, so if
1387 // it isn't re-associate Start to PostLoopOffset.
1388 assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
1389 PostLoopOffset = Start;
1390 Start = SE.getConstant(Normalized->getType(), 0);
1391 }
1392 Normalized =
1393 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1394 Start, Step, Normalized->getLoop(),
1395 Normalized->getNoWrapFlags(SCEV::FlagNW)));
1396 }
1397
1398 // Expand the core addrec. If we need post-loop scaling, force it to
1399 // expand to an integer type to avoid the need for additional casting.
1400 Type *ExpandTy = PostLoopScale ? IntTy : STy;
1401 // We can't use a pointer type for the addrec if the pointer type is
1402 // non-integral.
1403 Type *AddRecPHIExpandTy =
1404 DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
1405
1406 // In some cases, we decide to reuse an existing phi node but need to truncate
1407 // it and/or invert the step.
1408 Type *TruncTy = nullptr;
1409 bool InvertStep = false;
1410 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
1411 IntTy, TruncTy, InvertStep);
1412
1413 // Accommodate post-inc mode, if necessary.
1414 Value *Result;
1415 if (!PostIncLoops.count(L))
1416 Result = PN;
1417 else {
1418 // In PostInc mode, use the post-incremented value.
1419 BasicBlock *LatchBlock = L->getLoopLatch();
1420 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1421 Result = PN->getIncomingValueForBlock(LatchBlock);
1422
1423 // We might be introducing a new use of the post-inc IV that is not poison
1424 // safe, in which case we should drop poison generating flags. Only keep
1425 // those flags for which SCEV has proven that they always hold.
1426 if (isa<OverflowingBinaryOperator>(Result)) {
1427 auto *I = cast<Instruction>(Result);
1428 if (!S->hasNoUnsignedWrap())
1429 I->setHasNoUnsignedWrap(false);
1430 if (!S->hasNoSignedWrap())
1431 I->setHasNoSignedWrap(false);
1432 }
1433
1434 // For an expansion to use the postinc form, the client must call
1435 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1436 // or dominated by IVIncInsertPos.
1437 if (isa<Instruction>(Result) &&
1438 !SE.DT.dominates(cast<Instruction>(Result),
1439 &*Builder.GetInsertPoint())) {
1440 // The induction variable's postinc expansion does not dominate this use.
1441 // IVUsers tries to prevent this case, so it is rare. However, it can
1442 // happen when an IVUser outside the loop is not dominated by the latch
1443 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1444 // all cases. Consider a phi outside whose operand is replaced during
1445 // expansion with the value of the postinc user. Without fundamentally
1446 // changing the way postinc users are tracked, the only remedy is
1447 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1448 // but hopefully expandCodeFor handles that.
1449 bool useSubtract =
1450 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1451 if (useSubtract)
1452 Step = SE.getNegativeSCEV(Step);
1453 Value *StepV;
1454 {
1455 // Expand the step somewhere that dominates the loop header.
1456 SCEVInsertPointGuard Guard(Builder, this);
1457 StepV = expandCodeForImpl(
1458 Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
1459 }
1460 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1461 }
1462 }
1463
1464 // We have decided to reuse an induction variable of a dominating loop. Apply
1465 // truncation and/or inversion of the step.
1466 if (TruncTy) {
1467 Type *ResTy = Result->getType();
1468 // Normalize the result type.
1469 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1470 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1471 // Truncate the result.
1472 if (TruncTy != Result->getType())
1473 Result = Builder.CreateTrunc(Result, TruncTy);
1474
1475 // Invert the result.
1476 if (InvertStep)
1477 Result = Builder.CreateSub(
1478 expandCodeForImpl(Normalized->getStart(), TruncTy, false), Result);
1479 }
1480
1481 // Re-apply any non-loop-dominating scale.
1482 if (PostLoopScale) {
1483 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1484 Result = InsertNoopCastOfTo(Result, IntTy);
1485 Result = Builder.CreateMul(Result,
1486 expandCodeForImpl(PostLoopScale, IntTy, false));
1487 }
1488
1489 // Re-apply any non-loop-dominating offset.
1490 if (PostLoopOffset) {
1491 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1492 if (Result->getType()->isIntegerTy()) {
1493 Value *Base = expandCodeForImpl(PostLoopOffset, ExpandTy, false);
1494 Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
1495 } else {
1496 Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
1497 }
1498 } else {
1499 Result = InsertNoopCastOfTo(Result, IntTy);
1500 Result = Builder.CreateAdd(
1501 Result, expandCodeForImpl(PostLoopOffset, IntTy, false));
1502 }
1503 }
1504
1505 return Result;
1506 }
1507
visitAddRecExpr(const SCEVAddRecExpr * S)1508 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1509 // In canonical mode we compute the addrec as an expression of a canonical IV
1510 // using evaluateAtIteration and expand the resulting SCEV expression. This
1511 // way we avoid introducing new IVs to carry on the comutation of the addrec
1512 // throughout the loop.
1513 //
1514 // For nested addrecs evaluateAtIteration might need a canonical IV of a
1515 // type wider than the addrec itself. Emitting a canonical IV of the
1516 // proper type might produce non-legal types, for example expanding an i64
1517 // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
1518 // back to non-canonical mode for nested addrecs.
1519 if (!CanonicalMode || (S->getNumOperands() > 2))
1520 return expandAddRecExprLiterally(S);
1521
1522 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1523 const Loop *L = S->getLoop();
1524
1525 // First check for an existing canonical IV in a suitable type.
1526 PHINode *CanonicalIV = nullptr;
1527 if (PHINode *PN = L->getCanonicalInductionVariable())
1528 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1529 CanonicalIV = PN;
1530
1531 // Rewrite an AddRec in terms of the canonical induction variable, if
1532 // its type is more narrow.
1533 if (CanonicalIV &&
1534 SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
1535 !S->getType()->isPointerTy()) {
1536 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1537 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1538 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1539 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1540 S->getNoWrapFlags(SCEV::FlagNW)));
1541 BasicBlock::iterator NewInsertPt =
1542 findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
1543 V = expandCodeForImpl(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1544 &*NewInsertPt, false);
1545 return V;
1546 }
1547
1548 // {X,+,F} --> X + {0,+,F}
1549 if (!S->getStart()->isZero()) {
1550 if (PointerType *PTy = dyn_cast<PointerType>(S->getType())) {
1551 Value *StartV = expand(SE.getPointerBase(S));
1552 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1553 return expandAddToGEP(SE.removePointerBase(S), PTy, Ty, StartV);
1554 }
1555
1556 SmallVector<const SCEV *, 4> NewOps(S->operands());
1557 NewOps[0] = SE.getConstant(Ty, 0);
1558 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1559 S->getNoWrapFlags(SCEV::FlagNW));
1560
1561 // Just do a normal add. Pre-expand the operands to suppress folding.
1562 //
1563 // The LHS and RHS values are factored out of the expand call to make the
1564 // output independent of the argument evaluation order.
1565 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1566 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1567 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1568 }
1569
1570 // If we don't yet have a canonical IV, create one.
1571 if (!CanonicalIV) {
1572 // Create and insert the PHI node for the induction variable in the
1573 // specified loop.
1574 BasicBlock *Header = L->getHeader();
1575 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1576 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1577 &Header->front());
1578 rememberInstruction(CanonicalIV);
1579
1580 SmallSet<BasicBlock *, 4> PredSeen;
1581 Constant *One = ConstantInt::get(Ty, 1);
1582 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1583 BasicBlock *HP = *HPI;
1584 if (!PredSeen.insert(HP).second) {
1585 // There must be an incoming value for each predecessor, even the
1586 // duplicates!
1587 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1588 continue;
1589 }
1590
1591 if (L->contains(HP)) {
1592 // Insert a unit add instruction right before the terminator
1593 // corresponding to the back-edge.
1594 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1595 "indvar.next",
1596 HP->getTerminator());
1597 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1598 rememberInstruction(Add);
1599 CanonicalIV->addIncoming(Add, HP);
1600 } else {
1601 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1602 }
1603 }
1604 }
1605
1606 // {0,+,1} --> Insert a canonical induction variable into the loop!
1607 if (S->isAffine() && S->getOperand(1)->isOne()) {
1608 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1609 "IVs with types different from the canonical IV should "
1610 "already have been handled!");
1611 return CanonicalIV;
1612 }
1613
1614 // {0,+,F} --> {0,+,1} * F
1615
1616 // If this is a simple linear addrec, emit it now as a special case.
1617 if (S->isAffine()) // {0,+,F} --> i*F
1618 return
1619 expand(SE.getTruncateOrNoop(
1620 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1621 SE.getNoopOrAnyExtend(S->getOperand(1),
1622 CanonicalIV->getType())),
1623 Ty));
1624
1625 // If this is a chain of recurrences, turn it into a closed form, using the
1626 // folders, then expandCodeFor the closed form. This allows the folders to
1627 // simplify the expression without having to build a bunch of special code
1628 // into this folder.
1629 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1630
1631 // Promote S up to the canonical IV type, if the cast is foldable.
1632 const SCEV *NewS = S;
1633 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1634 if (isa<SCEVAddRecExpr>(Ext))
1635 NewS = Ext;
1636
1637 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1638
1639 // Truncate the result down to the original type, if needed.
1640 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1641 return expand(T);
1642 }
1643
visitPtrToIntExpr(const SCEVPtrToIntExpr * S)1644 Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
1645 Value *V =
1646 expandCodeForImpl(S->getOperand(), S->getOperand()->getType(), false);
1647 return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
1648 GetOptimalInsertionPointForCastOf(V));
1649 }
1650
visitTruncateExpr(const SCEVTruncateExpr * S)1651 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1652 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1653 Value *V = expandCodeForImpl(
1654 S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1655 false);
1656 return Builder.CreateTrunc(V, Ty);
1657 }
1658
visitZeroExtendExpr(const SCEVZeroExtendExpr * S)1659 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1660 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1661 Value *V = expandCodeForImpl(
1662 S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1663 false);
1664 return Builder.CreateZExt(V, Ty);
1665 }
1666
visitSignExtendExpr(const SCEVSignExtendExpr * S)1667 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1668 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1669 Value *V = expandCodeForImpl(
1670 S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
1671 false);
1672 return Builder.CreateSExt(V, Ty);
1673 }
1674
expandMinMaxExpr(const SCEVNAryExpr * S,Intrinsic::ID IntrinID,Twine Name,bool IsSequential)1675 Value *SCEVExpander::expandMinMaxExpr(const SCEVNAryExpr *S,
1676 Intrinsic::ID IntrinID, Twine Name,
1677 bool IsSequential) {
1678 Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1679 Type *Ty = LHS->getType();
1680 if (IsSequential)
1681 LHS = Builder.CreateFreeze(LHS);
1682 for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1683 Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
1684 if (IsSequential && i != 0)
1685 RHS = Builder.CreateFreeze(RHS);
1686 Value *Sel;
1687 if (Ty->isIntegerTy())
1688 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
1689 /*FMFSource=*/nullptr, Name);
1690 else {
1691 Value *ICmp =
1692 Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
1693 Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name);
1694 }
1695 LHS = Sel;
1696 }
1697 return LHS;
1698 }
1699
visitSMaxExpr(const SCEVSMaxExpr * S)1700 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1701 return expandMinMaxExpr(S, Intrinsic::smax, "smax");
1702 }
1703
visitUMaxExpr(const SCEVUMaxExpr * S)1704 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1705 return expandMinMaxExpr(S, Intrinsic::umax, "umax");
1706 }
1707
visitSMinExpr(const SCEVSMinExpr * S)1708 Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
1709 return expandMinMaxExpr(S, Intrinsic::smin, "smin");
1710 }
1711
visitUMinExpr(const SCEVUMinExpr * S)1712 Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
1713 return expandMinMaxExpr(S, Intrinsic::umin, "umin");
1714 }
1715
visitSequentialUMinExpr(const SCEVSequentialUMinExpr * S)1716 Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) {
1717 return expandMinMaxExpr(S, Intrinsic::umin, "umin", /*IsSequential*/true);
1718 }
1719
expandCodeForImpl(const SCEV * SH,Type * Ty,Instruction * IP,bool Root)1720 Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty,
1721 Instruction *IP, bool Root) {
1722 setInsertPoint(IP);
1723 Value *V = expandCodeForImpl(SH, Ty, Root);
1724 return V;
1725 }
1726
expandCodeForImpl(const SCEV * SH,Type * Ty,bool Root)1727 Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty, bool Root) {
1728 // Expand the code for this SCEV.
1729 Value *V = expand(SH);
1730
1731 if (PreserveLCSSA) {
1732 if (auto *Inst = dyn_cast<Instruction>(V)) {
1733 // Create a temporary instruction to at the current insertion point, so we
1734 // can hand it off to the helper to create LCSSA PHIs if required for the
1735 // new use.
1736 // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
1737 // would accept a insertion point and return an LCSSA phi for that
1738 // insertion point, so there is no need to insert & remove the temporary
1739 // instruction.
1740 Instruction *Tmp;
1741 if (Inst->getType()->isIntegerTy())
1742 Tmp = cast<Instruction>(Builder.CreateIntToPtr(
1743 Inst, Inst->getType()->getPointerTo(), "tmp.lcssa.user"));
1744 else {
1745 assert(Inst->getType()->isPointerTy());
1746 Tmp = cast<Instruction>(Builder.CreatePtrToInt(
1747 Inst, Type::getInt32Ty(Inst->getContext()), "tmp.lcssa.user"));
1748 }
1749 V = fixupLCSSAFormFor(Tmp, 0);
1750
1751 // Clean up temporary instruction.
1752 InsertedValues.erase(Tmp);
1753 InsertedPostIncValues.erase(Tmp);
1754 Tmp->eraseFromParent();
1755 }
1756 }
1757
1758 InsertedExpressions[std::make_pair(SH, &*Builder.GetInsertPoint())] = V;
1759 if (Ty) {
1760 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1761 "non-trivial casts should be done with the SCEVs directly!");
1762 V = InsertNoopCastOfTo(V, Ty);
1763 }
1764 return V;
1765 }
1766
FindValueInExprValueMap(const SCEV * S,const Instruction * InsertPt)1767 Value *SCEVExpander::FindValueInExprValueMap(const SCEV *S,
1768 const Instruction *InsertPt) {
1769 // If the expansion is not in CanonicalMode, and the SCEV contains any
1770 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1771 if (!CanonicalMode && SE.containsAddRecurrence(S))
1772 return nullptr;
1773
1774 // If S is a constant, it may be worse to reuse an existing Value.
1775 if (isa<SCEVConstant>(S))
1776 return nullptr;
1777
1778 // Choose a Value from the set which dominates the InsertPt.
1779 // InsertPt should be inside the Value's parent loop so as not to break
1780 // the LCSSA form.
1781 for (Value *V : SE.getSCEVValues(S)) {
1782 Instruction *EntInst = dyn_cast<Instruction>(V);
1783 if (!EntInst)
1784 continue;
1785
1786 assert(EntInst->getFunction() == InsertPt->getFunction());
1787 if (S->getType() == V->getType() &&
1788 SE.DT.dominates(EntInst, InsertPt) &&
1789 (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1790 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1791 return V;
1792 }
1793 return nullptr;
1794 }
1795
1796 // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1797 // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1798 // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1799 // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1800 // the expansion will try to reuse Value from ExprValueMap, and only when it
1801 // fails, expand the SCEV literally.
expand(const SCEV * S)1802 Value *SCEVExpander::expand(const SCEV *S) {
1803 // Compute an insertion point for this SCEV object. Hoist the instructions
1804 // as far out in the loop nest as possible.
1805 Instruction *InsertPt = &*Builder.GetInsertPoint();
1806
1807 // We can move insertion point only if there is no div or rem operations
1808 // otherwise we are risky to move it over the check for zero denominator.
1809 auto SafeToHoist = [](const SCEV *S) {
1810 return !SCEVExprContains(S, [](const SCEV *S) {
1811 if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1812 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1813 // Division by non-zero constants can be hoisted.
1814 return SC->getValue()->isZero();
1815 // All other divisions should not be moved as they may be
1816 // divisions by zero and should be kept within the
1817 // conditions of the surrounding loops that guard their
1818 // execution (see PR35406).
1819 return true;
1820 }
1821 return false;
1822 });
1823 };
1824 if (SafeToHoist(S)) {
1825 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1826 L = L->getParentLoop()) {
1827 if (SE.isLoopInvariant(S, L)) {
1828 if (!L) break;
1829 if (BasicBlock *Preheader = L->getLoopPreheader())
1830 InsertPt = Preheader->getTerminator();
1831 else
1832 // LSR sets the insertion point for AddRec start/step values to the
1833 // block start to simplify value reuse, even though it's an invalid
1834 // position. SCEVExpander must correct for this in all cases.
1835 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1836 } else {
1837 // If the SCEV is computable at this level, insert it into the header
1838 // after the PHIs (and after any other instructions that we've inserted
1839 // there) so that it is guaranteed to dominate any user inside the loop.
1840 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1841 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1842
1843 while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
1844 (isInsertedInstruction(InsertPt) ||
1845 isa<DbgInfoIntrinsic>(InsertPt))) {
1846 InsertPt = &*std::next(InsertPt->getIterator());
1847 }
1848 break;
1849 }
1850 }
1851 }
1852
1853 // Check to see if we already expanded this here.
1854 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1855 if (I != InsertedExpressions.end())
1856 return I->second;
1857
1858 SCEVInsertPointGuard Guard(Builder, this);
1859 Builder.SetInsertPoint(InsertPt);
1860
1861 // Expand the expression into instructions.
1862 Value *V = FindValueInExprValueMap(S, InsertPt);
1863 if (!V)
1864 V = visit(S);
1865 else {
1866 // If we're reusing an existing instruction, we are effectively CSEing two
1867 // copies of the instruction (with potentially different flags). As such,
1868 // we need to drop any poison generating flags unless we can prove that
1869 // said flags must be valid for all new users.
1870 if (auto *I = dyn_cast<Instruction>(V))
1871 if (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I))
1872 I->dropPoisonGeneratingFlags();
1873 }
1874 // Remember the expanded value for this SCEV at this location.
1875 //
1876 // This is independent of PostIncLoops. The mapped value simply materializes
1877 // the expression at this insertion point. If the mapped value happened to be
1878 // a postinc expansion, it could be reused by a non-postinc user, but only if
1879 // its insertion point was already at the head of the loop.
1880 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1881 return V;
1882 }
1883
rememberInstruction(Value * I)1884 void SCEVExpander::rememberInstruction(Value *I) {
1885 auto DoInsert = [this](Value *V) {
1886 if (!PostIncLoops.empty())
1887 InsertedPostIncValues.insert(V);
1888 else
1889 InsertedValues.insert(V);
1890 };
1891 DoInsert(I);
1892
1893 if (!PreserveLCSSA)
1894 return;
1895
1896 if (auto *Inst = dyn_cast<Instruction>(I)) {
1897 // A new instruction has been added, which might introduce new uses outside
1898 // a defining loop. Fix LCSSA from for each operand of the new instruction,
1899 // if required.
1900 for (unsigned OpIdx = 0, OpEnd = Inst->getNumOperands(); OpIdx != OpEnd;
1901 OpIdx++)
1902 fixupLCSSAFormFor(Inst, OpIdx);
1903 }
1904 }
1905
1906 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1907 /// replace them with their most canonical representative. Return the number of
1908 /// phis eliminated.
1909 ///
1910 /// This does not depend on any SCEVExpander state but should be used in
1911 /// the same context that SCEVExpander is used.
1912 unsigned
replaceCongruentIVs(Loop * L,const DominatorTree * DT,SmallVectorImpl<WeakTrackingVH> & DeadInsts,const TargetTransformInfo * TTI)1913 SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1914 SmallVectorImpl<WeakTrackingVH> &DeadInsts,
1915 const TargetTransformInfo *TTI) {
1916 // Find integer phis in order of increasing width.
1917 SmallVector<PHINode*, 8> Phis;
1918 for (PHINode &PN : L->getHeader()->phis())
1919 Phis.push_back(&PN);
1920
1921 if (TTI)
1922 // Use stable_sort to preserve order of equivalent PHIs, so the order
1923 // of the sorted Phis is the same from run to run on the same loop.
1924 llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
1925 // Put pointers at the back and make sure pointer < pointer = false.
1926 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1927 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1928 return RHS->getType()->getPrimitiveSizeInBits().getFixedSize() <
1929 LHS->getType()->getPrimitiveSizeInBits().getFixedSize();
1930 });
1931
1932 unsigned NumElim = 0;
1933 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1934 // Process phis from wide to narrow. Map wide phis to their truncation
1935 // so narrow phis can reuse them.
1936 for (PHINode *Phi : Phis) {
1937 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1938 if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1939 return V;
1940 if (!SE.isSCEVable(PN->getType()))
1941 return nullptr;
1942 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1943 if (!Const)
1944 return nullptr;
1945 return Const->getValue();
1946 };
1947
1948 // Fold constant phis. They may be congruent to other constant phis and
1949 // would confuse the logic below that expects proper IVs.
1950 if (Value *V = SimplifyPHINode(Phi)) {
1951 if (V->getType() != Phi->getType())
1952 continue;
1953 Phi->replaceAllUsesWith(V);
1954 DeadInsts.emplace_back(Phi);
1955 ++NumElim;
1956 SCEV_DEBUG_WITH_TYPE(DebugType,
1957 dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
1958 << '\n');
1959 continue;
1960 }
1961
1962 if (!SE.isSCEVable(Phi->getType()))
1963 continue;
1964
1965 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1966 if (!OrigPhiRef) {
1967 OrigPhiRef = Phi;
1968 if (Phi->getType()->isIntegerTy() && TTI &&
1969 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1970 // This phi can be freely truncated to the narrowest phi type. Map the
1971 // truncated expression to it so it will be reused for narrow types.
1972 const SCEV *TruncExpr =
1973 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1974 ExprToIVMap[TruncExpr] = Phi;
1975 }
1976 continue;
1977 }
1978
1979 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1980 // sense.
1981 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1982 continue;
1983
1984 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1985 Instruction *OrigInc = dyn_cast<Instruction>(
1986 OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1987 Instruction *IsomorphicInc =
1988 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1989
1990 if (OrigInc && IsomorphicInc) {
1991 // If this phi has the same width but is more canonical, replace the
1992 // original with it. As part of the "more canonical" determination,
1993 // respect a prior decision to use an IV chain.
1994 if (OrigPhiRef->getType() == Phi->getType() &&
1995 !(ChainedPhis.count(Phi) ||
1996 isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
1997 (ChainedPhis.count(Phi) ||
1998 isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1999 std::swap(OrigPhiRef, Phi);
2000 std::swap(OrigInc, IsomorphicInc);
2001 }
2002 // Replacing the congruent phi is sufficient because acyclic
2003 // redundancy elimination, CSE/GVN, should handle the
2004 // rest. However, once SCEV proves that a phi is congruent,
2005 // it's often the head of an IV user cycle that is isomorphic
2006 // with the original phi. It's worth eagerly cleaning up the
2007 // common case of a single IV increment so that DeleteDeadPHIs
2008 // can remove cycles that had postinc uses.
2009 const SCEV *TruncExpr =
2010 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
2011 if (OrigInc != IsomorphicInc &&
2012 TruncExpr == SE.getSCEV(IsomorphicInc) &&
2013 SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
2014 hoistIVInc(OrigInc, IsomorphicInc)) {
2015 SCEV_DEBUG_WITH_TYPE(
2016 DebugType, dbgs() << "INDVARS: Eliminated congruent iv.inc: "
2017 << *IsomorphicInc << '\n');
2018 Value *NewInc = OrigInc;
2019 if (OrigInc->getType() != IsomorphicInc->getType()) {
2020 Instruction *IP = nullptr;
2021 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
2022 IP = &*PN->getParent()->getFirstInsertionPt();
2023 else
2024 IP = OrigInc->getNextNode();
2025
2026 IRBuilder<> Builder(IP);
2027 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
2028 NewInc = Builder.CreateTruncOrBitCast(
2029 OrigInc, IsomorphicInc->getType(), IVName);
2030 }
2031 IsomorphicInc->replaceAllUsesWith(NewInc);
2032 DeadInsts.emplace_back(IsomorphicInc);
2033 }
2034 }
2035 }
2036 SCEV_DEBUG_WITH_TYPE(DebugType,
2037 dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
2038 << '\n');
2039 SCEV_DEBUG_WITH_TYPE(
2040 DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
2041 ++NumElim;
2042 Value *NewIV = OrigPhiRef;
2043 if (OrigPhiRef->getType() != Phi->getType()) {
2044 IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
2045 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
2046 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
2047 }
2048 Phi->replaceAllUsesWith(NewIV);
2049 DeadInsts.emplace_back(Phi);
2050 }
2051 return NumElim;
2052 }
2053
getRelatedExistingExpansion(const SCEV * S,const Instruction * At,Loop * L)2054 Value *SCEVExpander::getRelatedExistingExpansion(const SCEV *S,
2055 const Instruction *At,
2056 Loop *L) {
2057 using namespace llvm::PatternMatch;
2058
2059 SmallVector<BasicBlock *, 4> ExitingBlocks;
2060 L->getExitingBlocks(ExitingBlocks);
2061
2062 // Look for suitable value in simple conditions at the loop exits.
2063 for (BasicBlock *BB : ExitingBlocks) {
2064 ICmpInst::Predicate Pred;
2065 Instruction *LHS, *RHS;
2066
2067 if (!match(BB->getTerminator(),
2068 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
2069 m_BasicBlock(), m_BasicBlock())))
2070 continue;
2071
2072 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
2073 return LHS;
2074
2075 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
2076 return RHS;
2077 }
2078
2079 // Use expand's logic which is used for reusing a previous Value in
2080 // ExprValueMap. Note that we don't currently model the cost of
2081 // needing to drop poison generating flags on the instruction if we
2082 // want to reuse it. We effectively assume that has zero cost.
2083 return FindValueInExprValueMap(S, At);
2084 }
2085
costAndCollectOperands(const SCEVOperand & WorkItem,const TargetTransformInfo & TTI,TargetTransformInfo::TargetCostKind CostKind,SmallVectorImpl<SCEVOperand> & Worklist)2086 template<typename T> static InstructionCost costAndCollectOperands(
2087 const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
2088 TargetTransformInfo::TargetCostKind CostKind,
2089 SmallVectorImpl<SCEVOperand> &Worklist) {
2090
2091 const T *S = cast<T>(WorkItem.S);
2092 InstructionCost Cost = 0;
2093 // Object to help map SCEV operands to expanded IR instructions.
2094 struct OperationIndices {
2095 OperationIndices(unsigned Opc, size_t min, size_t max) :
2096 Opcode(Opc), MinIdx(min), MaxIdx(max) { }
2097 unsigned Opcode;
2098 size_t MinIdx;
2099 size_t MaxIdx;
2100 };
2101
2102 // Collect the operations of all the instructions that will be needed to
2103 // expand the SCEVExpr. This is so that when we come to cost the operands,
2104 // we know what the generated user(s) will be.
2105 SmallVector<OperationIndices, 2> Operations;
2106
2107 auto CastCost = [&](unsigned Opcode) -> InstructionCost {
2108 Operations.emplace_back(Opcode, 0, 0);
2109 return TTI.getCastInstrCost(Opcode, S->getType(),
2110 S->getOperand(0)->getType(),
2111 TTI::CastContextHint::None, CostKind);
2112 };
2113
2114 auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
2115 unsigned MinIdx = 0,
2116 unsigned MaxIdx = 1) -> InstructionCost {
2117 Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2118 return NumRequired *
2119 TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
2120 };
2121
2122 auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
2123 unsigned MaxIdx) -> InstructionCost {
2124 Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2125 Type *OpType = S->getOperand(0)->getType();
2126 return NumRequired * TTI.getCmpSelInstrCost(
2127 Opcode, OpType, CmpInst::makeCmpResultType(OpType),
2128 CmpInst::BAD_ICMP_PREDICATE, CostKind);
2129 };
2130
2131 switch (S->getSCEVType()) {
2132 case scCouldNotCompute:
2133 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2134 case scUnknown:
2135 case scConstant:
2136 return 0;
2137 case scPtrToInt:
2138 Cost = CastCost(Instruction::PtrToInt);
2139 break;
2140 case scTruncate:
2141 Cost = CastCost(Instruction::Trunc);
2142 break;
2143 case scZeroExtend:
2144 Cost = CastCost(Instruction::ZExt);
2145 break;
2146 case scSignExtend:
2147 Cost = CastCost(Instruction::SExt);
2148 break;
2149 case scUDivExpr: {
2150 unsigned Opcode = Instruction::UDiv;
2151 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
2152 if (SC->getAPInt().isPowerOf2())
2153 Opcode = Instruction::LShr;
2154 Cost = ArithCost(Opcode, 1);
2155 break;
2156 }
2157 case scAddExpr:
2158 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2159 break;
2160 case scMulExpr:
2161 // TODO: this is a very pessimistic cost modelling for Mul,
2162 // because of Bin Pow algorithm actually used by the expander,
2163 // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
2164 Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
2165 break;
2166 case scSMaxExpr:
2167 case scUMaxExpr:
2168 case scSMinExpr:
2169 case scUMinExpr:
2170 case scSequentialUMinExpr: {
2171 // FIXME: should this ask the cost for Intrinsic's?
2172 // The reduction tree.
2173 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
2174 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
2175 switch (S->getSCEVType()) {
2176 case scSequentialUMinExpr: {
2177 // The safety net against poison.
2178 // FIXME: this is broken.
2179 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
2180 Cost += ArithCost(Instruction::Or,
2181 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
2182 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
2183 break;
2184 }
2185 default:
2186 assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
2187 "Unhandled SCEV expression type?");
2188 break;
2189 }
2190 break;
2191 }
2192 case scAddRecExpr: {
2193 // In this polynominal, we may have some zero operands, and we shouldn't
2194 // really charge for those. So how many non-zero coeffients are there?
2195 int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) {
2196 return !Op->isZero();
2197 });
2198
2199 assert(NumTerms >= 1 && "Polynominal should have at least one term.");
2200 assert(!(*std::prev(S->operands().end()))->isZero() &&
2201 "Last operand should not be zero");
2202
2203 // Ignoring constant term (operand 0), how many of the coeffients are u> 1?
2204 int NumNonZeroDegreeNonOneTerms =
2205 llvm::count_if(S->operands(), [](const SCEV *Op) {
2206 auto *SConst = dyn_cast<SCEVConstant>(Op);
2207 return !SConst || SConst->getAPInt().ugt(1);
2208 });
2209
2210 // Much like with normal add expr, the polynominal will require
2211 // one less addition than the number of it's terms.
2212 InstructionCost AddCost = ArithCost(Instruction::Add, NumTerms - 1,
2213 /*MinIdx*/ 1, /*MaxIdx*/ 1);
2214 // Here, *each* one of those will require a multiplication.
2215 InstructionCost MulCost =
2216 ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
2217 Cost = AddCost + MulCost;
2218
2219 // What is the degree of this polynominal?
2220 int PolyDegree = S->getNumOperands() - 1;
2221 assert(PolyDegree >= 1 && "Should be at least affine.");
2222
2223 // The final term will be:
2224 // Op_{PolyDegree} * x ^ {PolyDegree}
2225 // Where x ^ {PolyDegree} will again require PolyDegree-1 mul operations.
2226 // Note that x ^ {PolyDegree} = x * x ^ {PolyDegree-1} so charging for
2227 // x ^ {PolyDegree} will give us x ^ {2} .. x ^ {PolyDegree-1} for free.
2228 // FIXME: this is conservatively correct, but might be overly pessimistic.
2229 Cost += MulCost * (PolyDegree - 1);
2230 break;
2231 }
2232 }
2233
2234 for (auto &CostOp : Operations) {
2235 for (auto SCEVOp : enumerate(S->operands())) {
2236 // Clamp the index to account for multiple IR operations being chained.
2237 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2238 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2239 Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
2240 }
2241 }
2242 return Cost;
2243 }
2244
isHighCostExpansionHelper(const SCEVOperand & WorkItem,Loop * L,const Instruction & At,InstructionCost & Cost,unsigned Budget,const TargetTransformInfo & TTI,SmallPtrSetImpl<const SCEV * > & Processed,SmallVectorImpl<SCEVOperand> & Worklist)2245 bool SCEVExpander::isHighCostExpansionHelper(
2246 const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
2247 InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
2248 SmallPtrSetImpl<const SCEV *> &Processed,
2249 SmallVectorImpl<SCEVOperand> &Worklist) {
2250 if (Cost > Budget)
2251 return true; // Already run out of budget, give up.
2252
2253 const SCEV *S = WorkItem.S;
2254 // Was the cost of expansion of this expression already accounted for?
2255 if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
2256 return false; // We have already accounted for this expression.
2257
2258 // If we can find an existing value for this scev available at the point "At"
2259 // then consider the expression cheap.
2260 if (getRelatedExistingExpansion(S, &At, L))
2261 return false; // Consider the expression to be free.
2262
2263 TargetTransformInfo::TargetCostKind CostKind =
2264 L->getHeader()->getParent()->hasMinSize()
2265 ? TargetTransformInfo::TCK_CodeSize
2266 : TargetTransformInfo::TCK_RecipThroughput;
2267
2268 switch (S->getSCEVType()) {
2269 case scCouldNotCompute:
2270 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2271 case scUnknown:
2272 // Assume to be zero-cost.
2273 return false;
2274 case scConstant: {
2275 // Only evalulate the costs of constants when optimizing for size.
2276 if (CostKind != TargetTransformInfo::TCK_CodeSize)
2277 return false;
2278 const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
2279 Type *Ty = S->getType();
2280 Cost += TTI.getIntImmCostInst(
2281 WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
2282 return Cost > Budget;
2283 }
2284 case scTruncate:
2285 case scPtrToInt:
2286 case scZeroExtend:
2287 case scSignExtend: {
2288 Cost +=
2289 costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
2290 return false; // Will answer upon next entry into this function.
2291 }
2292 case scUDivExpr: {
2293 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2294 // HowManyLessThans produced to compute a precise expression, rather than a
2295 // UDiv from the user's code. If we can't find a UDiv in the code with some
2296 // simple searching, we need to account for it's cost.
2297
2298 // At the beginning of this function we already tried to find existing
2299 // value for plain 'S'. Now try to lookup 'S + 1' since it is common
2300 // pattern involving division. This is just a simple search heuristic.
2301 if (getRelatedExistingExpansion(
2302 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
2303 return false; // Consider it to be free.
2304
2305 Cost +=
2306 costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
2307 return false; // Will answer upon next entry into this function.
2308 }
2309 case scAddExpr:
2310 case scMulExpr:
2311 case scUMaxExpr:
2312 case scSMaxExpr:
2313 case scUMinExpr:
2314 case scSMinExpr:
2315 case scSequentialUMinExpr: {
2316 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2317 "Nary expr should have more than 1 operand.");
2318 // The simple nary expr will require one less op (or pair of ops)
2319 // than the number of it's terms.
2320 Cost +=
2321 costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
2322 return Cost > Budget;
2323 }
2324 case scAddRecExpr: {
2325 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2326 "Polynomial should be at least linear");
2327 Cost += costAndCollectOperands<SCEVAddRecExpr>(
2328 WorkItem, TTI, CostKind, Worklist);
2329 return Cost > Budget;
2330 }
2331 }
2332 llvm_unreachable("Unknown SCEV kind!");
2333 }
2334
expandCodeForPredicate(const SCEVPredicate * Pred,Instruction * IP)2335 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
2336 Instruction *IP) {
2337 assert(IP);
2338 switch (Pred->getKind()) {
2339 case SCEVPredicate::P_Union:
2340 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
2341 case SCEVPredicate::P_Compare:
2342 return expandComparePredicate(cast<SCEVComparePredicate>(Pred), IP);
2343 case SCEVPredicate::P_Wrap: {
2344 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2345 return expandWrapPredicate(AddRecPred, IP);
2346 }
2347 }
2348 llvm_unreachable("Unknown SCEV predicate type");
2349 }
2350
expandComparePredicate(const SCEVComparePredicate * Pred,Instruction * IP)2351 Value *SCEVExpander::expandComparePredicate(const SCEVComparePredicate *Pred,
2352 Instruction *IP) {
2353 Value *Expr0 =
2354 expandCodeForImpl(Pred->getLHS(), Pred->getLHS()->getType(), IP, false);
2355 Value *Expr1 =
2356 expandCodeForImpl(Pred->getRHS(), Pred->getRHS()->getType(), IP, false);
2357
2358 Builder.SetInsertPoint(IP);
2359 auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
2360 auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
2361 return I;
2362 }
2363
generateOverflowCheck(const SCEVAddRecExpr * AR,Instruction * Loc,bool Signed)2364 Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
2365 Instruction *Loc, bool Signed) {
2366 assert(AR->isAffine() && "Cannot generate RT check for "
2367 "non-affine expression");
2368
2369 // FIXME: It is highly suspicious that we're ignoring the predicates here.
2370 SmallVector<const SCEVPredicate *, 4> Pred;
2371 const SCEV *ExitCount =
2372 SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
2373
2374 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
2375
2376 const SCEV *Step = AR->getStepRecurrence(SE);
2377 const SCEV *Start = AR->getStart();
2378
2379 Type *ARTy = AR->getType();
2380 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2381 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2382
2383 // The expression {Start,+,Step} has nusw/nssw if
2384 // Step < 0, Start - |Step| * Backedge <= Start
2385 // Step >= 0, Start + |Step| * Backedge > Start
2386 // and |Step| * Backedge doesn't unsigned overflow.
2387
2388 IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
2389 Builder.SetInsertPoint(Loc);
2390 Value *TripCountVal = expandCodeForImpl(ExitCount, CountTy, Loc, false);
2391
2392 IntegerType *Ty =
2393 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2394
2395 Value *StepValue = expandCodeForImpl(Step, Ty, Loc, false);
2396 Value *NegStepValue =
2397 expandCodeForImpl(SE.getNegativeSCEV(Step), Ty, Loc, false);
2398 Value *StartValue = expandCodeForImpl(Start, ARTy, Loc, false);
2399
2400 ConstantInt *Zero =
2401 ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
2402
2403 Builder.SetInsertPoint(Loc);
2404 // Compute |Step|
2405 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2406 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2407
2408 // Compute |Step| * Backedge
2409 // Compute:
2410 // 1. Start + |Step| * Backedge < Start
2411 // 2. Start - |Step| * Backedge > Start
2412 //
2413 // And select either 1. or 2. depending on whether step is positive or
2414 // negative. If Step is known to be positive or negative, only create
2415 // either 1. or 2.
2416 auto ComputeEndCheck = [&]() -> Value * {
2417 // Checking <u 0 is always false.
2418 if (!Signed && Start->isZero() && SE.isKnownPositive(Step))
2419 return ConstantInt::getFalse(Loc->getContext());
2420
2421 // Get the backedge taken count and truncate or extended to the AR type.
2422 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2423
2424 Value *MulV, *OfMul;
2425 if (Step->isOne()) {
2426 // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't
2427 // needed, there is never an overflow, so to avoid artificially inflating
2428 // the cost of the check, directly emit the optimized IR.
2429 MulV = TruncTripCount;
2430 OfMul = ConstantInt::getFalse(MulV->getContext());
2431 } else {
2432 auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
2433 Intrinsic::umul_with_overflow, Ty);
2434 CallInst *Mul =
2435 Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
2436 MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2437 OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2438 }
2439
2440 Value *Add = nullptr, *Sub = nullptr;
2441 bool NeedPosCheck = !SE.isKnownNegative(Step);
2442 bool NeedNegCheck = !SE.isKnownPositive(Step);
2443
2444 if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARTy)) {
2445 StartValue = InsertNoopCastOfTo(
2446 StartValue, Builder.getInt8PtrTy(ARPtrTy->getAddressSpace()));
2447 Value *NegMulV = Builder.CreateNeg(MulV);
2448 if (NeedPosCheck)
2449 Add = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, MulV);
2450 if (NeedNegCheck)
2451 Sub = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, NegMulV);
2452 } else {
2453 if (NeedPosCheck)
2454 Add = Builder.CreateAdd(StartValue, MulV);
2455 if (NeedNegCheck)
2456 Sub = Builder.CreateSub(StartValue, MulV);
2457 }
2458
2459 Value *EndCompareLT = nullptr;
2460 Value *EndCompareGT = nullptr;
2461 Value *EndCheck = nullptr;
2462 if (NeedPosCheck)
2463 EndCheck = EndCompareLT = Builder.CreateICmp(
2464 Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
2465 if (NeedNegCheck)
2466 EndCheck = EndCompareGT = Builder.CreateICmp(
2467 Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
2468 if (NeedPosCheck && NeedNegCheck) {
2469 // Select the answer based on the sign of Step.
2470 EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2471 }
2472 return Builder.CreateOr(EndCheck, OfMul);
2473 };
2474 Value *EndCheck = ComputeEndCheck();
2475
2476 // If the backedge taken count type is larger than the AR type,
2477 // check that we don't drop any bits by truncating it. If we are
2478 // dropping bits, then we have overflow (unless the step is zero).
2479 if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
2480 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2481 auto *BackedgeCheck =
2482 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2483 ConstantInt::get(Loc->getContext(), MaxVal));
2484 BackedgeCheck = Builder.CreateAnd(
2485 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2486
2487 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2488 }
2489
2490 return EndCheck;
2491 }
2492
expandWrapPredicate(const SCEVWrapPredicate * Pred,Instruction * IP)2493 Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
2494 Instruction *IP) {
2495 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2496 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2497
2498 // Add a check for NUSW
2499 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2500 NUSWCheck = generateOverflowCheck(A, IP, false);
2501
2502 // Add a check for NSSW
2503 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2504 NSSWCheck = generateOverflowCheck(A, IP, true);
2505
2506 if (NUSWCheck && NSSWCheck)
2507 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2508
2509 if (NUSWCheck)
2510 return NUSWCheck;
2511
2512 if (NSSWCheck)
2513 return NSSWCheck;
2514
2515 return ConstantInt::getFalse(IP->getContext());
2516 }
2517
expandUnionPredicate(const SCEVUnionPredicate * Union,Instruction * IP)2518 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
2519 Instruction *IP) {
2520 // Loop over all checks in this set.
2521 SmallVector<Value *> Checks;
2522 for (auto Pred : Union->getPredicates()) {
2523 Checks.push_back(expandCodeForPredicate(Pred, IP));
2524 Builder.SetInsertPoint(IP);
2525 }
2526
2527 if (Checks.empty())
2528 return ConstantInt::getFalse(IP->getContext());
2529 return Builder.CreateOr(Checks);
2530 }
2531
fixupLCSSAFormFor(Instruction * User,unsigned OpIdx)2532 Value *SCEVExpander::fixupLCSSAFormFor(Instruction *User, unsigned OpIdx) {
2533 assert(PreserveLCSSA);
2534 SmallVector<Instruction *, 1> ToUpdate;
2535
2536 auto *OpV = User->getOperand(OpIdx);
2537 auto *OpI = dyn_cast<Instruction>(OpV);
2538 if (!OpI)
2539 return OpV;
2540
2541 Loop *DefLoop = SE.LI.getLoopFor(OpI->getParent());
2542 Loop *UseLoop = SE.LI.getLoopFor(User->getParent());
2543 if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2544 return OpV;
2545
2546 ToUpdate.push_back(OpI);
2547 SmallVector<PHINode *, 16> PHIsToRemove;
2548 formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, Builder, &PHIsToRemove);
2549 for (PHINode *PN : PHIsToRemove) {
2550 if (!PN->use_empty())
2551 continue;
2552 InsertedValues.erase(PN);
2553 InsertedPostIncValues.erase(PN);
2554 PN->eraseFromParent();
2555 }
2556
2557 return User->getOperand(OpIdx);
2558 }
2559
2560 namespace {
2561 // Search for a SCEV subexpression that is not safe to expand. Any expression
2562 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2563 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
2564 // instruction, but the important thing is that we prove the denominator is
2565 // nonzero before expansion.
2566 //
2567 // IVUsers already checks that IV-derived expressions are safe. So this check is
2568 // only needed when the expression includes some subexpression that is not IV
2569 // derived.
2570 //
2571 // Currently, we only allow division by a value provably non-zero here.
2572 //
2573 // We cannot generally expand recurrences unless the step dominates the loop
2574 // header. The expander handles the special case of affine recurrences by
2575 // scaling the recurrence outside the loop, but this technique isn't generally
2576 // applicable. Expanding a nested recurrence outside a loop requires computing
2577 // binomial coefficients. This could be done, but the recurrence has to be in a
2578 // perfectly reduced form, which can't be guaranteed.
2579 struct SCEVFindUnsafe {
2580 ScalarEvolution &SE;
2581 bool CanonicalMode;
2582 bool IsUnsafe = false;
2583
SCEVFindUnsafe__anon307280901011::SCEVFindUnsafe2584 SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
2585 : SE(SE), CanonicalMode(CanonicalMode) {}
2586
follow__anon307280901011::SCEVFindUnsafe2587 bool follow(const SCEV *S) {
2588 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2589 if (!SE.isKnownNonZero(D->getRHS())) {
2590 IsUnsafe = true;
2591 return false;
2592 }
2593 }
2594 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2595 const SCEV *Step = AR->getStepRecurrence(SE);
2596 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2597 IsUnsafe = true;
2598 return false;
2599 }
2600
2601 // For non-affine addrecs or in non-canonical mode we need a preheader
2602 // to insert into.
2603 if (!AR->getLoop()->getLoopPreheader() &&
2604 (!CanonicalMode || !AR->isAffine())) {
2605 IsUnsafe = true;
2606 return false;
2607 }
2608 }
2609 return true;
2610 }
isDone__anon307280901011::SCEVFindUnsafe2611 bool isDone() const { return IsUnsafe; }
2612 };
2613 } // namespace
2614
isSafeToExpand(const SCEV * S) const2615 bool SCEVExpander::isSafeToExpand(const SCEV *S) const {
2616 SCEVFindUnsafe Search(SE, CanonicalMode);
2617 visitAll(S, Search);
2618 return !Search.IsUnsafe;
2619 }
2620
isSafeToExpandAt(const SCEV * S,const Instruction * InsertionPoint) const2621 bool SCEVExpander::isSafeToExpandAt(const SCEV *S,
2622 const Instruction *InsertionPoint) const {
2623 if (!isSafeToExpand(S))
2624 return false;
2625 // We have to prove that the expanded site of S dominates InsertionPoint.
2626 // This is easy when not in the same block, but hard when S is an instruction
2627 // to be expanded somewhere inside the same block as our insertion point.
2628 // What we really need here is something analogous to an OrderedBasicBlock,
2629 // but for the moment, we paper over the problem by handling two common and
2630 // cheap to check cases.
2631 if (SE.properlyDominates(S, InsertionPoint->getParent()))
2632 return true;
2633 if (SE.dominates(S, InsertionPoint->getParent())) {
2634 if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2635 return true;
2636 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2637 if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
2638 return true;
2639 }
2640 return false;
2641 }
2642
cleanup()2643 void SCEVExpanderCleaner::cleanup() {
2644 // Result is used, nothing to remove.
2645 if (ResultUsed)
2646 return;
2647
2648 auto InsertedInstructions = Expander.getAllInsertedInstructions();
2649 #ifndef NDEBUG
2650 SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
2651 InsertedInstructions.end());
2652 (void)InsertedSet;
2653 #endif
2654 // Remove sets with value handles.
2655 Expander.clear();
2656
2657 // Remove all inserted instructions.
2658 for (Instruction *I : reverse(InsertedInstructions)) {
2659 #ifndef NDEBUG
2660 assert(all_of(I->users(),
2661 [&InsertedSet](Value *U) {
2662 return InsertedSet.contains(cast<Instruction>(U));
2663 }) &&
2664 "removed instruction should only be used by instructions inserted "
2665 "during expansion");
2666 #endif
2667 assert(!I->getType()->isVoidTy() &&
2668 "inserted instruction should have non-void types");
2669 I->replaceAllUsesWith(UndefValue::get(I->getType()));
2670 I->eraseFromParent();
2671 }
2672 }
2673