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