LLVM 24.0.0git
ScalarEvolutionExpander.cpp
Go to the documentation of this file.
1//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the implementation of the scalar evolution expander,
10// which is used to generate the code corresponding to a given scalar evolution
11// expression.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Dominators.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
41 "scev-cheap-expansion-budget", cl::Hidden, cl::init(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
49 NUW = false;
50 NSW = false;
51 Exact = false;
52 Disjoint = false;
53 NNeg = false;
54 SameSign = false;
56 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I)) {
57 NUW = OBO->hasNoUnsignedWrap();
58 NSW = OBO->hasNoSignedWrap();
59 }
60 if (auto *PEO = dyn_cast<PossiblyExactOperator>(I))
61 Exact = PEO->isExact();
62 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
63 Disjoint = PDI->isDisjoint();
64 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
65 NNeg = PNI->hasNonNeg();
66 if (auto *TI = dyn_cast<TruncInst>(I)) {
67 NUW = TI->hasNoUnsignedWrap();
68 NSW = TI->hasNoSignedWrap();
69 }
71 GEPNW = GEP->getNoWrapFlags();
72 if (auto *ICmp = dyn_cast<ICmpInst>(I))
73 SameSign = ICmp->hasSameSign();
74}
75
78 I->setHasNoUnsignedWrap(NUW);
79 I->setHasNoSignedWrap(NSW);
80 }
82 I->setIsExact(Exact);
83 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(I))
84 PDI->setIsDisjoint(Disjoint);
85 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(I))
86 PNI->setNonNeg(NNeg);
87 if (isa<TruncInst>(I)) {
88 I->setHasNoUnsignedWrap(NUW);
89 I->setHasNoSignedWrap(NSW);
90 }
92 GEP->setNoWrapFlags(GEPNW);
93 if (auto *ICmp = dyn_cast<ICmpInst>(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,
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>(V)) {
117 // Check to see if there is already a cast!
118 for (User *U : V->users()) {
119 if (U->getType() != Ty)
120 continue;
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(&*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, Ty, 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
154 Instruction *MustDominate) const {
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(&*IP) && &*IP != MustDominate)
168 ++IP;
169
170 return IP;
171}
172
174 SmallVector<Value *> WorkList;
175 SmallPtrSet<Value *, 8> DeletedValues;
177 while (!WorkList.empty()) {
178 Value *V = WorkList.pop_back_val();
179 if (DeletedValues.contains(V))
180 continue;
181 auto *I = dyn_cast<Instruction>(V);
182 if (!I || I == Root || !isInsertedInstruction(I) ||
184 continue;
185 append_range(WorkList, I->operands());
186 InsertedValues.erase(I);
187 InsertedPostIncValues.erase(I);
188 DeletedValues.insert(I);
189 I->eraseFromParent();
190 }
191}
192
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>(V)) {
198 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
199 while ((isa<BitCastInst>(IP) &&
200 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
201 cast<BitCastInst>(IP)->getOperand(0) != A))
202 ++IP;
203 return IP;
204 }
205
206 // Cast the instruction immediately after the instruction.
208 return findInsertPointAfter(I, &*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.
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(V, false, Ty, 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>(Ty);
239 if (DL.isNonIntegralPointerType(PtrTy))
240 return Builder.CreatePtrAdd(Constant::getNullValue(PtrTy), V, "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>(V)) {
247 if (CI->getOperand(0)->getType() == Ty)
248 return CI->getOperand(0);
249 }
250 }
251 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
252 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
253 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
254 if (CastInst *CI = dyn_cast<CastInst>(V))
255 if ((CI->getOpcode() == Instruction::PtrToInt ||
256 CI->getOpcode() == Instruction::IntToPtr) &&
257 SE.getTypeSizeInBits(CI->getType()) ==
258 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
259 return CI->getOperand(0);
260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
261 if ((CE->getOpcode() == Instruction::PtrToInt ||
262 CE->getOpcode() == Instruction::IntToPtr) &&
263 SE.getTypeSizeInBits(CE->getType()) ==
264 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
265 return CE->getOperand(0);
266 }
267
268 // Fold a cast of a constant.
269 if (Constant *C = dyn_cast<Constant>(V))
270 return ConstantExpr::getCast(Op, C, Ty);
271
272 // Try to reuse existing cast, or insert one.
273 return ReuseOrCreateCast(V, Ty, Op, 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>(LHS))
284 if (Constant *CRHS = dyn_cast<Constant>(RHS))
285 if (Constant *Res = ConstantFoldBinaryOpOperands(Opcode, CLHS, 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.
299 if (I->hasNoSignedWrap() != any(Flags & SCEV::FlagNSW))
300 return true;
301 if (I->hasNoUnsignedWrap() != any(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>(I) && I->isExact())
307 return true;
308 return false;
309 };
310 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
311 IP->getOperand(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(Builder.GetInsertBlock())) {
324 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(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(Flags & SCEV::FlagNUW);
336 bool IsNSW = any(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(PostIncLoops, [&](const Loop *L) {
341 return !L->contains(Builder.GetInsertBlock());
342 })) {
343 auto *BO = BinaryOperator::Create(Opcode, LHS, RHS);
344 if (IsNUW)
345 BO->setHasNoUnsignedWrap();
346 if (IsNSW)
347 BO->setHasNoSignedWrap();
348 return Builder.Insert(BO);
349 }
350 return Builder.CreateNoWrapBinOp(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) {
383 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
384
385 Value *Idx = expand(Offset);
386 GEPNoWrapFlags NW = any(Flags & SCEV::FlagNUW)
388 : GEPNoWrapFlags::none();
389
390 // Fold a GEP with constant operands.
391 if (Constant *CLHS = dyn_cast<Constant>(V))
392 if (Constant *CRHS = dyn_cast<Constant>(Idx))
393 return Builder.CreatePtrAdd(CLHS, CRHS, "", 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>(IP)) {
404 if (GEP->getPointerOperand() == V &&
405 GEP->getSourceElementType() == Builder.getInt8Ty() &&
406 GEP->getOperand(1) == Idx) {
407 rememberFlags(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(Builder.GetInsertBlock())) {
421 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(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(V, Idx, "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(B)) return B;
441 if (B->contains(A)) return A;
442 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
443 if (DT.dominates(B->getHeader(), 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(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:
472 const Loop *L = nullptr;
473 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
474 L = AR->getLoop();
475 for (const SCEV *Op : S->operands())
476 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
477 return RelevantLoops[S] = L;
478 }
479 case scUnknown: {
480 const SCEVUnknown *U = cast<SCEVUnknown>(S);
481 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
482 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
483 // A non-instruction has no relevant loops.
484 return nullptr;
485 }
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(LHS.first, 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(S, m_scev_URem(m_SCEV(URemLHS), m_SCEV(URemRHS), SE))) {
532 Value *LHS = expand(URemLHS);
533 Value *RHS = expand(URemRHS);
534 return InsertBinop(Instruction::URem, LHS, RHS, SCEV::FlagAnyWrap,
535 /*IsSafeToHoist*/ false);
536 }
537
538 // Collect all the add operands in a loop, along with their associated loops.
539 // Iterate in reverse so that constants are emitted last, all else equal, and
540 // so that pointer operands are inserted first, which the code below relies on
541 // to form more involved GEPs.
543 for (const SCEV *Op : reverse(S->operands()))
544 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
545
546 // Sort by loop. Use a stable sort so that constants follow non-constants and
547 // pointer operands precede non-pointer operands.
548 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
549
550 // Emit instructions to add all the operands. Hoist as much as possible
551 // out of loops, and form meaningful getelementptrs where possible.
552 Value *Sum = nullptr;
553 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
554 const Loop *CurLoop = I->first;
555 const SCEV *Op = I->second;
556 if (!Sum) {
557 // This is the first operand. Just expand it.
558 Sum = expand(Op);
559 ++I;
560 continue;
561 }
562
563 assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
564 if (isa<PointerType>(Sum->getType())) {
565 // The running sum expression is a pointer. Try to form a getelementptr
566 // at this level with that as the base.
568 for (; I != E && I->first == CurLoop; ++I) {
569 // If the operand is SCEVUnknown and not instructions, peek through
570 // it, to enable more of it to be folded into the GEP.
571 const SCEV *X = I->second;
572 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
573 if (!isa<Instruction>(U->getValue()))
574 X = SE.getSCEV(U->getValue());
575 NewOps.push_back(X);
576 }
577 Sum = expandAddToGEP(SE.getAddExpr(NewOps), Sum, S.getNoWrapFlags());
578 } else if (Op->isNonConstantNegative()) {
579 // Instead of doing a negate and add, just do a subtract.
580 Value *W = expand(SE.getNegativeSCEV(Op));
581 Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
582 /*IsSafeToHoist*/ true);
583 ++I;
584 } else {
585 // A simple add.
586 Value *W = expand(Op);
587 // Canonicalize a constant to the RHS.
588 if (isa<Constant>(Sum))
589 std::swap(Sum, W);
590 Sum = InsertBinop(Instruction::Add, Sum, W, S.getNoWrapFlags(),
591 /*IsSafeToHoist*/ true);
592 ++I;
593 }
594 }
595
596 return Sum;
597}
598
599Value *SCEVExpander::visitMulExpr(SCEVUseT<const SCEVMulExpr *> S) {
600 Type *Ty = S->getType();
601
602 const SCEVConstant *C1, *C2;
603 const SCEV *Val;
604 // mul(PowerOf2C, (udiv X, PowerOf2C)) == (X >> C) << C
605 // -> X & (-1 << C)
607 m_scev_UDiv(m_SCEV(Val), m_SCEVConstant(C2)))) &&
608 C1 == C2 && C1->getAPInt().isPowerOf2()) {
609 Value *LHS = expand(Val);
610 unsigned ShAmtC = C1->getAPInt().logBase2();
611 unsigned BitWidth = Ty->getScalarSizeInBits();
612 APInt Mask(APInt::getBitsSetFrom(BitWidth, ShAmtC));
613 Value *Res = InsertBinop(Instruction::And, LHS, ConstantInt::get(Ty, Mask),
614 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
615 return Res;
616 }
617
618 // Collect all the mul operands in a loop, along with their associated loops.
619 // Iterate in reverse so that constants are emitted last, all else equal.
621 for (const SCEV *Op : reverse(S->operands()))
622 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
623
624 // Sort by loop. Use a stable sort so that constants follow non-constants.
625 llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
626
627 // Emit instructions to mul all the operands. Hoist as much as possible
628 // out of loops.
629 Value *Prod = nullptr;
630 auto I = OpsAndLoops.begin();
631
632 // Expand the calculation of X pow N in the following manner:
633 // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
634 // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
635 const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops]() {
636 auto E = I;
637 // Calculate how many times the same operand from the same loop is included
638 // into this power.
639 uint64_t Exponent = 0;
640 const uint64_t MaxExponent = UINT64_MAX >> 1;
641 // No one sane will ever try to calculate such huge exponents, but if we
642 // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
643 // below when the power of 2 exceeds our Exponent, and we want it to be
644 // 1u << 31 at most to not deal with unsigned overflow.
645 while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
646 ++Exponent;
647 ++E;
648 }
649 assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
650
651 // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
652 // that are needed into the result.
653 Value *P = expand(I->second);
654 Value *Result = nullptr;
655 if (Exponent & 1)
656 Result = P;
657 for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
658 P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
659 /*IsSafeToHoist*/ true);
660 if (Exponent & BinExp)
661 Result = Result ? InsertBinop(Instruction::Mul, Result, P,
663 /*IsSafeToHoist*/ true)
664 : P;
665 }
666
667 I = E;
668 assert(Result && "Nothing was expanded?");
669 return Result;
670 };
671
672 while (I != OpsAndLoops.end()) {
673 if (!Prod) {
674 // This is the first operand. Just expand it.
675 Prod = ExpandOpBinPowN();
676 } else if (I->second->isAllOnesValue()) {
677 // Instead of doing a multiply by negative one, just do a negate.
678 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
679 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
680 ++I;
681 } else {
682 // A simple mul.
683 Value *W = ExpandOpBinPowN();
684 // Canonicalize a constant to the RHS.
685 if (isa<Constant>(Prod)) std::swap(Prod, W);
686 const APInt *RHS;
687 if (match(W, m_Power2(RHS))) {
688 // Canonicalize Prod*(1<<C) to Prod<<C.
689 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
690 auto NWFlags = S.getNoWrapFlags();
691 // clear nsw flag if shl will produce poison value.
692 if (RHS->logBase2() == RHS->getBitWidth() - 1)
693 NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
694 Prod = InsertBinop(Instruction::Shl, Prod,
695 ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
696 /*IsSafeToHoist*/ true);
697 } else {
698 Prod = InsertBinop(Instruction::Mul, Prod, W, S.getNoWrapFlags(),
699 /*IsSafeToHoist*/ true);
700 }
701 }
702 }
703
704 return Prod;
705}
706
707Value *SCEVExpander::visitUDivExpr(SCEVUseT<const SCEVUDivExpr *> S) {
708 Value *LHS = expand(S->getLHS());
709 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
710 const APInt &RHS = SC->getAPInt();
711 if (RHS.isPowerOf2())
712 return InsertBinop(Instruction::LShr, LHS,
713 ConstantInt::get(SC->getType(), RHS.logBase2()),
714 SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
715 }
716
717 const SCEV *RHSExpr = S->getRHS();
718 Value *RHS = expand(RHSExpr);
719 if (SafeUDivMode) {
720 bool GuaranteedNotPoison =
722 if (!GuaranteedNotPoison)
723 RHS = Builder.CreateFreeze(RHS);
724
725 // We need an umax if either RHSExpr is not known to be zero, or if it is
726 // not guaranteed to be non-poison. In the later case, the frozen poison may
727 // be 0.
728 if (!SE.isKnownNonZero(RHSExpr) || !GuaranteedNotPoison)
729 RHS = Builder.CreateIntrinsic(RHS->getType(), Intrinsic::umax,
730 {RHS, ConstantInt::get(RHS->getType(), 1)});
731 }
732 return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
733 /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
734}
735
736/// Determine if this is a well-behaved chain of instructions leading back to
737/// the PHI. If so, it may be reused by expanded expressions.
738bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
739 const Loop *L) {
740 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
741 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
742 return false;
743 // If any of the operands don't dominate the insert position, bail.
744 // Addrec operands are always loop-invariant, so this can only happen
745 // if there are instructions which haven't been hoisted.
746 if (L == IVIncInsertLoop) {
747 for (Use &Op : llvm::drop_begin(IncV->operands()))
748 if (Instruction *OInst = dyn_cast<Instruction>(Op))
749 if (!SE.DT.dominates(OInst, IVIncInsertPos))
750 return false;
751 }
752 // Advance to the next instruction.
753 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
754 if (!IncV)
755 return false;
756
757 if (IncV->mayHaveSideEffects())
758 return false;
759
760 if (IncV == PN)
761 return true;
762
763 return isNormalAddRecExprPHI(PN, IncV, L);
764}
765
766/// getIVIncOperand returns an induction variable increment's induction
767/// variable operand.
768///
769/// If allowScale is set, any type of GEP is allowed as long as the nonIV
770/// operands dominate InsertPos.
771///
772/// If allowScale is not set, ensure that a GEP increment conforms to one of the
773/// simple patterns generated by getAddRecExprPHILiterally and
774/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
776 Instruction *InsertPos,
777 bool allowScale) {
778 if (IncV == InsertPos)
779 return nullptr;
780
781 switch (IncV->getOpcode()) {
782 default:
783 return nullptr;
784 // Check for a simple Add/Sub or GEP of a loop invariant step.
785 case Instruction::Add:
786 case Instruction::Sub: {
788 if (!OInst || SE.DT.dominates(OInst, InsertPos))
789 return dyn_cast<Instruction>(IncV->getOperand(0));
790 return nullptr;
791 }
792 case Instruction::BitCast:
793 return dyn_cast<Instruction>(IncV->getOperand(0));
794 case Instruction::GetElementPtr:
795 for (Use &U : llvm::drop_begin(IncV->operands())) {
796 if (isa<Constant>(U))
797 continue;
798 if (Instruction *OInst = dyn_cast<Instruction>(U)) {
799 if (!SE.DT.dominates(OInst, InsertPos))
800 return nullptr;
801 }
802 if (allowScale) {
803 // allow any kind of GEP as long as it can be hoisted.
804 continue;
805 }
806 // GEPs produced by SCEVExpander use i8 element type.
807 if (!cast<GEPOperator>(IncV)->getSourceElementType()->isIntegerTy(8))
808 return nullptr;
809 break;
810 }
811 return dyn_cast<Instruction>(IncV->getOperand(0));
812 }
813}
814
815/// If the insert point of the current builder or any of the builders on the
816/// stack of saved builders has 'I' as its insert point, update it to point to
817/// the instruction after 'I'. This is intended to be used when the instruction
818/// 'I' is being moved. If this fixup is not done and 'I' is moved to a
819/// different block, the inconsistent insert point (with a mismatched
820/// Instruction and Block) can lead to an instruction being inserted in a block
821/// other than its parent.
822void SCEVExpander::fixupInsertPoints(Instruction *I) {
824 BasicBlock::iterator NewInsertPt = std::next(It);
825 if (Builder.GetInsertPoint() == It)
826 Builder.SetInsertPoint(&*NewInsertPt);
827 for (auto *InsertPtGuard : InsertPointGuards)
828 if (InsertPtGuard->GetInsertPoint() == It)
829 InsertPtGuard->SetInsertPoint(NewInsertPt);
830}
831
832/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
833/// it available to other uses in this loop. Recursively hoist any operands,
834/// until we reach a value that dominates InsertPos.
836 bool RecomputePoisonFlags) {
837 auto FixupPoisonFlags = [this](Instruction *I) {
838 // Drop flags that are potentially inferred from old context and infer flags
839 // in new context.
840 rememberFlags(I);
841 I->dropPoisonGeneratingFlags();
842 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
843 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
844 auto *BO = cast<BinaryOperator>(I);
845 BO->setHasNoUnsignedWrap(
847 BO->setHasNoSignedWrap(
849 }
850 };
851
852 if (SE.DT.dominates(IncV, InsertPos)) {
853 if (RecomputePoisonFlags)
854 FixupPoisonFlags(IncV);
855 return true;
856 }
857
858 // InsertPos must itself dominate IncV so that IncV's new position satisfies
859 // its existing users.
860 if (isa<PHINode>(InsertPos) ||
861 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
862 return false;
863
864 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
865 return false;
866
867 // Check that the chain of IV operands leading back to Phi can be hoisted.
869 for(;;) {
870 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
871 if (!Oper)
872 return false;
873 // IncV is safe to hoist.
874 IVIncs.push_back(IncV);
875 IncV = Oper;
876 if (SE.DT.dominates(IncV, InsertPos))
877 break;
878 }
879 for (Instruction *I : llvm::reverse(IVIncs)) {
880 fixupInsertPoints(I);
881 I->moveBefore(InsertPos->getIterator());
882 if (RecomputePoisonFlags)
883 FixupPoisonFlags(I);
884 }
885 return true;
886}
887
889 PHINode *WidePhi,
890 Instruction *OrigInc,
891 Instruction *WideInc) {
892 return match(OrigInc, m_c_BinOp(m_Specific(OrigPhi), m_Value())) &&
893 match(WideInc, m_c_BinOp(m_Specific(WidePhi), m_Value())) &&
894 OrigInc->getOpcode() == WideInc->getOpcode();
895}
896
897/// Determine if this cyclic phi is in a form that would have been generated by
898/// LSR. We don't care if the phi was actually expanded in this pass, as long
899/// as it is in a low-cost form, for example, no implied multiplication. This
900/// should match any patterns generated by getAddRecExprPHILiterally and
901/// expandAddtoGEP.
902bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
903 const Loop *L) {
904 for(Instruction *IVOper = IncV;
905 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
906 /*allowScale=*/false));) {
907 if (IVOper == PN)
908 return true;
909 }
910 return false;
911}
912
913/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
914/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
915/// need to materialize IV increments elsewhere to handle difficult situations.
916Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
917 bool useSubtract) {
918 Value *IncV;
919 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
920 if (PN->getType()->isPointerTy()) {
921 // TODO: Change name to IVName.iv.next.
922 IncV = Builder.CreatePtrAdd(PN, StepV, "scevgep");
923 } else {
924 IncV = useSubtract ?
925 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
926 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
927 }
928 return IncV;
929}
930
931/// Check whether we can cheaply express the requested SCEV in terms of
932/// the available PHI SCEV by truncation and/or inversion of the step.
934 const SCEVAddRecExpr *Phi,
935 const SCEVAddRecExpr *Requested,
936 bool &InvertStep) {
937 // We can't transform to match a pointer PHI.
938 Type *PhiTy = Phi->getType();
939 Type *RequestedTy = Requested->getType();
940 if (PhiTy->isPointerTy() || RequestedTy->isPointerTy())
941 return false;
942
943 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
944 return false;
945
946 // Try truncate it if necessary.
947 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
948 if (!Phi)
949 return false;
950
951 // Check whether truncation will help.
952 if (Phi == Requested) {
953 InvertStep = false;
954 return true;
955 }
956
957 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
958 if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
959 InvertStep = true;
960 return true;
961 }
962
963 return false;
964}
965
966static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
967 if (!isa<IntegerType>(AR->getType()))
968 return false;
969
970 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
971 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
972 const SCEV *Step = AR->getStepRecurrence(SE);
973 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
974 SE.getSignExtendExpr(AR, WideTy));
975 const SCEV *ExtendAfterOp =
976 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
977 return ExtendAfterOp == OpAfterExtend;
978}
979
980static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
981 if (!isa<IntegerType>(AR->getType()))
982 return false;
983
984 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
985 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
986 const SCEV *Step = AR->getStepRecurrence(SE);
987 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
988 SE.getZeroExtendExpr(AR, WideTy));
989 const SCEV *ExtendAfterOp =
990 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
991 return ExtendAfterOp == OpAfterExtend;
992}
993
994/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
995/// the base addrec, which is the addrec without any non-loop-dominating
996/// values, and return the PHI.
997PHINode *
998SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
999 const Loop *L, Type *&TruncTy,
1000 bool &InvertStep) {
1001 assert((!IVIncInsertLoop || IVIncInsertPos) &&
1002 "Uninitialized insert position");
1003
1004 // Reuse a previously-inserted PHI, if present.
1005 BasicBlock *LatchBlock = L->getLoopLatch();
1006 if (LatchBlock) {
1007 PHINode *AddRecPhiMatch = nullptr;
1008 Instruction *IncV = nullptr;
1009 TruncTy = nullptr;
1010 InvertStep = false;
1011
1012 // Only try partially matching scevs that need truncation and/or
1013 // step-inversion if we know this loop is outside the current loop.
1014 bool TryNonMatchingSCEV =
1015 IVIncInsertLoop &&
1016 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1017
1018 for (PHINode &PN : L->getHeader()->phis()) {
1019 if (!SE.isSCEVable(PN.getType()))
1020 continue;
1021
1022 // We should not look for a incomplete PHI. Getting SCEV for a incomplete
1023 // PHI has no meaning at all.
1024 if (!PN.isComplete()) {
1026 DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
1027 continue;
1028 }
1029
1030 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
1031 if (!PhiSCEV)
1032 continue;
1033
1034 bool IsMatchingSCEV = PhiSCEV == Normalized;
1035 // We only handle truncation and inversion of phi recurrences for the
1036 // expanded expression if the expanded expression's loop dominates the
1037 // loop we insert to. Check now, so we can bail out early.
1038 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1039 continue;
1040
1041 // TODO: this possibly can be reworked to avoid this cast at all.
1042 Instruction *TempIncV =
1044 if (!TempIncV)
1045 continue;
1046
1047 // Check whether we can reuse this PHI node.
1048 if (LSRMode) {
1049 if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
1050 continue;
1051 } else {
1052 if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
1053 continue;
1054 }
1055
1056 // Stop if we have found an exact match SCEV.
1057 if (IsMatchingSCEV) {
1058 IncV = TempIncV;
1059 TruncTy = nullptr;
1060 InvertStep = false;
1061 AddRecPhiMatch = &PN;
1062 break;
1063 }
1064
1065 // Try whether the phi can be translated into the requested form
1066 // (truncated and/or offset by a constant).
1067 if ((!TruncTy || InvertStep) &&
1068 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1069 // Record the phi node. But don't stop we might find an exact match
1070 // later.
1071 AddRecPhiMatch = &PN;
1072 IncV = TempIncV;
1073 TruncTy = Normalized->getType();
1074 }
1075 }
1076
1077 if (AddRecPhiMatch) {
1078 // Ok, the add recurrence looks usable.
1079 // Remember this PHI, even in post-inc mode.
1080 InsertedValues.insert(AddRecPhiMatch);
1081 // Remember the increment.
1082 rememberInstruction(IncV);
1083 // Those values were not actually inserted but re-used.
1084 ReusedValues.insert(AddRecPhiMatch);
1085 ReusedValues.insert(IncV);
1086 return AddRecPhiMatch;
1087 }
1088 }
1089
1090 // Save the original insertion point so we can restore it when we're done.
1091 SCEVInsertPointGuard Guard(Builder, this);
1092
1093 // Another AddRec may need to be recursively expanded below. For example, if
1094 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1095 // loop. Remove this loop from the PostIncLoops set before expanding such
1096 // AddRecs. Otherwise, we cannot find a valid position for the step
1097 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1098 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1099 // so it's not worth implementing SmallPtrSet::swap.
1100 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1101 PostIncLoops.clear();
1102
1103 // Expand code for the start value into the loop preheader.
1104 assert(L->getLoopPreheader() &&
1105 "Can't expand add recurrences without a loop preheader!");
1106 Value *StartV =
1107 expand(Normalized->getStart(), L->getLoopPreheader()->getTerminator());
1108
1109 // StartV must have been be inserted into L's preheader to dominate the new
1110 // phi.
1111 assert(!isa<Instruction>(StartV) ||
1112 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1113 L->getHeader()));
1114
1115 // Expand code for the step value. Do this before creating the PHI so that PHI
1116 // reuse code doesn't see an incomplete PHI.
1117 const SCEV *Step = Normalized->getStepRecurrence(SE);
1118 Type *ExpandTy = Normalized->getType();
1119 // If the stride is negative, insert a sub instead of an add for the increment
1120 // (unless it's a constant, because subtracts of constants are canonicalized
1121 // to adds).
1122 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1123 if (useSubtract)
1124 Step = SE.getNegativeSCEV(Step);
1125 // Expand the step somewhere that dominates the loop header.
1126 Value *StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1127
1128 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1129 // we actually do emit an addition. It does not apply if we emit a
1130 // subtraction.
1131 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1132 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1133
1134 // Create the PHI.
1135 BasicBlock *Header = L->getHeader();
1136 Builder.SetInsertPoint(Header, Header->begin());
1137 PHINode *PN =
1138 Builder.CreatePHI(ExpandTy, pred_size(Header), Twine(IVName) + ".iv");
1139
1140 // Create the step instructions and populate the PHI.
1141 for (BasicBlock *Pred : predecessors(Header)) {
1142 // Add a start value.
1143 if (!L->contains(Pred)) {
1144 PN->addIncoming(StartV, Pred);
1145 continue;
1146 }
1147
1148 // Create a step value and add it to the PHI.
1149 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1150 // instructions at IVIncInsertPos.
1151 Instruction *InsertPos = L == IVIncInsertLoop ?
1152 IVIncInsertPos : Pred->getTerminator();
1153 Builder.SetInsertPoint(InsertPos);
1154 Value *IncV = expandIVInc(PN, StepV, L, useSubtract);
1155
1157 if (IncrementIsNUW)
1158 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1159 if (IncrementIsNSW)
1160 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1161 }
1162 PN->addIncoming(IncV, Pred);
1163 }
1164
1165 // After expanding subexpressions, restore the PostIncLoops set so the caller
1166 // can ensure that IVIncrement dominates the current uses.
1167 PostIncLoops = SavedPostIncLoops;
1168
1169 // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
1170 // effective when we are able to use an IV inserted here, so record it.
1171 InsertedValues.insert(PN);
1172 InsertedIVs.push_back(PN);
1173 return PN;
1174}
1175
1176Value *
1177SCEVExpander::expandAddRecExprLiterally(SCEVUseT<const SCEVAddRecExpr *> S) {
1178 const Loop *L = S->getLoop();
1179
1180 // Determine a normalized form of this expression, which is the expression
1181 // before any post-inc adjustment is made.
1182 const SCEVAddRecExpr *Normalized = S;
1183 if (PostIncLoops.count(L)) {
1185 Loops.insert(L);
1186 Normalized = cast<SCEVAddRecExpr>(
1187 normalizeForPostIncUse(S, Loops, SE, /*CheckInvertible=*/false));
1188 }
1189
1190 [[maybe_unused]] const SCEV *Start = Normalized->getStart();
1191 const SCEV *Step = Normalized->getStepRecurrence(SE);
1192 assert(SE.properlyDominates(Start, L->getHeader()) &&
1193 "Start does not properly dominate loop header");
1194 assert(SE.dominates(Step, L->getHeader()) && "Step not dominate loop header");
1195
1196 // In some cases, we decide to reuse an existing phi node but need to truncate
1197 // it and/or invert the step.
1198 Type *TruncTy = nullptr;
1199 bool InvertStep = false;
1200 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, TruncTy, InvertStep);
1201
1202 // Accommodate post-inc mode, if necessary.
1203 Value *Result;
1204 if (!PostIncLoops.count(L))
1205 Result = PN;
1206 else {
1207 // In PostInc mode, use the post-incremented value.
1208 BasicBlock *LatchBlock = L->getLoopLatch();
1209 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1210 Result = PN->getIncomingValueForBlock(LatchBlock);
1211
1212 // We might be introducing a new use of the post-inc IV that is not poison
1213 // safe, in which case we should drop poison generating flags. Only keep
1214 // those flags for which SCEV has proven that they always hold.
1215 if (isa<OverflowingBinaryOperator>(Result)) {
1216 auto *I = cast<Instruction>(Result);
1217 if (!S->hasNoUnsignedWrap())
1218 I->setHasNoUnsignedWrap(false);
1219 if (!S->hasNoSignedWrap())
1220 I->setHasNoSignedWrap(false);
1221 }
1222
1223 // For an expansion to use the postinc form, the client must call
1224 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1225 // or dominated by IVIncInsertPos.
1226 if (isa<Instruction>(Result) &&
1227 !SE.DT.dominates(cast<Instruction>(Result),
1228 &*Builder.GetInsertPoint())) {
1229 // The induction variable's postinc expansion does not dominate this use.
1230 // IVUsers tries to prevent this case, so it is rare. However, it can
1231 // happen when an IVUser outside the loop is not dominated by the latch
1232 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1233 // all cases. Consider a phi outside whose operand is replaced during
1234 // expansion with the value of the postinc user. Without fundamentally
1235 // changing the way postinc users are tracked, the only remedy is
1236 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1237 // but hopefully expandCodeFor handles that.
1238 bool useSubtract =
1239 !S->getType()->isPointerTy() && Step->isNonConstantNegative();
1240 if (useSubtract)
1241 Step = SE.getNegativeSCEV(Step);
1242 Value *StepV;
1243 {
1244 // Expand the step somewhere that dominates the loop header.
1245 SCEVInsertPointGuard Guard(Builder, this);
1246 StepV = expand(Step, L->getHeader()->getFirstInsertionPt());
1247 }
1248 Result = expandIVInc(PN, StepV, L, useSubtract);
1249 }
1250 }
1251
1252 // We have decided to reuse an induction variable of a dominating loop. Apply
1253 // truncation and/or inversion of the step.
1254 if (TruncTy) {
1255 if (TruncTy != Result->getType() || InvertStep)
1256 Result = fixupLCSSAFormFor(Result);
1257 // Truncate the result.
1258 if (TruncTy != Result->getType())
1259 Result = Builder.CreateTrunc(Result, TruncTy);
1260
1261 // Invert the result.
1262 if (InvertStep)
1263 Result = Builder.CreateSub(expand(Normalized->getStart()), Result);
1264 }
1265
1266 return Result;
1267}
1268
1269Value *SCEVExpander::tryToReuseLCSSAPhi(SCEVUseT<const SCEVAddRecExpr *> S) {
1270 Type *STy = S->getType();
1271 const Loop *L = S->getLoop();
1272 BasicBlock *EB = L->getExitBlock();
1273 if (!EB || !EB->getSinglePredecessor() ||
1274 !SE.DT.dominates(EB, Builder.GetInsertBlock()))
1275 return nullptr;
1276
1277 // Helper to check if the diff between S and ExitSCEV is simple enough to
1278 // allow reusing the LCSSA phi.
1279 auto CanReuse = [&](const SCEV *ExitSCEV) -> const SCEV * {
1280 if (isa<SCEVCouldNotCompute>(ExitSCEV))
1281 return nullptr;
1282 const SCEV *Diff = SE.getMinusSCEV(S, ExitSCEV);
1283 const SCEV *Op = Diff;
1288 return nullptr;
1289 return Diff;
1290 };
1291
1292 for (auto &PN : EB->phis()) {
1293 if (!SE.isSCEVable(PN.getType()))
1294 continue;
1295 auto *ExitSCEV = SE.getSCEV(&PN);
1296 if (!isa<SCEVAddRecExpr>(ExitSCEV))
1297 continue;
1298 Type *PhiTy = PN.getType();
1299 const SCEV *Diff = nullptr;
1300 if (STy->isIntegerTy() && PhiTy->isPointerTy() &&
1301 DL.getAddressType(PhiTy) == STy) {
1302 const SCEV *AddrSCEV = SE.getPtrToAddrExpr(ExitSCEV);
1303 Diff = CanReuse(AddrSCEV);
1304 } else if (STy == PhiTy) {
1305 Diff = CanReuse(ExitSCEV);
1306 }
1307 if (!Diff)
1308 continue;
1309
1310 assert(Diff->getType()->isIntegerTy() &&
1311 "difference must be of integer type");
1312 Value *DiffV = expand(Diff);
1313 Value *BaseV = fixupLCSSAFormFor(&PN);
1314 if (PhiTy->isPointerTy()) {
1315 if (STy->isPointerTy())
1316 return Builder.CreatePtrAdd(BaseV, DiffV);
1317 BaseV = Builder.CreatePtrToAddr(BaseV);
1318 }
1319 return Builder.CreateAdd(BaseV, DiffV);
1320 }
1321
1322 return nullptr;
1323}
1324
1325Value *SCEVExpander::visitAddRecExpr(SCEVUseT<const SCEVAddRecExpr *> S) {
1326 // In canonical mode we compute the addrec as an expression of a canonical IV
1327 // using evaluateAtIteration and expand the resulting SCEV expression. This
1328 // way we avoid introducing new IVs to carry on the computation of the addrec
1329 // throughout the loop.
1330 //
1331 // For nested addrecs evaluateAtIteration might need a canonical IV of a
1332 // type wider than the addrec itself. Emitting a canonical IV of the
1333 // proper type might produce non-legal types, for example expanding an i64
1334 // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
1335 // back to non-canonical mode for nested addrecs.
1336 if (!CanonicalMode || (S->getNumOperands() > 2))
1337 return expandAddRecExprLiterally(S);
1338
1339 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1340 const Loop *L = S->getLoop();
1341
1342 // First check for an existing canonical IV in a suitable type.
1343 PHINode *CanonicalIV = nullptr;
1344 if (PHINode *PN = L->getCanonicalInductionVariable())
1345 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1346 CanonicalIV = PN;
1347
1348 // Rewrite an AddRec in terms of the canonical induction variable, if
1349 // its type is more narrow.
1350 if (CanonicalIV &&
1351 SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
1352 !S->getType()->isPointerTy()) {
1353 SmallVector<SCEVUse, 4> NewOps(S->getNumOperands());
1354 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1355 NewOps[i] = SE.getAnyExtendExpr(S->getOperand(i), CanonicalIV->getType());
1356 Value *V = expand(
1357 SE.getAddRecExpr(NewOps, S->getLoop(), S.getNoWrapFlags(SCEV::FlagNW)));
1358 BasicBlock::iterator NewInsertPt =
1360 &*Builder.GetInsertPoint())
1361 : Builder.GetInsertPoint();
1362 V = expand(SE.getTruncateExpr(SE.getUnknown(V), Ty), NewInsertPt);
1363 return V;
1364 }
1365
1366 // If S is expanded outside the defining loop, check if there is a
1367 // matching LCSSA phi node for it.
1368 if (Value *V = tryToReuseLCSSAPhi(S))
1369 return V;
1370
1371 // {X,+,F} --> X + {0,+,F}
1372 if (!S->getStart()->isZero()) {
1373 if (isa<PointerType>(S->getType())) {
1374 Value *StartV = expand(SE.getPointerBase(S));
1375 return expandAddToGEP(SE.removePointerBase(S), StartV,
1377 }
1378
1379 SmallVector<SCEVUse, 4> NewOps(S->operands());
1380 NewOps[0] = SE.getConstant(Ty, 0);
1381 const SCEV *Rest =
1382 SE.getAddRecExpr(NewOps, L, S.getNoWrapFlags(SCEV::FlagNW));
1383
1384 // Just do a normal add. Pre-expand the operands to suppress folding.
1385 //
1386 // The LHS and RHS values are factored out of the expand call to make the
1387 // output independent of the argument evaluation order.
1388 const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
1389 const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
1390 return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
1391 }
1392
1393 // If we don't yet have a canonical IV, create one.
1394 if (!CanonicalIV) {
1395 // Create and insert the PHI node for the induction variable in the
1396 // specified loop.
1397 BasicBlock *Header = L->getHeader();
1398 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1399 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar");
1400 CanonicalIV->insertBefore(Header->begin());
1401 rememberInstruction(CanonicalIV);
1402
1403 SmallPtrSet<BasicBlock *, 4> PredSeen;
1404 Constant *One = ConstantInt::get(Ty, 1);
1405 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1406 BasicBlock *HP = *HPI;
1407 if (!PredSeen.insert(HP).second) {
1408 // There must be an incoming value for each predecessor, even the
1409 // duplicates!
1410 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1411 continue;
1412 }
1413
1414 if (L->contains(HP)) {
1415 // Insert a unit add instruction right before the terminator
1416 // corresponding to the back-edge.
1417 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1418 "indvar.next",
1419 HP->getTerminator()->getIterator());
1420 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1421 rememberInstruction(Add);
1422 CanonicalIV->addIncoming(Add, HP);
1423 } else {
1424 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1425 }
1426 }
1427 }
1428
1429 // {0,+,1} --> Insert a canonical induction variable into the loop!
1430 if (S->isAffine() && S->getOperand(1)->isOne()) {
1431 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1432 "IVs with types different from the canonical IV should "
1433 "already have been handled!");
1434 return CanonicalIV;
1435 }
1436
1437 // {0,+,F} --> {0,+,1} * F
1438
1439 // If this is a simple linear addrec, emit it now as a special case.
1440 if (S->isAffine()) // {0,+,F} --> i*F
1441 return
1442 expand(SE.getTruncateOrNoop(
1443 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1444 SE.getNoopOrAnyExtend(S->getOperand(1),
1445 CanonicalIV->getType())),
1446 Ty));
1447
1448 // If this is a chain of recurrences, turn it into a closed form, using the
1449 // folders, then expandCodeFor the closed form. This allows the folders to
1450 // simplify the expression without having to build a bunch of special code
1451 // into this folder.
1452 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1453
1454 // Promote S up to the canonical IV type, if the cast is foldable.
1455 const SCEV *NewS = S;
1456 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1457 if (isa<SCEVAddRecExpr>(Ext))
1458 NewS = Ext;
1459
1460 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1461
1462 // Truncate the result down to the original type, if needed.
1463 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1464 return expand(T);
1465}
1466
1467/// Return true if \p CI computes the same value as a `ptrtoaddr` of its
1468/// pointer operand to \p Ty.
1469static bool canReuseCastForPtrToAddr(const CastInst *CI, Type *Ty,
1470 const DataLayout &DL) {
1471 if (CI->getType() != Ty)
1472 return false;
1473 if (CI->getOpcode() == CastInst::PtrToAddr)
1474 return true;
1475 if (CI->getOpcode() != CastInst::PtrToInt)
1476 return false;
1477 unsigned AS = CI->getSrcTy()->getPointerAddressSpace();
1478 return DL.getPointerSizeInBits(AS) == DL.getIndexSizeInBits(AS);
1479}
1480
1482 Value *PtrOp, Type *Ty, const DataLayout &DL,
1483 function_ref<bool(const CastInst *)> Dominates) {
1484 // Constants have no use list to scan.
1485 if (isa<Constant>(PtrOp))
1486 return nullptr;
1487 for (User *U : PtrOp->users()) {
1488 auto *CI = dyn_cast<CastInst>(U);
1489 if (!CI || !canReuseCastForPtrToAddr(CI, Ty, DL))
1490 continue;
1491 if (Dominates(CI))
1492 return CI;
1493 }
1494 return nullptr;
1495}
1496
1497Value *SCEVExpander::visitPtrToAddrExpr(SCEVUseT<const SCEVPtrToAddrExpr *> S) {
1498 Value *V = expand(S->getOperand());
1499 Type *Ty = S->getType();
1500
1501 // ptrtoaddr and ptrtoint can produce the same value, so try to reuse either.
1502 BasicBlock::iterator BIP = Builder.GetInsertPoint();
1503 if (CastInst *CI =
1504 findReusableCastForPtrToAddr(V, Ty, DL, [&](const CastInst *CI) {
1505 return &*BIP != CI && SE.DT.dominates(CI, &*BIP);
1506 }))
1507 return CI;
1508
1509 return ReuseOrCreateCast(V, Ty, CastInst::PtrToAddr,
1510 GetOptimalInsertionPointForCastOf(V));
1511}
1512
1513Value *SCEVExpander::visitTruncateExpr(SCEVUseT<const SCEVTruncateExpr *> S) {
1514 Type *Ty = S->getType();
1515
1516 // When truncating a ptrtoaddr, check for existing ptrtoint instructions that
1517 // convert directly to the target type, to avoid generating redundant
1518 // ptrtoaddr + trunc sequences.
1519 if (auto *PtrToAddr = dyn_cast<SCEVPtrToAddrExpr>(S->getOperand())) {
1520 Value *PtrOp = expand(PtrToAddr->getOperand());
1521 if (!isa<Constant>(PtrOp)) {
1522 BasicBlock::iterator BIP = Builder.GetInsertPoint();
1523 for (User *U : PtrOp->users()) {
1524 auto *CI = dyn_cast<CastInst>(U);
1525 if (CI && CI->getType() == Ty &&
1526 CI->getOpcode() == CastInst::PtrToInt && &*BIP != CI &&
1527 SE.DT.dominates(CI, &*BIP))
1528 return CI;
1529 }
1530 }
1531 }
1532
1533 Value *V = expand(S->getOperand());
1534 return Builder.CreateTrunc(V, S->getType());
1535}
1536
1537Value *
1538SCEVExpander::visitZeroExtendExpr(SCEVUseT<const SCEVZeroExtendExpr *> S) {
1539 Value *V = expand(S->getOperand());
1540 return Builder.CreateZExt(V, S->getType(), "",
1541 SE.isKnownNonNegative(S->getOperand()));
1542}
1543
1544Value *
1545SCEVExpander::visitSignExtendExpr(SCEVUseT<const SCEVSignExtendExpr *> S) {
1546 Value *V = expand(S->getOperand());
1547 return Builder.CreateSExt(V, S->getType());
1548}
1549
1550Value *SCEVExpander::expandMinMaxExpr(SCEVUseT<const SCEVNAryExpr *> S,
1551 Intrinsic::ID IntrinID, Twine Name,
1552 bool IsSequential) {
1553 bool PrevSafeMode = SafeUDivMode;
1554 SafeUDivMode |= IsSequential;
1555 Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
1556 Type *Ty = LHS->getType();
1557 if (IsSequential)
1558 LHS = Builder.CreateFreeze(LHS);
1559 for (int i = S->getNumOperands() - 2; i >= 0; --i) {
1560 SafeUDivMode = (IsSequential && i != 0) || PrevSafeMode;
1561 Value *RHS = expand(S->getOperand(i));
1562 if (IsSequential && i != 0)
1563 RHS = Builder.CreateFreeze(RHS);
1564 Value *Sel;
1565 if (Ty->isIntegerTy())
1566 Sel = Builder.CreateIntrinsic(IntrinID, {Ty}, {LHS, RHS},
1567 /*FMFSource=*/nullptr, Name);
1568 else {
1569 Value *ICmp =
1570 Builder.CreateICmp(MinMaxIntrinsic::getPredicate(IntrinID), LHS, RHS);
1571 Sel = Builder.CreateSelect(ICmp, LHS, RHS, Name);
1572 }
1573 LHS = Sel;
1574 }
1575 SafeUDivMode = PrevSafeMode;
1576 return LHS;
1577}
1578
1579Value *SCEVExpander::visitSMaxExpr(SCEVUseT<const SCEVSMaxExpr *> S) {
1580 return expandMinMaxExpr(S, Intrinsic::smax, "smax");
1581}
1582
1583Value *SCEVExpander::visitUMaxExpr(SCEVUseT<const SCEVUMaxExpr *> S) {
1584 return expandMinMaxExpr(S, Intrinsic::umax, "umax");
1585}
1586
1587Value *SCEVExpander::visitSMinExpr(SCEVUseT<const SCEVSMinExpr *> S) {
1588 return expandMinMaxExpr(S, Intrinsic::smin, "smin");
1589}
1590
1591Value *SCEVExpander::visitUMinExpr(SCEVUseT<const SCEVUMinExpr *> S) {
1592 return expandMinMaxExpr(S, Intrinsic::umin, "umin");
1593}
1594
1595Value *SCEVExpander::visitSequentialUMinExpr(
1597 return expandMinMaxExpr(S, Intrinsic::umin, "umin",
1598 /*IsSequential*/ true);
1599}
1600
1601Value *SCEVExpander::visitVScale(SCEVUseT<const SCEVVScale *> S) {
1602 return Builder.CreateVScale(S->getType());
1603}
1604
1607 setInsertPoint(IP);
1608 return expandCodeFor(SH, Ty);
1609}
1610
1612 // Expand the code for this SCEV.
1613 Value *V = expand(SH);
1614
1615 if (Ty && Ty != V->getType()) {
1616 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1617 "non-trivial casts should be done with the SCEVs directly!");
1618 V = InsertNoopCastOfTo(V, Ty);
1619 }
1620 return V;
1621}
1622
1623Value *SCEVExpander::FindValueInExprValueMap(
1624 SCEVUse S, const Instruction *InsertPt,
1625 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts) {
1626 // If the expansion is not in CanonicalMode, and the SCEV contains any
1627 // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
1628 if (!CanonicalMode && SE.containsAddRecurrence(S))
1629 return nullptr;
1630
1631 // If S is a constant or unknown, it may be worse to reuse an existing Value.
1633 return nullptr;
1634
1635 for (Value *V : SE.getSCEVValues(S)) {
1636 Instruction *EntInst = dyn_cast<Instruction>(V);
1637 if (!EntInst)
1638 continue;
1639
1640 // Choose a Value from the set which dominates the InsertPt.
1641 // InsertPt should be inside the Value's parent loop so as not to break
1642 // the LCSSA form.
1643 assert(EntInst->getFunction() == InsertPt->getFunction());
1644 if (S->getType() != V->getType() || !SE.DT.dominates(EntInst, InsertPt) ||
1645 !(SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
1646 SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
1647 continue;
1648
1649 // Make sure reusing the instruction is poison-safe.
1650 if (SE.canReuseInstruction(S, EntInst, DropPoisonGeneratingInsts))
1651 return V;
1652 DropPoisonGeneratingInsts.clear();
1653 }
1654 return nullptr;
1655}
1656
1657// The expansion of SCEV will either reuse a previous Value in ExprValueMap,
1658// or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
1659// and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
1660// literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
1661// the expansion will try to reuse Value from ExprValueMap, and only when it
1662// fails, expand the SCEV literally.
1663Value *SCEVExpander::expand(SCEVUse S) {
1664 // Compute an insertion point for this SCEV object. Hoist the instructions
1665 // as far out in the loop nest as possible.
1666 BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
1667
1668 // We can move insertion point only if there is no div or rem operations
1669 // otherwise we are risky to move it over the check for zero denominator.
1670 auto SafeToHoist = [](const SCEV *S) {
1671 return !SCEVExprContains(S, [](const SCEV *S) {
1672 if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
1673 if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
1674 // Division by non-zero constants can be hoisted.
1675 return SC->getValue()->isZero();
1676 // All other divisions should not be moved as they may be
1677 // divisions by zero and should be kept within the
1678 // conditions of the surrounding loops that guard their
1679 // execution (see PR35406).
1680 return true;
1681 }
1682 return false;
1683 });
1684 };
1685 if (SafeToHoist(S)) {
1686 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1687 L = L->getParentLoop()) {
1688 if (SE.isLoopInvariant(S, L)) {
1689 if (!L) break;
1690 if (BasicBlock *Preheader = L->getLoopPreheader()) {
1691 InsertPt = Preheader->getTerminator()->getIterator();
1692 } else {
1693 // LSR sets the insertion point for AddRec start/step values to the
1694 // block start to simplify value reuse, even though it's an invalid
1695 // position. SCEVExpander must correct for this in all cases.
1696 InsertPt = L->getHeader()->getFirstInsertionPt();
1697 }
1698 } else {
1699 // If the SCEV is computable at this level, insert it into the header
1700 // after the PHIs (and after any other instructions that we've inserted
1701 // there) so that it is guaranteed to dominate any user inside the loop.
1702 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1703 InsertPt = L->getHeader()->getFirstInsertionPt();
1704
1705 while (InsertPt != Builder.GetInsertPoint() &&
1706 (isInsertedInstruction(&*InsertPt))) {
1707 InsertPt = std::next(InsertPt);
1708 }
1709 break;
1710 }
1711 }
1712 }
1713
1714 // Check to see if we already expanded this here.
1715 auto I = InsertedExpressions.find(std::make_pair(S, &*InsertPt));
1716 if (I != InsertedExpressions.end())
1717 return I->second;
1718
1719 SCEVInsertPointGuard Guard(Builder, this);
1720 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1721
1722 // Expand the expression into instructions.
1723 SmallVector<Instruction *> DropPoisonGeneratingInsts;
1724 Value *V = FindValueInExprValueMap(S, &*InsertPt, DropPoisonGeneratingInsts);
1725 if (!V) {
1726 V = visit(S);
1727 V = fixupLCSSAFormFor(V);
1728 } else {
1729 for (Instruction *I : DropPoisonGeneratingInsts) {
1730 rememberFlags(I);
1732 }
1733 }
1734 // Remember the expanded value for this SCEV at this location.
1735 //
1736 // This is independent of PostIncLoops. The mapped value simply materializes
1737 // the expression at this insertion point. If the mapped value happened to be
1738 // a postinc expansion, it could be reused by a non-postinc user, but only if
1739 // its insertion point was already at the head of the loop.
1740 InsertedExpressions[std::make_pair(S, &*InsertPt)] = V;
1741 return V;
1742}
1743
1744void SCEVExpander::rememberInstruction(Value *I) {
1745 auto DoInsert = [this](Value *V) {
1746 if (!PostIncLoops.empty())
1747 InsertedPostIncValues.insert(V);
1748 else
1749 InsertedValues.insert(V);
1750 };
1751 DoInsert(I);
1752}
1753
1754void SCEVExpander::rememberFlags(Instruction *I) {
1755 // If we already have flags for the instruction, keep the existing ones.
1756 OrigFlags.try_emplace(I, PoisonFlags(I));
1757}
1758
1761 I->dropPoisonGeneratingAnnotations();
1762 // See if we can re-infer from first principles any of the flags we just
1763 // dropped.
1764 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
1765 if (auto Flags = SE.getStrengthenedNoWrapFlagsFromBinOp(OBO)) {
1766 auto *BO = cast<BinaryOperator>(I);
1767 BO->setHasNoUnsignedWrap(
1769 BO->setHasNoSignedWrap(
1771 }
1772 if (auto *NNI = dyn_cast<PossiblyNonNegInst>(I)) {
1773 auto *Src = NNI->getOperand(0);
1775 Constant::getNullValue(Src->getType()), I,
1776 SE.getDataLayout())
1777 .value_or(false))
1778 NNI->setNonNeg(true);
1779 }
1780}
1781
1782void SCEVExpander::replaceCongruentIVInc(
1783 PHINode *&Phi, PHINode *&OrigPhi, Loop *L, const DominatorTree *DT,
1785 BasicBlock *LatchBlock = L->getLoopLatch();
1786 if (!LatchBlock)
1787 return;
1788
1789 Instruction *OrigInc =
1790 dyn_cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1791 Instruction *IsomorphicInc =
1792 dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1793 if (!OrigInc || !IsomorphicInc)
1794 return;
1795
1796 // If this phi has the same width but is more canonical, replace the
1797 // original with it. As part of the "more canonical" determination,
1798 // respect a prior decision to use an IV chain.
1799 if (OrigPhi->getType() == Phi->getType()) {
1800 bool Chained = ChainedPhis.contains(Phi);
1801 if (!(Chained || isExpandedAddRecExprPHI(OrigPhi, OrigInc, L)) &&
1802 (Chained || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1803 std::swap(OrigPhi, Phi);
1804 std::swap(OrigInc, IsomorphicInc);
1805 }
1806 }
1807
1808 // Replacing the congruent phi is sufficient because acyclic
1809 // redundancy elimination, CSE/GVN, should handle the
1810 // rest. However, once SCEV proves that a phi is congruent,
1811 // it's often the head of an IV user cycle that is isomorphic
1812 // with the original phi. It's worth eagerly cleaning up the
1813 // common case of a single IV increment so that DeleteDeadPHIs
1814 // can remove cycles that had postinc uses.
1815 // Because we may potentially introduce a new use of OrigIV that didn't
1816 // exist before at this point, its poison flags need readjustment.
1817 const SCEV *TruncExpr =
1818 SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
1819 if (OrigInc == IsomorphicInc || TruncExpr != SE.getSCEV(IsomorphicInc) ||
1820 !SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc))
1821 return;
1822
1823 bool BothHaveNUW = false;
1824 bool BothHaveNSW = false;
1825 auto *OBOIncV = dyn_cast<OverflowingBinaryOperator>(OrigInc);
1826 auto *OBOIsomorphic = dyn_cast<OverflowingBinaryOperator>(IsomorphicInc);
1827 if (OBOIncV && OBOIsomorphic) {
1828 BothHaveNUW =
1829 OBOIncV->hasNoUnsignedWrap() && OBOIsomorphic->hasNoUnsignedWrap();
1830 BothHaveNSW =
1831 OBOIncV->hasNoSignedWrap() && OBOIsomorphic->hasNoSignedWrap();
1832 }
1833
1834 if (!hoistIVInc(OrigInc, IsomorphicInc,
1835 /*RecomputePoisonFlags*/ true))
1836 return;
1837
1838 // We are replacing with a wider increment. If both OrigInc and IsomorphicInc
1839 // are NUW/NSW, then we can preserve them on the wider increment; the narrower
1840 // IsomorphicInc would wrap before the wider OrigInc, so the replacement won't
1841 // make IsomorphicInc's uses more poisonous.
1842 assert(OrigInc->getType()->getScalarSizeInBits() >=
1843 IsomorphicInc->getType()->getScalarSizeInBits() &&
1844 "Should only replace an increment with a wider one.");
1845 if (BothHaveNUW || BothHaveNSW) {
1846 OrigInc->setHasNoUnsignedWrap(OBOIncV->hasNoUnsignedWrap() || BothHaveNUW);
1847 OrigInc->setHasNoSignedWrap(OBOIncV->hasNoSignedWrap() || BothHaveNSW);
1848 }
1849
1850 SCEV_DEBUG_WITH_TYPE(DebugType,
1851 dbgs() << "INDVARS: Eliminated congruent iv.inc: "
1852 << *IsomorphicInc << '\n');
1853 Value *NewInc = OrigInc;
1854 if (OrigInc->getType() != IsomorphicInc->getType()) {
1856 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1857 IP = PN->getParent()->getFirstInsertionPt();
1858 else
1859 IP = OrigInc->getNextNode()->getIterator();
1860
1861 IRBuilder<> Builder(IP->getParent(), IP);
1862 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1863 NewInc =
1864 Builder.CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1865 }
1866 IsomorphicInc->replaceAllUsesWith(NewInc);
1867 DeadInsts.emplace_back(IsomorphicInc);
1868}
1869
1870/// replaceCongruentIVs - Check for congruent phis in this loop header and
1871/// replace them with their most canonical representative. Return the number of
1872/// phis eliminated.
1873///
1874/// This does not depend on any SCEVExpander state but should be used in
1875/// the same context that SCEVExpander is used.
1876unsigned
1879 const TargetTransformInfo *TTI) {
1880 // Find integer phis in order of increasing width.
1882 llvm::make_pointer_range(L->getHeader()->phis()));
1883
1884 if (TTI)
1885 // Use stable_sort to preserve order of equivalent PHIs, so the order
1886 // of the sorted Phis is the same from run to run on the same loop.
1887 llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
1888 // Put pointers at the back and make sure pointer < pointer = false.
1889 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1890 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1891 return RHS->getType()->getPrimitiveSizeInBits().getFixedValue() <
1892 LHS->getType()->getPrimitiveSizeInBits().getFixedValue();
1893 });
1894
1895 unsigned NumElim = 0;
1897 // Process phis from wide to narrow. Map wide phis to their truncation
1898 // so narrow phis can reuse them.
1899 for (PHINode *Phi : Phis) {
1900 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1901 if (Value *V = simplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
1902 return V;
1903 if (!SE.isSCEVable(PN->getType()))
1904 return nullptr;
1905 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1906 if (!Const)
1907 return nullptr;
1908 return Const->getValue();
1909 };
1910
1911 // Fold constant phis. They may be congruent to other constant phis and
1912 // would confuse the logic below that expects proper IVs.
1913 if (Value *V = SimplifyPHINode(Phi)) {
1914 if (V->getType() != Phi->getType())
1915 continue;
1916 SE.forgetValue(Phi);
1917 Phi->replaceAllUsesWith(V);
1918 DeadInsts.emplace_back(Phi);
1919 ++NumElim;
1920 SCEV_DEBUG_WITH_TYPE(DebugType,
1921 dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
1922 << '\n');
1923 continue;
1924 }
1925
1926 if (!SE.isSCEVable(Phi->getType()))
1927 continue;
1928
1929 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1930 if (!OrigPhiRef) {
1931 OrigPhiRef = Phi;
1932 if (Phi->getType()->isIntegerTy() && TTI &&
1933 TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1934 // Make sure we only rewrite using simple induction variables;
1935 // otherwise, we can make the trip count of a loop unanalyzable
1936 // to SCEV.
1937 const SCEV *PhiExpr = SE.getSCEV(Phi);
1938 if (isa<SCEVAddRecExpr>(PhiExpr)) {
1939 // This phi can be freely truncated to the narrowest phi type. Map the
1940 // truncated expression to it so it will be reused for narrow types.
1941 const SCEV *TruncExpr =
1942 SE.getTruncateExpr(PhiExpr, Phis.back()->getType());
1943 ExprToIVMap[TruncExpr] = Phi;
1944 }
1945 }
1946 continue;
1947 }
1948
1949 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1950 // sense.
1951 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1952 continue;
1953
1954 replaceCongruentIVInc(Phi, OrigPhiRef, L, DT, DeadInsts);
1955 SCEV_DEBUG_WITH_TYPE(DebugType,
1956 dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
1957 << '\n');
1959 DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
1960 ++NumElim;
1961 Value *NewIV = OrigPhiRef;
1962 if (OrigPhiRef->getType() != Phi->getType()) {
1963 IRBuilder<> Builder(L->getHeader(),
1964 L->getHeader()->getFirstInsertionPt());
1965 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1966 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1967 }
1968 Phi->replaceAllUsesWith(NewIV);
1969 DeadInsts.emplace_back(Phi);
1970 }
1971 return NumElim;
1972}
1973
1975 const Instruction *At,
1976 Loop *L) {
1977 using namespace llvm::PatternMatch;
1978
1979 SmallVector<BasicBlock *, 4> ExitingBlocks;
1980 L->getExitingBlocks(ExitingBlocks);
1981
1982 // Look for suitable value in simple conditions at the loop exits.
1983 for (BasicBlock *BB : ExitingBlocks) {
1984 CmpPredicate Pred;
1985 Instruction *LHS, *RHS;
1986
1987 if (!match(BB->getTerminator(),
1988 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1990 continue;
1991
1992 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1993 return true;
1994
1995 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1996 return true;
1997 }
1998
1999 // Use expand's logic which is used for reusing a previous Value in
2000 // ExprValueMap. Note that we don't currently model the cost of
2001 // needing to drop poison generating flags on the instruction if we
2002 // want to reuse it. We effectively assume that has zero cost.
2003 SmallVector<Instruction *> DropPoisonGeneratingInsts;
2004 return FindValueInExprValueMap(S, At, DropPoisonGeneratingInsts) != nullptr;
2005}
2006
2007template<typename T> static InstructionCost costAndCollectOperands(
2010 SmallVectorImpl<SCEVOperand> &Worklist) {
2011
2012 const T *S = cast<T>(WorkItem.S);
2013 InstructionCost Cost = 0;
2014 // Object to help map SCEV operands to expanded IR instructions.
2015 struct OperationIndices {
2016 OperationIndices(unsigned Opc, size_t min, size_t max) :
2017 Opcode(Opc), MinIdx(min), MaxIdx(max) { }
2018 unsigned Opcode;
2019 size_t MinIdx;
2020 size_t MaxIdx;
2021 };
2022
2023 // Collect the operations of all the instructions that will be needed to
2024 // expand the SCEVExpr. This is so that when we come to cost the operands,
2025 // we know what the generated user(s) will be.
2027
2028 auto CastCost = [&](unsigned Opcode) -> InstructionCost {
2029 Operations.emplace_back(Opcode, 0, 0);
2030 return TTI.getCastInstrCost(Opcode, S->getType(),
2031 S->getOperand(0)->getType(),
2033 };
2034
2035 auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
2036 unsigned MinIdx = 0,
2037 unsigned MaxIdx = 1) -> InstructionCost {
2038 Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2039 return NumRequired *
2040 TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
2041 };
2042
2043 auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
2044 unsigned MaxIdx) -> InstructionCost {
2045 Operations.emplace_back(Opcode, MinIdx, MaxIdx);
2046 Type *OpType = S->getType();
2047 return NumRequired * TTI.getCmpSelInstrCost(
2048 Opcode, OpType, CmpInst::makeCmpResultType(OpType),
2050 };
2051
2052 switch (S->getSCEVType()) {
2053 case scCouldNotCompute:
2054 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2055 case scUnknown:
2056 case scConstant:
2057 case scVScale:
2058 return 0;
2059 case scPtrToAddr:
2060 Cost = CastCost(Instruction::PtrToAddr);
2061 break;
2062 case scTruncate:
2063 Cost = CastCost(Instruction::Trunc);
2064 break;
2065 case scZeroExtend:
2066 Cost = CastCost(Instruction::ZExt);
2067 break;
2068 case scSignExtend:
2069 Cost = CastCost(Instruction::SExt);
2070 break;
2071 case scUDivExpr: {
2072 unsigned Opcode = Instruction::UDiv;
2073 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
2074 if (SC->getAPInt().isPowerOf2())
2075 Opcode = Instruction::LShr;
2076 Cost = ArithCost(Opcode, 1);
2077 break;
2078 }
2079 case scAddExpr:
2080 Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
2081 break;
2082 case scMulExpr: {
2083 // Match the actual expansion in visitMulExpr: multiply by -1 is
2084 // expanded as a negate (sub 0, x), and multiply by a power of 2 is
2085 // expanded as a shift. Only handle the common two-operand case with a
2086 // constant LHS; for everything else fall back to the pessimistic
2087 // all-multiplies estimate.
2088 // TODO: this is still pessimistic for the general case because of the
2089 // Bin Pow algorithm actually used by the expander, see
2090 // SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
2091 unsigned OpCode = Instruction::Mul;
2092 if (S->getNumOperands() == 2)
2093 if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(0))) {
2094 if (SC->getAPInt().isAllOnes()) // -1
2095 OpCode = Instruction::Sub;
2096 else if (SC->getAPInt().isPowerOf2())
2097 OpCode = Instruction::Shl;
2098 }
2099 Cost = ArithCost(OpCode, S->getNumOperands() - 1);
2100 break;
2101 }
2102 case scSMaxExpr:
2103 case scUMaxExpr:
2104 case scSMinExpr:
2105 case scUMinExpr:
2106 case scSequentialUMinExpr: {
2107 // FIXME: should this ask the cost for Intrinsic's?
2108 // The reduction tree.
2109 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
2110 Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
2111 switch (S->getSCEVType()) {
2112 case scSequentialUMinExpr: {
2113 // The safety net against poison.
2114 // FIXME: this is broken.
2115 Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
2116 Cost += ArithCost(Instruction::Or,
2117 S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
2118 Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
2119 break;
2120 }
2121 default:
2123 "Unhandled SCEV expression type?");
2124 break;
2125 }
2126 break;
2127 }
2128 case scAddRecExpr: {
2129 // Addrec expands to a phi and add per recurrence.
2130 unsigned NumRecurrences = S->getNumOperands() - 1;
2131 Cost += TTI.getCFInstrCost(Instruction::PHI, CostKind) * NumRecurrences;
2132 Cost +=
2133 TTI.getArithmeticInstrCost(Instruction::Add, S->getType(), CostKind) *
2134 NumRecurrences;
2135 // AR start is used in phi.
2136 Worklist.emplace_back(Instruction::PHI, 0, S->getOperand(0));
2137 // Other operands are used in add.
2138 for (const SCEV *Op : S->operands().drop_front())
2139 Worklist.emplace_back(Instruction::Add, 1, Op);
2140 break;
2141 }
2142 }
2143
2144 for (auto &CostOp : Operations) {
2145 for (auto SCEVOp : enumerate(S->operands())) {
2146 // Clamp the index to account for multiple IR operations being chained.
2147 size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
2148 size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
2149 Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
2150 }
2151 }
2152 return Cost;
2153}
2154
2155bool SCEVExpander::isHighCostExpansionHelper(
2156 const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
2157 InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
2159 SmallVectorImpl<SCEVOperand> &Worklist) {
2160 if (Cost > Budget)
2161 return true; // Already run out of budget, give up.
2162
2163 const SCEV *S = WorkItem.S;
2164 // Was the cost of expansion of this expression already accounted for?
2165 if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
2166 return false; // We have already accounted for this expression.
2167
2168 // If we can find an existing value for this scev available at the point "At"
2169 // then consider the expression cheap.
2170 if (hasRelatedExistingExpansion(S, &At, L))
2171 return false; // Consider the expression to be free.
2172
2174 L->getHeader()->getParent()->hasMinSize()
2177
2178 switch (S->getSCEVType()) {
2179 case scCouldNotCompute:
2180 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
2181 case scUnknown:
2182 case scVScale:
2183 // Assume to be zero-cost.
2184 return false;
2185 case scConstant: {
2186 // Only evalulate the costs of constants when optimizing for size.
2188 return false;
2189 const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
2190 Type *Ty = S->getType();
2192 WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
2193 return Cost > Budget;
2194 }
2195 case scTruncate:
2196 case scPtrToAddr:
2197 case scZeroExtend:
2198 case scSignExtend: {
2199 Cost +=
2201 return false; // Will answer upon next entry into this function.
2202 }
2203 case scUDivExpr: {
2204 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
2205 // HowManyLessThans produced to compute a precise expression, rather than a
2206 // UDiv from the user's code. If we can't find a UDiv in the code with some
2207 // simple searching, we need to account for it's cost.
2208
2209 // At the beginning of this function we already tried to find existing
2210 // value for plain 'S'. Now try to lookup 'S + 1' since it is common
2211 // pattern involving division. This is just a simple search heuristic.
2213 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
2214 return false; // Consider it to be free.
2215
2216 Cost +=
2218 return false; // Will answer upon next entry into this function.
2219 }
2220 case scAddExpr:
2221 case scMulExpr:
2222 case scUMaxExpr:
2223 case scSMaxExpr:
2224 case scUMinExpr:
2225 case scSMinExpr:
2226 case scSequentialUMinExpr: {
2227 assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
2228 "Nary expr should have more than 1 operand.");
2229 // The simple nary expr will require one less op (or pair of ops)
2230 // than the number of it's terms.
2231 Cost +=
2233 return Cost > Budget;
2234 }
2235 case scAddRecExpr: {
2236 assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
2237 "Polynomial should be at least linear");
2239 WorkItem, TTI, CostKind, Worklist);
2240 return Cost > Budget;
2241 }
2242 }
2243 llvm_unreachable("Unknown SCEV kind!");
2244}
2245
2247 Instruction *IP) {
2248 assert(IP);
2249 switch (Pred->getKind()) {
2254 case SCEVPredicate::P_Wrap: {
2255 auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
2256 return expandWrapPredicate(AddRecPred, IP);
2257 }
2258 }
2259 llvm_unreachable("Unknown SCEV predicate type");
2260}
2261
2263 Instruction *IP) {
2264 Value *Expr0 = expand(Pred->getLHS(), IP);
2265 Value *Expr1 = expand(Pred->getRHS(), IP);
2266
2267 Builder.SetInsertPoint(IP);
2268 auto InvPred = ICmpInst::getInversePredicate(Pred->getPredicate());
2269 auto *I = Builder.CreateICmp(InvPred, Expr0, Expr1, "ident.check");
2270 return I;
2271}
2272
2274 Instruction *Loc, bool Signed) {
2275 assert(AR->isAffine() && "Cannot generate RT check for "
2276 "non-affine expression");
2277
2278 // FIXME: It is highly suspicious that we're ignoring the predicates here.
2280 const SCEV *ExitCount =
2281 SE.getPredicatedSymbolicMaxBackedgeTakenCount(AR->getLoop(), Pred);
2282
2283 assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
2284
2285 const SCEV *Step = AR->getStepRecurrence(SE);
2286 const SCEV *Start = AR->getStart();
2287
2288 Type *ARTy = AR->getType();
2289 unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
2290 unsigned DstBits = SE.getTypeSizeInBits(ARTy);
2291
2292 // The expression {Start,+,Step} has nusw/nssw if
2293 // Step < 0, Start - |Step| * Backedge <= Start
2294 // Step >= 0, Start + |Step| * Backedge > Start
2295 // and |Step| * Backedge doesn't unsigned overflow.
2296
2297 Builder.SetInsertPoint(Loc);
2298 Value *TripCountVal = expand(ExitCount, Loc);
2299
2300 IntegerType *Ty =
2301 IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
2302
2303 Value *StepValue = expand(Step, Loc);
2304 Value *NegStepValue = expand(SE.getNegativeSCEV(Step), Loc);
2305 Value *StartValue = expand(Start, Loc);
2306
2307 ConstantInt *Zero =
2308 ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
2309
2310 Builder.SetInsertPoint(Loc);
2311 // Compute |Step|
2312 Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
2313 Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
2314
2315 // Compute |Step| * Backedge
2316 // Compute:
2317 // 1. Start + |Step| * Backedge < Start
2318 // 2. Start - |Step| * Backedge > Start
2319 //
2320 // And select either 1. or 2. depending on whether step is positive or
2321 // negative. If Step is known to be positive or negative, only create
2322 // either 1. or 2.
2323 auto ComputeEndCheck = [&]() -> Value * {
2324 // Get the backedge taken count and truncate or extended to the AR type.
2325 Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
2326
2327 Value *Mul = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, Ty,
2328 {AbsStep, TruncTripCount},
2329 /*FMFSource=*/nullptr, "mul");
2330 Value *MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
2331 Value *OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
2332
2333 Value *Add = nullptr, *Sub = nullptr;
2334 bool NeedPosCheck = !SE.isKnownNegative(Step);
2335 bool NeedNegCheck = !SE.isKnownPositive(Step);
2336
2337 if (isa<PointerType>(ARTy)) {
2338 Value *NegMulV = Builder.CreateNeg(MulV);
2339 if (NeedPosCheck)
2340 Add = Builder.CreatePtrAdd(StartValue, MulV);
2341 if (NeedNegCheck)
2342 Sub = Builder.CreatePtrAdd(StartValue, NegMulV);
2343 } else {
2344 if (NeedPosCheck)
2345 Add = Builder.CreateAdd(StartValue, MulV);
2346 if (NeedNegCheck)
2347 Sub = Builder.CreateSub(StartValue, MulV);
2348 }
2349
2350 Value *EndCompareLT = nullptr;
2351 Value *EndCompareGT = nullptr;
2352 Value *EndCheck = nullptr;
2353 if (NeedPosCheck)
2354 EndCheck = EndCompareLT = Builder.CreateICmp(
2356 if (NeedNegCheck)
2357 EndCheck = EndCompareGT = Builder.CreateICmp(
2359 if (NeedPosCheck && NeedNegCheck) {
2360 // Select the answer based on the sign of Step.
2361 EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
2362 }
2363 return Builder.CreateOr(EndCheck, OfMul);
2364 };
2365 Value *EndCheck = ComputeEndCheck();
2366
2367 // If the backedge taken count type is larger than the AR type,
2368 // check that we don't drop any bits by truncating it. If we are
2369 // dropping bits, then we have overflow (unless the step is zero).
2370 if (SrcBits > DstBits) {
2371 auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
2372 auto *BackedgeCheck =
2373 Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
2374 ConstantInt::get(Loc->getContext(), MaxVal));
2375 BackedgeCheck = Builder.CreateAnd(
2376 BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
2377
2378 EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
2379 }
2380
2381 return EndCheck;
2382}
2383
2385 Instruction *IP) {
2386 const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
2387 Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
2388
2389 // Add a check for NUSW
2390 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
2391 NUSWCheck = generateOverflowCheck(A, IP, false);
2392
2393 // Add a check for NSSW
2394 if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
2395 NSSWCheck = generateOverflowCheck(A, IP, true);
2396
2397 if (NUSWCheck && NSSWCheck)
2398 return Builder.CreateOr(NUSWCheck, NSSWCheck);
2399
2400 if (NUSWCheck)
2401 return NUSWCheck;
2402
2403 if (NSSWCheck)
2404 return NSSWCheck;
2405
2406 return ConstantInt::getFalse(IP->getContext());
2407}
2408
2410 Instruction *IP) {
2411 // Loop over all checks in this set.
2412 SmallVector<Value *> Checks;
2413 for (const auto *Pred : Union->getPredicates()) {
2414 Checks.push_back(expandCodeForPredicate(Pred, IP));
2415 Builder.SetInsertPoint(IP);
2416 }
2417
2418 if (Checks.empty())
2419 return ConstantInt::getFalse(IP->getContext());
2420 return Builder.CreateOr(Checks);
2421}
2422
2423Value *SCEVExpander::fixupLCSSAFormFor(Value *V) {
2424 auto *DefI = dyn_cast<Instruction>(V);
2425 if (!PreserveLCSSA || !DefI)
2426 return V;
2427
2428 BasicBlock::iterator InsertPt = Builder.GetInsertPoint();
2429 Loop *DefLoop = SE.LI.getLoopFor(DefI->getParent());
2430 Loop *UseLoop = SE.LI.getLoopFor(InsertPt->getParent());
2431 if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
2432 return V;
2433
2434 // Create a temporary instruction to at the current insertion point, so we
2435 // can hand it off to the helper to create LCSSA PHIs if required for the
2436 // new use.
2437 // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
2438 // would accept a insertion point and return an LCSSA phi for that
2439 // insertion point, so there is no need to insert & remove the temporary
2440 // instruction.
2441 Type *ToTy;
2442 if (DefI->getType()->isIntegerTy())
2443 ToTy = PointerType::get(DefI->getContext(), 0);
2444 else
2445 ToTy = Type::getInt32Ty(DefI->getContext());
2446 Instruction *User =
2447 CastInst::CreateBitOrPointerCast(DefI, ToTy, "tmp.lcssa.user", InsertPt);
2448 llvm::scope_exit RemoveUserOnExit([User]() { User->eraseFromParent(); });
2449
2451 ToUpdate.push_back(DefI);
2452 SmallVector<PHINode *, 16> PHIsToRemove;
2453 SmallVector<PHINode *, 16> InsertedPHIs;
2454 formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, &PHIsToRemove,
2455 &InsertedPHIs);
2456 for (PHINode *PN : InsertedPHIs)
2457 rememberInstruction(PN);
2458 for (PHINode *PN : PHIsToRemove) {
2459 if (!PN->use_empty())
2460 continue;
2461 InsertedValues.erase(PN);
2462 InsertedPostIncValues.erase(PN);
2463 PN->eraseFromParent();
2464 }
2465
2466 return User->getOperand(0);
2467}
2468
2469namespace {
2470// Search for a SCEV subexpression that is not safe to expand. Any expression
2471// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
2472// UDiv expressions. We don't know if the UDiv is derived from an IR divide
2473// instruction, but the important thing is that we prove the denominator is
2474// nonzero before expansion.
2475//
2476// IVUsers already checks that IV-derived expressions are safe. So this check is
2477// only needed when the expression includes some subexpression that is not IV
2478// derived.
2479//
2480// Currently, we only allow division by a value provably non-zero here.
2481//
2482// We cannot generally expand recurrences unless the step dominates the loop
2483// header. The expander handles the special case of affine recurrences by
2484// scaling the recurrence outside the loop, but this technique isn't generally
2485// applicable. Expanding a nested recurrence outside a loop requires computing
2486// binomial coefficients. This could be done, but the recurrence has to be in a
2487// perfectly reduced form, which can't be guaranteed.
2488struct SCEVFindUnsafe {
2489 ScalarEvolution &SE;
2490 bool CanonicalMode;
2491 bool IsUnsafe = false;
2492
2493 SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
2494 : SE(SE), CanonicalMode(CanonicalMode) {}
2495
2496 bool follow(const SCEV *S) {
2497 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2498 if (!SE.isKnownNonZero(D->getRHS()) ||
2499 !SE.isGuaranteedNotToBePoison(D->getRHS())) {
2500 IsUnsafe = true;
2501 return false;
2502 }
2503 }
2504 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2505 // For non-affine addrecs or in non-canonical mode we need a preheader
2506 // to insert into.
2507 if (!AR->getLoop()->getLoopPreheader() &&
2508 (!CanonicalMode || !AR->isAffine())) {
2509 IsUnsafe = true;
2510 return false;
2511 }
2512 }
2513 return true;
2514 }
2515 bool isDone() const { return IsUnsafe; }
2516};
2517} // namespace
2518
2520 SCEVFindUnsafe Search(SE, CanonicalMode);
2521 visitAll(S, Search);
2522 return !Search.IsUnsafe;
2523}
2524
2526 const Instruction *InsertionPoint) const {
2527 if (!isSafeToExpand(S))
2528 return false;
2529 // We have to prove that the expanded site of S dominates InsertionPoint.
2530 // This is easy when not in the same block, but hard when S is an instruction
2531 // to be expanded somewhere inside the same block as our insertion point.
2532 // What we really need here is something analogous to an OrderedBasicBlock,
2533 // but for the moment, we paper over the problem by handling two common and
2534 // cheap to check cases.
2535 if (SE.properlyDominates(S, InsertionPoint->getParent()))
2536 return true;
2537 if (SE.dominates(S, InsertionPoint->getParent())) {
2538 if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
2539 return true;
2540 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
2541 if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
2542 return true;
2543 }
2544 return false;
2545}
2546
2548 // Result is used, nothing to remove.
2549 if (ResultUsed)
2550 return;
2551
2552 // Restore original poison flags.
2553 for (auto [I, Flags] : Expander.OrigFlags)
2554 Flags.apply(I);
2555
2556 auto InsertedInstructions = Expander.getAllInsertedInstructions();
2557#ifndef NDEBUG
2559 InsertedInstructions);
2560 (void)InsertedSet;
2561#endif
2562 // Remove sets with value handles.
2563 Expander.clear();
2564
2565 // Remove all inserted instructions.
2566 for (Instruction *I : reverse(InsertedInstructions)) {
2567#ifndef NDEBUG
2568 assert(all_of(I->users(),
2569 [&InsertedSet](Value *U) {
2570 return InsertedSet.contains(cast<Instruction>(U));
2571 }) &&
2572 "removed instruction should only be used by instructions inserted "
2573 "during expansion");
2574#endif
2575 assert(!I->getType()->isVoidTy() &&
2576 "inserted instruction should have non-void types");
2577 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
2578 I->eraseFromParent();
2579 }
2580}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< OutputCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(OutputCostKind::RecipThroughput), cl::values(clEnumValN(OutputCostKind::RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(OutputCostKind::Latency, "latency", "Instruction latency"), clEnumValN(OutputCostKind::CodeSize, "code-size", "Code size"), clEnumValN(OutputCostKind::SizeAndLatency, "size-latency", "Code size and latency"), clEnumValN(OutputCostKind::All, "all", "Print all cost kinds")))
static Expected< BitVector > expand(StringRef S, StringRef Original)
Hexagon Common GEP
Hexagon Hardware Loops
#define I(x, y, z)
Definition MD5.cpp:57
#define T
MachineInstr unsigned OpIdx
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static const Loop * PickMostRelevantLoop(const Loop *A, const Loop *B, DominatorTree &DT)
PickMostRelevantLoop - Given two loops pick the one that's most relevant for SCEV expansion.
static InstructionCost costAndCollectOperands(const SCEVOperand &WorkItem, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, SmallVectorImpl< SCEVOperand > &Worklist)
static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR)
static bool canBeCheaplyTransformed(ScalarEvolution &SE, const SCEVAddRecExpr *Phi, const SCEVAddRecExpr *Requested, bool &InvertStep)
Check whether we can cheaply express the requested SCEV in terms of the available PHI SCEV by truncat...
#define SCEV_DEBUG_WITH_TYPE(TYPE, X)
static bool canReuseCastForPtrToAddr(const CastInst *CI, Type *Ty, const DataLayout &DL)
Return true if CI computes the same value as a ptrtoaddr of its pointer operand to Ty.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
unsigned logBase2() const
Definition APInt.h:1786
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Type * getSrcTy() const
Return the source type, as a convenience.
Definition InstrTypes.h:679
static LLVM_ABI Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags none()
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
ICmpInst::Predicate getPredicate() const
Returns the comparison predicate underlying the intrinsic.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
bool isComplete() const
If the PHI node is complete which means all of its parent's predecessors have incoming value in this ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
const APInt & getAPInt() const
LLVM_ABI Value * generateOverflowCheck(const SCEVAddRecExpr *AR, Instruction *Loc, bool Signed)
Generates code that evaluates if the AR expression will overflow.
LLVM_ABI bool hasRelatedExistingExpansion(const SCEV *S, const Instruction *At, Loop *L)
Determine whether there is an existing expansion of S that can be reused.
SmallVector< Instruction *, 32 > getAllInsertedInstructions() const
Return a vector containing all instructions inserted during expansion.
LLVM_ABI bool isSafeToExpand(const SCEV *S) const
Return true if the given expression is safe to expand in the sense that all materialized values are s...
LLVM_ABI bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
LLVM_ABI unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
static LLVM_ABI void dropPoisonGeneratingAnnotationsAndReinfer(ScalarEvolution &SE, Instruction *I)
Drop poison-generating flags from I, then try re-infer via SCEV.
LLVM_ABI Value * expandUnionPredicate(const SCEVUnionPredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
static LLVM_ABI CastInst * findReusableCastForPtrToAddr(Value *PtrOp, Type *Ty, const DataLayout &DL, function_ref< bool(const CastInst *)> Dominates)
Find an existing cast among PtrOp's users that computes the same value as a ptrtoaddr of PtrOp to Ty ...
LLVM_ABI bool hoistIVInc(Instruction *IncV, Instruction *InsertPos, bool RecomputePoisonFlags=false)
Utility for hoisting IncV (with all subexpressions requried for its computation) before InsertPos.
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
static LLVM_ABI bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi, PHINode *WidePhi, Instruction *OrigInc, Instruction *WideInc)
Return true if both increments directly increment the corresponding IV PHI nodes and have the same op...
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
LLVM_ABI Value * expandComparePredicate(const SCEVComparePredicate *Pred, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Value * expandWrapPredicate(const SCEVWrapPredicate *P, Instruction *Loc)
A specialized variant of expandCodeForPredicate, handling the case when we are expanding code for a S...
LLVM_ABI Instruction * getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale)
Return the induction variable increment's IV operand.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
LLVM_ABI BasicBlock::iterator findInsertPointAfter(Instruction *I, Instruction *MustDominate) const
Returns a suitable insert point after I, that dominates MustDominate.
void setInsertPoint(Instruction *IP)
Set the current insertion point.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an assumption made on an AddRec expression.
This class represents an analyzed expression in the program.
SCEVNoWrapFlags NoWrapFlags
static constexpr auto FlagNUW
static constexpr auto FlagAnyWrap
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
Type * getType() const
Return the LLVM type of this SCEV expression.
SCEVTypes getSCEVType() const
static constexpr auto FlagNW
The main scalar evolution driver.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
static LLVM_ABI bool isGuaranteedNotToBePoison(const SCEV *Op)
Returns true if Op is guaranteed to not be poison.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx, const APInt &Imm, Type *Ty, TargetCostKind CostKind, Instruction *Inst=nullptr) const
Return the expected cost of materialization for the given integer immediate of the specified type for...
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ None
The cast is not used with a load/store of any kind.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr bool any(E Val)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
cst_pred_ty< is_all_ones > m_scev_AllOnes()
Match an integer with all bits set.
SCEVUnaryExpr_match< SCEVPtrToAddrExpr, Op0_t > m_scev_PtrToAddr(const Op0_t &Op0)
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
SCEVBinaryExpr_match< SCEVUDivExpr, Op0_t, Op1_t > m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1)
match_bind< const SCEVAddExpr > m_scev_Add(const SCEVAddExpr *&V)
SCEVURem_match< Op0_t, Op1_t > m_scev_URem(Op0_t LHS, Op1_t RHS, ScalarEvolution &SE)
Match the mathematical pattern A - (A / B) * B, where A and B can be arbitrary expressions.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void visitAll(const SCEV *Root, SV &Visitor)
Use SCEVTraversal to visit all nodes in the given expression tree.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
void stable_sort(R &&Range)
Definition STLExtras.h:2116
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
auto pred_size(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE, bool CheckInvertible=true)
Normalize S to be post-increment for all loops present in Loops.
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
constexpr unsigned BitWidth
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
Definition LCSSA.cpp:328
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
SmallPtrSet< const Loop *, 2 > PostIncLoopSet
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
SCEVUseT< const SCEV * > SCEVUse
bool SCEVExprContains(const SCEV *Root, PredTy Pred)
Return true if any node in Root satisfies the predicate Pred.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
LLVM_ABI void apply(Instruction *I)
LLVM_ABI PoisonFlags(const Instruction *I)
struct for holding enough information to help calculate the cost of the given SCEV when expanded into...
const SCEV * S
The SCEV operand to be costed.
unsigned ParentOpcode
LLVM instruction opcode that uses the operand.
int OperandIdx
The use index of an expanded instruction.
SCEVNoWrapFlags getNoWrapFlags(SCEVNoWrapFlags Mask=SCEVNoWrapFlags::NoWrapMask) const
Return the no-wrap flags for this SCEVUse, which is the union of the use-specific flags and the under...