LLVM 24.0.0git
ScalarEvolutionExpander.h
Go to the documentation of this file.
1//===---- llvm/Analysis/ScalarEvolutionExpander.h - SCEV Exprs --*- C++ -*-===//
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 defines the classes used to generate code from scalar expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_UTILS_SCALAREVOLUTIONEXPANDER_H
14#define LLVM_TRANSFORMS_UTILS_SCALAREVOLUTIONEXPANDER_H
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
24#include "llvm/IR/IRBuilder.h"
25#include "llvm/IR/ValueHandle.h"
29
30namespace llvm {
32
33/// struct for holding enough information to help calculate the cost of the
34/// given SCEV when expanded into IR.
36 explicit SCEVOperand(unsigned Opc, int Idx, const SCEV *S) :
37 ParentOpcode(Opc), OperandIdx(Idx), S(S) { }
38 /// LLVM instruction opcode that uses the operand.
39 unsigned ParentOpcode;
40 /// The use index of an expanded instruction.
42 /// The SCEV operand to be costed.
43 const SCEV* S;
44};
45
47 unsigned NUW : 1;
48 unsigned NSW : 1;
49 unsigned Exact : 1;
50 unsigned Disjoint : 1;
51 unsigned NNeg : 1;
52 unsigned SameSign : 1;
54
57};
58
59/// This class uses information about analyze scalars to rewrite expressions
60/// in canonical form.
61///
62/// Clients should create an instance of this class when rewriting is needed,
63/// and destroy it when finished to allow the release of the associated
64/// memory.
65class SCEVExpander : public SCEVUseVisitor<SCEVExpander, Value *> {
66 friend class SCEVExpanderCleaner;
67
69 const DataLayout &DL;
70
71 // New instructions receive a name to identify them with the current pass.
72 const char *IVName;
73
74 /// Indicates whether LCSSA phis should be created for inserted values.
75 bool PreserveLCSSA;
76
77 // InsertedExpressions caches Values for reuse, so must track RAUW.
79 InsertedExpressions;
80
81 // InsertedOverflowChecks caches Values for reuse, so must track RAUW.
83 std::pair<TrackingVH<Value>, TrackingVH<Value>>>
84 InsertedOverflowChecks;
85
86 // InsertedValues only flags inserted instructions so needs no RAUW.
87 DenseSet<AssertingVH<Value>> InsertedValues;
88 DenseSet<AssertingVH<Value>> InsertedPostIncValues;
89
90 /// Keep track of the existing IR values re-used during expansion.
91 /// FIXME: Ideally re-used instructions would not be added to
92 /// InsertedValues/InsertedPostIncValues.
93 SmallPtrSet<Value *, 16> ReusedValues;
94
95 /// Original flags of instructions for which they were modified. Used
96 /// by SCEVExpanderCleaner to undo changes.
98
99 // The induction variables generated.
100 SmallVector<WeakVH, 2> InsertedIVs;
101
102 /// A memoization of the "relevant" loop for a given SCEV.
104
105 /// Addrecs referring to any of the given loops are expanded in post-inc
106 /// mode. For example, expanding {1,+,1}<L> in post-inc mode returns the add
107 /// instruction that adds one to the phi for {0,+,1}<L>, as opposed to a new
108 /// phi starting at 1. This is only supported in non-canonical mode.
109 PostIncLoopSet PostIncLoops;
110
111 /// When this is non-null, addrecs expanded in the loop it indicates should
112 /// be inserted with increments at IVIncInsertPos.
113 const Loop *IVIncInsertLoop;
114
115 /// When expanding addrecs in the IVIncInsertLoop loop, insert the IV
116 /// increment at this position.
117 Instruction *IVIncInsertPos;
118
119 /// Phis that complete an IV chain. Reuse
121
122 /// When true, SCEVExpander tries to expand expressions in "canonical" form.
123 /// When false, expressions are expanded in a more literal form.
124 ///
125 /// In "canonical" form addrecs are expanded as arithmetic based on a
126 /// canonical induction variable. Note that CanonicalMode doesn't guarantee
127 /// that all expressions are expanded in "canonical" form. For some
128 /// expressions literal mode can be preferred.
129 bool CanonicalMode;
130
131 /// When invoked from LSR, the expander is in "strength reduction" mode. The
132 /// only difference is that phi's are only reused if they are already in
133 /// "expanded" form.
134 bool LSRMode;
135
136 /// When true, rewrite any divisors of UDiv expressions that may be 0 to
137 /// umax(Divisor, 1) to avoid introducing UB. If the divisor may be poison,
138 /// freeze it first.
139 bool SafeUDivMode = false;
140
142 BuilderType Builder;
143
144 // RAII object that stores the current insertion point and restores it when
145 // the object is destroyed. This includes the debug location. Duplicated
146 // from InsertPointGuard to add SetInsertPoint() which is used to updated
147 // InsertPointGuards stack when insert points are moved during SCEV
148 // expansion.
149 class SCEVInsertPointGuard {
150 IRBuilderBase &Builder;
153 DebugLoc DbgLoc;
154 SCEVExpander *SE;
155
156 SCEVInsertPointGuard(const SCEVInsertPointGuard &) = delete;
157 SCEVInsertPointGuard &operator=(const SCEVInsertPointGuard &) = delete;
158
159 public:
160 SCEVInsertPointGuard(IRBuilderBase &B, SCEVExpander *SE)
161 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
162 DbgLoc(B.getCurrentDebugLocation()), SE(SE) {
163 SE->InsertPointGuards.push_back(this);
164 }
165
166 ~SCEVInsertPointGuard() {
167 // These guards should always created/destroyed in FIFO order since they
168 // are used to guard lexically scoped blocks of code in
169 // ScalarEvolutionExpander.
170 assert(SE->InsertPointGuards.back() == this);
171 SE->InsertPointGuards.pop_back();
172 Builder.restoreIP(IRBuilderBase::InsertPoint(Block, Point));
173 Builder.SetCurrentDebugLocation(DbgLoc);
174 }
175
176 BasicBlock::iterator GetInsertPoint() const { return Point; }
177 void SetInsertPoint(BasicBlock::iterator I) { Point = I; }
178 };
179
180 /// Stack of pointers to saved insert points, used to keep insert points
181 /// consistent when instructions are moved.
183
184#if LLVM_ENABLE_ABI_BREAKING_CHECKS
185 const char *DebugType;
186#endif
187
188 friend struct SCEVUseVisitor<SCEVExpander, Value *>;
189
190public:
191 /// Construct a SCEVExpander in "canonical" mode.
192 explicit SCEVExpander(ScalarEvolution &SE, const char *Name,
193 bool PreserveLCSSA = true)
194 : SE(SE), DL(SE.getDataLayout()), IVName(Name),
195 PreserveLCSSA(PreserveLCSSA), IVIncInsertLoop(nullptr),
196 IVIncInsertPos(nullptr), CanonicalMode(true), LSRMode(false),
197 Builder(SE.getContext(), InstSimplifyFolder(DL),
199 [this](Instruction *I) { rememberInstruction(I); })) {
200#if LLVM_ENABLE_ABI_BREAKING_CHECKS
201 DebugType = "";
202#endif
203 }
204
206 // Make sure the insert point guard stack is consistent.
207 assert(InsertPointGuards.empty());
208 }
209
210#if LLVM_ENABLE_ABI_BREAKING_CHECKS
211 void setDebugType(const char *s) { DebugType = s; }
212#endif
213
214 /// Erase the contents of the InsertedExpressions map so that users trying
215 /// to expand the same expression into multiple BasicBlocks or different
216 /// places within the same BasicBlock can do so.
217 void clear() {
218 InsertedExpressions.clear();
219 InsertedOverflowChecks.clear();
220 InsertedValues.clear();
221 InsertedPostIncValues.clear();
222 ReusedValues.clear();
223 OrigFlags.clear();
224 ChainedPhis.clear();
225 InsertedIVs.clear();
226 }
227
228 ScalarEvolution *getSE() { return &SE; }
229 const SmallVectorImpl<WeakVH> &getInsertedIVs() const { return InsertedIVs; }
230
231 /// Return a vector containing all instructions inserted during expansion.
234 for (const auto &VH : InsertedValues) {
235 Value *V = VH;
236 if (ReusedValues.contains(V))
237 continue;
238 if (auto *Inst = dyn_cast<Instruction>(V))
239 Result.push_back(Inst);
240 }
241 for (const auto &VH : InsertedPostIncValues) {
242 Value *V = VH;
243 if (ReusedValues.contains(V))
244 continue;
245 if (auto *Inst = dyn_cast<Instruction>(V))
246 Result.push_back(Inst);
247 }
248
249 return Result;
250 }
251
252 /// Return true for expressions that can't be evaluated at runtime
253 /// within given \b Budget.
254 ///
255 /// \p At is a parameter which specifies point in code where user is going to
256 /// expand these expressions. Sometimes this knowledge can lead to
257 /// a less pessimistic cost estimation.
259 unsigned Budget, const TargetTransformInfo *TTI,
260 const Instruction *At) {
261 assert(TTI && "This function requires TTI to be provided.");
262 assert(At && "This function requires At instruction to be provided.");
263 if (!TTI) // In assert-less builds, avoid crashing
264 return true; // by always claiming to be high-cost.
268 unsigned ScaledBudget = Budget * TargetTransformInfo::TCC_Basic;
269 for (auto *Expr : Exprs)
270 Worklist.emplace_back(-1, -1, Expr);
271 while (!Worklist.empty()) {
272 const SCEVOperand WorkItem = Worklist.pop_back_val();
273 if (isHighCostExpansionHelper(WorkItem, L, *At, Cost, ScaledBudget, *TTI,
274 Processed, Worklist))
275 return true;
276 }
277 assert(Cost <= ScaledBudget && "Should have returned from inner loop.");
278 return false;
279 }
280
281 /// Return the induction variable increment's IV operand.
283 getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale);
284
285 /// Utility for hoisting \p IncV (with all subexpressions requried for its
286 /// computation) before \p InsertPos. If \p RecomputePoisonFlags is set, drops
287 /// all poison-generating flags from instructions being hoisted and tries to
288 /// re-infer them in the new location. It should be used when we are going to
289 /// introduce a new use in the new position that didn't exist before, and may
290 /// trigger new UB in case of poison.
291 LLVM_ABI bool hoistIVInc(Instruction *IncV, Instruction *InsertPos,
292 bool RecomputePoisonFlags = false);
293
294 /// Return true if both increments directly increment the corresponding IV PHI
295 /// nodes and have the same opcode. It is not safe to re-use the flags from
296 /// the original increment, if it is more complex and SCEV expansion may have
297 /// yielded a more simplified wider increment.
299 PHINode *WidePhi,
300 Instruction *OrigInc,
301 Instruction *WideInc);
302
303 /// replace congruent phis with their most canonical representative. Return
304 /// the number of phis eliminated.
305 LLVM_ABI unsigned
308 const TargetTransformInfo *TTI = nullptr);
309
310 /// Return true if the given expression is safe to expand in the sense that
311 /// all materialized values are safe to speculate anywhere their operands are
312 /// defined, and the expander is capable of expanding the expression.
313 LLVM_ABI bool isSafeToExpand(const SCEV *S) const;
314
315 /// Return true if the given expression is safe to expand in the sense that
316 /// all materialized values are defined and safe to speculate at the specified
317 /// location and their operands are defined at this location.
318 LLVM_ABI bool isSafeToExpandAt(const SCEV *S,
319 const Instruction *InsertionPoint) const;
320
321 /// Drop poison-generating flags from \p I, then try re-infer via SCEV.
322 LLVM_ABI static void
324 Instruction *I);
325
326 /// Find an existing cast among \p PtrOp's users that computes the same value
327 /// as a `ptrtoaddr` of \p PtrOp to \p Ty and can be reused when expanding
328 /// ptrtoaddr.
329 LLVM_ABI static CastInst *
331 function_ref<bool(const CastInst *)> Dominates);
332
333 /// Insert code to directly compute the specified SCEV expression into the
334 /// program. The code is inserted into the specified block.
337 return expandCodeFor(SH, Ty, I->getIterator());
338 }
339
340 /// Insert code to directly compute the specified SCEV expression into the
341 /// program. The code is inserted into the SCEVExpander's current
342 /// insertion point. If a type is specified, the result will be expanded to
343 /// have that type, with a cast if necessary.
344 LLVM_ABI Value *expandCodeFor(SCEVUse SH, Type *Ty = nullptr);
345
346 /// Generates a code sequence that evaluates this predicate. The inserted
347 /// instructions will be at position \p Loc. The result will be of type i1
348 /// and will have a value of 0 when the predicate is false and 1 otherwise.
351
352 /// A specialized variant of expandCodeForPredicate, handling the case when
353 /// we are expanding code for a SCEVComparePredicate.
356
357 /// Generates code that evaluates if the \p AR expression will overflow.
359 Instruction *Loc, bool Signed);
360
361 /// A specialized variant of expandCodeForPredicate, handling the case when
362 /// we are expanding code for a SCEVWrapPredicate.
365
366 /// A specialized variant of expandCodeForPredicate, handling the case when
367 /// we are expanding code for a SCEVUnionPredicate.
370
371 /// Set the current IV increment loop and position.
372 void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
373 assert(!CanonicalMode &&
374 "IV increment positions are not supported in CanonicalMode");
375 IVIncInsertLoop = L;
376 IVIncInsertPos = Pos;
377 }
378
379 /// Enable post-inc expansion for addrecs referring to the given
380 /// loops. Post-inc expansion is only supported in non-canonical mode.
381 void setPostInc(const PostIncLoopSet &L) {
382 assert(!CanonicalMode &&
383 "Post-inc expansion is not supported in CanonicalMode");
384 PostIncLoops = L;
385 }
386
387 /// Disable all post-inc expansion.
389 PostIncLoops.clear();
390
391 // When we change the post-inc loop set, cached expansions may no
392 // longer be valid.
393 InsertedPostIncValues.clear();
394 }
395
396 /// Disable the behavior of expanding expressions in canonical form rather
397 /// than in a more literal form. Non-canonical mode is useful for late
398 /// optimization passes.
399 void disableCanonicalMode() { CanonicalMode = false; }
400
401 void enableLSRMode() { LSRMode = true; }
402
403 /// Set the current insertion point. This is useful if multiple calls to
404 /// expandCodeFor() are going to be made with the same insert point and the
405 /// insert point may be moved during one of the expansions (e.g. if the
406 /// insert point is not a block terminator).
408 assert(IP);
409 Builder.SetInsertPoint(IP);
410 }
411
413 Builder.SetInsertPoint(IP->getParent(), IP);
414 }
415
416 /// Clear the current insertion point. This is useful if the instruction
417 /// that had been serving as the insertion point may have been deleted.
418 void clearInsertPoint() { Builder.ClearInsertionPoint(); }
419
420 /// Set location information used by debugging information.
422 Builder.SetCurrentDebugLocation(std::move(L));
423 }
424
425 /// Get location information used by debugging information.
427 return Builder.getCurrentDebugLocation();
428 }
429
430 /// Return true if the specified instruction was inserted by the code
431 /// rewriter. If so, the client should not modify the instruction. Note that
432 /// this also includes instructions re-used during expansion.
434 return InsertedValues.count(I) || InsertedPostIncValues.count(I);
435 }
436
437 void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
438
439 /// Determine whether there is an existing expansion of S that can be reused.
440 /// This is used to check whether S can be expanded cheaply.
441 ///
442 /// L is a hint which tells in which loop to look for the suitable value.
443 ///
444 /// Note that this function does not perform an exhaustive search. I.e if it
445 /// didn't find any value it does not mean that there is no such value.
447 const Instruction *At, Loop *L);
448
449 /// Returns a suitable insert point after \p I, that dominates \p
450 /// MustDominate. Skips instructions inserted by the expander.
452 findInsertPointAfter(Instruction *I, Instruction *MustDominate) const;
453
454 /// Remove inserted instructions that are dead, e.g. due to InstSimplifyFolder
455 /// simplifications. \p Root is assumed to be used and won't be removed.
457
458private:
459 LLVMContext &getContext() const { return SE.getContext(); }
460
461 /// Recursive helper function for isHighCostExpansion.
462 LLVM_ABI bool
463 isHighCostExpansionHelper(const SCEVOperand &WorkItem, Loop *L,
464 const Instruction &At, InstructionCost &Cost,
465 unsigned Budget, const TargetTransformInfo &TTI,
466 SmallPtrSetImpl<const SCEV *> &Processed,
467 SmallVectorImpl<SCEVOperand> &Worklist);
468
469 /// Insert the specified binary operator, doing a small amount of work to
470 /// avoid inserting an obviously redundant operation, and hoisting to an
471 /// outer loop when the opportunity is there and it is safe.
472 Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
473 SCEV::NoWrapFlags Flags, bool IsSafeToHoist);
474
475 /// We want to cast \p V. What would be the best place for such a cast?
476 BasicBlock::iterator GetOptimalInsertionPointForCastOf(Value *V) const;
477
478 /// Arrange for there to be a cast of V to Ty at IP, reusing an existing
479 /// cast if a suitable one exists, moving an existing cast if a suitable one
480 /// exists but isn't in the right place, or creating a new one.
481 Value *ReuseOrCreateCast(Value *V, Type *Ty, Instruction::CastOps Op,
483
484 /// Insert a cast of V to the specified type, which must be possible with a
485 /// noop cast, doing what we can to share the casts.
486 Value *InsertNoopCastOfTo(Value *V, Type *Ty);
487
488 /// Expand a SCEVAddExpr with a pointer type into a GEP instead of using
489 /// ptrtoint+arithmetic+inttoptr.
490 Value *expandAddToGEP(const SCEV *Op, Value *V, SCEV::NoWrapFlags Flags);
491
492 /// Find a previous Value in ExprValueMap for expand.
493 /// DropPoisonGeneratingInsts is populated with instructions for which
494 /// poison-generating flags must be dropped if the value is reused.
495 Value *FindValueInExprValueMap(
496 SCEVUse S, const Instruction *InsertPt,
497 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts);
498
499 LLVM_ABI Value *expand(SCEVUse S);
502 return expand(S);
503 }
504 Value *expand(SCEVUse S, Instruction *I) {
506 return expand(S);
507 }
508
509 /// Determine the most "relevant" loop for the given SCEV.
510 const Loop *getRelevantLoop(const SCEV *);
511
512 Value *expandMinMaxExpr(SCEVUseT<const SCEVNAryExpr *> S,
513 Intrinsic::ID IntrinID, Twine Name,
514 bool IsSequential = false);
515
516 Value *visitConstant(SCEVUseT<const SCEVConstant *> S) {
517 return S->getValue();
518 }
519
520 Value *visitVScale(SCEVUseT<const SCEVVScale *> S);
521
522 Value *visitPtrToAddrExpr(SCEVUseT<const SCEVPtrToAddrExpr *> S);
523
524 Value *visitTruncateExpr(SCEVUseT<const SCEVTruncateExpr *> S);
525
526 Value *visitZeroExtendExpr(SCEVUseT<const SCEVZeroExtendExpr *> S);
527
528 Value *visitSignExtendExpr(SCEVUseT<const SCEVSignExtendExpr *> S);
529
530 Value *visitAddExpr(SCEVUseT<const SCEVAddExpr *> S);
531
532 Value *visitMulExpr(SCEVUseT<const SCEVMulExpr *> S);
533
534 Value *visitUDivExpr(SCEVUseT<const SCEVUDivExpr *> S);
535
536 Value *visitAddRecExpr(SCEVUseT<const SCEVAddRecExpr *> S);
537
538 Value *visitSMaxExpr(SCEVUseT<const SCEVSMaxExpr *> S);
539
540 Value *visitUMaxExpr(SCEVUseT<const SCEVUMaxExpr *> S);
541
542 Value *visitSMinExpr(SCEVUseT<const SCEVSMinExpr *> S);
543
544 Value *visitUMinExpr(SCEVUseT<const SCEVUMinExpr *> S);
545
546 Value *visitSequentialUMinExpr(SCEVUseT<const SCEVSequentialUMinExpr *> S);
547
548 Value *visitUnknown(SCEVUseT<const SCEVUnknown *> S) { return S->getValue(); }
549
550 LLVM_ABI void rememberInstruction(Value *I);
551
552 void rememberFlags(Instruction *I);
553
554 bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
555
556 bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
557
558 Value *tryToReuseLCSSAPhi(SCEVUseT<const SCEVAddRecExpr *> S);
559 Value *expandAddRecExprLiterally(SCEVUseT<const SCEVAddRecExpr *> S);
560 PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
561 const Loop *L, Type *&TruncTy,
562 bool &InvertStep);
563 Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
564 bool useSubtract);
565
566 void fixupInsertPoints(Instruction *I);
567
568 /// Create LCSSA PHIs for \p V, if it is required for uses at the Builder's
569 /// current insertion point.
570 Value *fixupLCSSAFormFor(Value *V);
571
572 /// Replace congruent phi increments with their most canonical representative.
573 /// May swap \p Phi and \p OrigPhi, if \p Phi is more canonical, due to its
574 /// increment.
575 void replaceCongruentIVInc(PHINode *&Phi, PHINode *&OrigPhi, Loop *L,
576 const DominatorTree *DT,
577 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
578};
579
580/// Helper to remove instructions inserted during SCEV expansion, unless they
581/// are marked as used.
583 SCEVExpander &Expander;
584
585 /// Indicates whether the result of the expansion is used. If false, the
586 /// instructions added during expansion are removed.
587 bool ResultUsed;
588
589public:
591 : Expander(Expander), ResultUsed(false) {}
592
594
595 /// Indicate that the result of the expansion is used.
596 void markResultUsed() { ResultUsed = true; }
597
598 LLVM_ABI void cleanup();
599};
600} // namespace llvm
601
602#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static Expected< BitVector > expand(StringRef S, StringRef Original)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file defines the SmallVector class.
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Value handle that asserts if the Value is deleted.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents flags for the getelementptr instruction/expression.
InsertPoint - A saved insertion point.
Definition IRBuilder.h:246
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:75
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This node represents a polynomial recurrence on the trip count of the specified loop.
This class represents an assumption that the expression LHS Pred RHS evaluates to true,...
SCEVExpanderCleaner(SCEVExpander &Expander)
void markResultUsed()
Indicate that the result of the expansion is used.
This class uses information about analyze scalars to rewrite expressions in canonical form.
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.
void setChainedPhi(PHINode *PN)
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...
void setInsertPoint(BasicBlock::iterator IP)
bool isHighCostExpansion(ArrayRef< const SCEV * > Exprs, Loop *L, unsigned Budget, const TargetTransformInfo *TTI, const Instruction *At)
Return true for expressions that can't be evaluated at runtime within given Budget.
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...
ScalarEvolution * getSE()
LLVM_ABI unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
void clearInsertPoint()
Clear the current insertion point.
static LLVM_ABI void dropPoisonGeneratingAnnotationsAndReinfer(ScalarEvolution &SE, Instruction *I)
Drop poison-generating flags from I, then try re-infer via SCEV.
void clearPostInc()
Disable all post-inc expansion.
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.
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
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.
void setPostInc(const PostIncLoopSet &L)
Enable post-inc expansion for addrecs referring to the given loops.
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...
DebugLoc getCurrentDebugLocation() const
Get location information used by debugging information.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
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...
void setIVIncInsertPos(const Loop *L, Instruction *Pos)
Set the current IV increment loop and position.
const SmallVectorImpl< WeakVH > & getInsertedIVs() const
void disableCanonicalMode()
Disable the behavior of expanding expressions in canonical form rather than in a more literal form.
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...
SCEVExpander(ScalarEvolution &SE, const char *Name, bool PreserveLCSSA=true)
Construct a SCEVExpander in "canonical" mode.
Value * expandCodeFor(SCEVUse SH, Type *Ty, Instruction *I)
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 class represents an assumption made on an AddRec expression.
This class represents an analyzed expression in the program.
SCEVNoWrapFlags NoWrapFlags
The main scalar evolution driver.
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)
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.
@ TCC_Basic
The cost of a typical 'add' instruction.
Value handle that tracks a Value across RAUW.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
This is an optimization pass for GlobalISel generic memory operations.
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
SCEVUseT(SCEVPtrT) -> SCEVUseT< SCEVPtrT >
Deduction guide for various SCEV subclass pointers.
LLVM_ABI cl::opt< unsigned > SCEVCheapExpansionBudget
TargetTransformInfo TTI
DWARFExpression::Operation Op
SmallPtrSet< const Loop *, 2 > PostIncLoopSet
SCEVUseT< const SCEV * > SCEVUse
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.
SCEVOperand(unsigned Opc, int Idx, const SCEV *S)
int OperandIdx
The use index of an expanded instruction.
A visitor class for SCEVUse.