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.
82 // The key is a tuple containing the trip count for the loop, the absolute
83 // value of the recurrence step, and the insert point. The stored pair values
84 // are the multiply result and a boolean value indicating overflow.
86 std::pair<TrackingVH<Value>, TrackingVH<Value>>>
87 InsertedOverflowChecks;
88
89 // InsertedValues only flags inserted instructions so needs no RAUW.
90 DenseSet<AssertingVH<Value>> InsertedValues;
91 DenseSet<AssertingVH<Value>> InsertedPostIncValues;
92
93 /// Keep track of the existing IR values re-used during expansion.
94 /// FIXME: Ideally re-used instructions would not be added to
95 /// InsertedValues/InsertedPostIncValues.
96 SmallPtrSet<Value *, 16> ReusedValues;
97
98 /// Original flags of instructions for which they were modified. Used
99 /// by SCEVExpanderCleaner to undo changes.
101
102 // The induction variables generated.
103 SmallVector<WeakVH, 2> InsertedIVs;
104
105 /// A memoization of the "relevant" loop for a given SCEV.
107
108 /// Addrecs referring to any of the given loops are expanded in post-inc
109 /// mode. For example, expanding {1,+,1}<L> in post-inc mode returns the add
110 /// instruction that adds one to the phi for {0,+,1}<L>, as opposed to a new
111 /// phi starting at 1. This is only supported in non-canonical mode.
112 PostIncLoopSet PostIncLoops;
113
114 /// When this is non-null, addrecs expanded in the loop it indicates should
115 /// be inserted with increments at IVIncInsertPos.
116 const Loop *IVIncInsertLoop;
117
118 /// When expanding addrecs in the IVIncInsertLoop loop, insert the IV
119 /// increment at this position.
120 Instruction *IVIncInsertPos;
121
122 /// Phis that complete an IV chain. Reuse
124
125 /// When true, SCEVExpander tries to expand expressions in "canonical" form.
126 /// When false, expressions are expanded in a more literal form.
127 ///
128 /// In "canonical" form addrecs are expanded as arithmetic based on a
129 /// canonical induction variable. Note that CanonicalMode doesn't guarantee
130 /// that all expressions are expanded in "canonical" form. For some
131 /// expressions literal mode can be preferred.
132 bool CanonicalMode;
133
134 /// When invoked from LSR, the expander is in "strength reduction" mode. The
135 /// only difference is that phi's are only reused if they are already in
136 /// "expanded" form.
137 bool LSRMode;
138
139 /// When true, rewrite any divisors of UDiv expressions that may be 0 to
140 /// umax(Divisor, 1) to avoid introducing UB. If the divisor may be poison,
141 /// freeze it first.
142 bool SafeUDivMode;
143
145 BuilderType Builder;
146
147 // RAII object that stores the current insertion point and restores it when
148 // the object is destroyed. This includes the debug location. Duplicated
149 // from InsertPointGuard to add SetInsertPoint() which is used to updated
150 // InsertPointGuards stack when insert points are moved during SCEV
151 // expansion.
152 class SCEVInsertPointGuard {
153 IRBuilderBase &Builder;
155 DebugLoc DbgLoc;
156 SCEVExpander *SE;
157
158 SCEVInsertPointGuard(const SCEVInsertPointGuard &) = delete;
159 SCEVInsertPointGuard &operator=(const SCEVInsertPointGuard &) = delete;
160
161 public:
162 SCEVInsertPointGuard(IRBuilderBase &B, SCEVExpander *SE)
163 : Builder(B), Point(B.GetInsertPoint()),
164 DbgLoc(B.getCurrentDebugLocation()), SE(SE) {
165 SE->InsertPointGuards.push_back(this);
166 }
167
168 ~SCEVInsertPointGuard() {
169 // These guards should always created/destroyed in FIFO order since they
170 // are used to guard lexically scoped blocks of code in
171 // ScalarEvolutionExpander.
172 assert(SE->InsertPointGuards.back() == this);
173 SE->InsertPointGuards.pop_back();
174 Builder.restoreIP(Point);
175 Builder.SetCurrentDebugLocation(DbgLoc);
176 }
177
178 BasicBlock::iterator GetInsertPoint() const { return Point; }
179 void SetInsertPoint(BasicBlock::iterator I) { Point = I; }
180 };
181
182 /// Stack of pointers to saved insert points, used to keep insert points
183 /// consistent when instructions are moved.
185
186#if LLVM_ENABLE_ABI_BREAKING_CHECKS
187 const char *DebugType;
188#endif
189
190 friend struct SCEVUseVisitor<SCEVExpander, Value *>;
191
192public:
193 /// Construct a SCEVExpander in "canonical" mode.
194 /// If \p SafeUDivMode is true, UDiv expressions are expanded such that they
195 /// cannot cause UB, by rewriting divisors that may be zero or poison to
196 /// umax(freeze(Divisor), 1).
197 explicit SCEVExpander(ScalarEvolution &SE, const char *Name,
198 bool PreserveLCSSA = true, bool SafeUDivMode = false)
199 : SE(SE), DL(SE.getDataLayout()), IVName(Name),
200 PreserveLCSSA(PreserveLCSSA), IVIncInsertLoop(nullptr),
201 IVIncInsertPos(nullptr), CanonicalMode(true), LSRMode(false),
202 SafeUDivMode(SafeUDivMode),
203 Builder(SE.getModule(), InstSimplifyFolder(DL),
205 [this](Instruction *I) { rememberInstruction(I); })) {
206#if LLVM_ENABLE_ABI_BREAKING_CHECKS
207 DebugType = "";
208#endif
209 }
210
212 // Make sure the insert point guard stack is consistent.
213 assert(InsertPointGuards.empty());
214 }
215
216#if LLVM_ENABLE_ABI_BREAKING_CHECKS
217 void setDebugType(const char *s) { DebugType = s; }
218#endif
219
220 /// Erase the contents of the InsertedExpressions map so that users trying
221 /// to expand the same expression into multiple BasicBlocks or different
222 /// places within the same BasicBlock can do so.
223 void clear() {
224 InsertedExpressions.clear();
225 InsertedOverflowChecks.clear();
226 InsertedValues.clear();
227 InsertedPostIncValues.clear();
228 ReusedValues.clear();
229 OrigFlags.clear();
230 ChainedPhis.clear();
231 InsertedIVs.clear();
232 }
233
234 ScalarEvolution *getSE() { return &SE; }
235 const SmallVectorImpl<WeakVH> &getInsertedIVs() const { return InsertedIVs; }
236
237 /// Return a vector containing all instructions inserted during expansion.
240 for (const auto &VH : InsertedValues) {
241 Value *V = VH;
242 if (ReusedValues.contains(V))
243 continue;
244 if (auto *Inst = dyn_cast<Instruction>(V))
245 Result.push_back(Inst);
246 }
247 for (const auto &VH : InsertedPostIncValues) {
248 Value *V = VH;
249 if (ReusedValues.contains(V))
250 continue;
251 if (auto *Inst = dyn_cast<Instruction>(V))
252 Result.push_back(Inst);
253 }
254
255 return Result;
256 }
257
258 /// Return true for expressions that can't be evaluated at runtime
259 /// within given \b Budget.
260 ///
261 /// \p At is a parameter which specifies point in code where user is going to
262 /// expand these expressions. Sometimes this knowledge can lead to
263 /// a less pessimistic cost estimation.
265 unsigned Budget, const TargetTransformInfo *TTI,
266 const Instruction *At) {
267 assert(TTI && "This function requires TTI to be provided.");
268 assert(At && "This function requires At instruction to be provided.");
269 if (!TTI) // In assert-less builds, avoid crashing
270 return true; // by always claiming to be high-cost.
274 unsigned ScaledBudget = Budget * TargetTransformInfo::TCC_Basic;
275 for (auto *Expr : Exprs)
276 Worklist.emplace_back(-1, -1, Expr);
277 while (!Worklist.empty()) {
278 const SCEVOperand WorkItem = Worklist.pop_back_val();
279 if (isHighCostExpansionHelper(WorkItem, L, *At, Cost, ScaledBudget, *TTI,
280 Processed, Worklist))
281 return true;
282 }
283 assert(Cost <= ScaledBudget && "Should have returned from inner loop.");
284 return false;
285 }
286
287 /// Return the induction variable increment's IV operand.
289 getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale);
290
291 /// Utility for hoisting \p IncV (with all subexpressions requried for its
292 /// computation) before \p InsertPos. If \p RecomputePoisonFlags is set, drops
293 /// all poison-generating flags from instructions being hoisted and tries to
294 /// re-infer them in the new location. It should be used when we are going to
295 /// introduce a new use in the new position that didn't exist before, and may
296 /// trigger new UB in case of poison.
297 LLVM_ABI bool hoistIVInc(Instruction *IncV, Instruction *InsertPos,
298 bool RecomputePoisonFlags = false);
299
300 /// Return true if both increments directly increment the corresponding IV PHI
301 /// nodes and have the same opcode. It is not safe to re-use the flags from
302 /// the original increment, if it is more complex and SCEV expansion may have
303 /// yielded a more simplified wider increment.
305 PHINode *WidePhi,
306 Instruction *OrigInc,
307 Instruction *WideInc);
308
309 /// replace congruent phis with their most canonical representative. Return
310 /// the number of phis eliminated.
311 LLVM_ABI unsigned
314 const TargetTransformInfo *TTI = nullptr);
315
316 /// Return true if the given expression is safe to expand in the sense that
317 /// all materialized values are safe to speculate anywhere their operands are
318 /// defined, and the expander is capable of expanding the expression.
319 LLVM_ABI bool isSafeToExpand(const SCEV *S) const;
320
321 /// Return true if the given expression is safe to expand in the sense that
322 /// all materialized values are defined and safe to speculate at the specified
323 /// location and their operands are defined at this location.
324 LLVM_ABI bool isSafeToExpandAt(const SCEV *S,
325 const Instruction *InsertionPoint) const;
326
327 /// Drop poison-generating flags from \p I, then try re-infer via SCEV.
328 LLVM_ABI static void
330 Instruction *I);
331
332 /// Find an existing cast among \p PtrOp's users that computes the same value
333 /// as a `ptrtoaddr` of \p PtrOp to \p Ty and can be reused when expanding
334 /// ptrtoaddr.
335 LLVM_ABI static CastInst *
337 function_ref<bool(const CastInst *)> Dominates);
338
339 /// Find a phi in the exit block of \p S's loop, which must dominate
340 /// \p InsertBB, such that \p S can be expanded in \p InsertBB as the phi
341 /// plus a simple difference. Returns the phi and the difference, or
342 /// {nullptr, nullptr}.
343 LLVM_ABI static std::pair<PHINode *, const SCEV *>
345 const BasicBlock *InsertBB);
346
347 /// Insert code to directly compute the specified SCEV expression into the
348 /// program. The code is inserted into the specified block.
351 return expandCodeFor(SH, Ty, I->getIterator());
352 }
353
354 /// Insert code to directly compute the specified SCEV expression into the
355 /// program. The code is inserted into the SCEVExpander's current
356 /// insertion point. If a type is specified, the result will be expanded to
357 /// have that type, with a cast if necessary.
358 LLVM_ABI Value *expandCodeFor(SCEVUse SH, Type *Ty = nullptr);
359
360 /// Generates a code sequence that evaluates this predicate. The inserted
361 /// instructions will be at position \p Loc. The result will be of type i1
362 /// and will have a value of 0 when the predicate is false and 1 otherwise.
365
366 /// A specialized variant of expandCodeForPredicate, handling the case when
367 /// we are expanding code for a SCEVComparePredicate.
370
371 /// Generates code that evaluates if the \p AR expression will overflow.
373 Instruction *Loc, bool Signed);
374
375 /// A specialized variant of expandCodeForPredicate, handling the case when
376 /// we are expanding code for a SCEVWrapPredicate.
379
380 /// A specialized variant of expandCodeForPredicate, handling the case when
381 /// we are expanding code for a SCEVUnionPredicate.
384
385 /// Set the current IV increment loop and position.
386 void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
387 assert(!CanonicalMode &&
388 "IV increment positions are not supported in CanonicalMode");
389 IVIncInsertLoop = L;
390 IVIncInsertPos = Pos;
391 }
392
393 /// Enable post-inc expansion for addrecs referring to the given
394 /// loops. Post-inc expansion is only supported in non-canonical mode.
395 void setPostInc(const PostIncLoopSet &L) {
396 assert(!CanonicalMode &&
397 "Post-inc expansion is not supported in CanonicalMode");
398 PostIncLoops = L;
399 }
400
401 /// Disable all post-inc expansion.
403 PostIncLoops.clear();
404
405 // When we change the post-inc loop set, cached expansions may no
406 // longer be valid.
407 InsertedPostIncValues.clear();
408 }
409
410 /// Disable the behavior of expanding expressions in canonical form rather
411 /// than in a more literal form. Non-canonical mode is useful for late
412 /// optimization passes.
413 void disableCanonicalMode() { CanonicalMode = false; }
414
415 void enableLSRMode() { LSRMode = true; }
416
417 /// Set the current insertion point. This is useful if multiple calls to
418 /// expandCodeFor() are going to be made with the same insert point and the
419 /// insert point may be moved during one of the expansions (e.g. if the
420 /// insert point is not a block terminator).
422 assert(IP);
423 Builder.SetInsertPoint(IP);
424 }
425
426 void setInsertPoint(BasicBlock::iterator IP) { Builder.SetInsertPoint(IP); }
427
428 /// Clear the current insertion point. This is useful if the instruction
429 /// that had been serving as the insertion point may have been deleted.
430 void clearInsertPoint() { Builder.ClearInsertionPoint(); }
431
432 /// Set location information used by debugging information.
434 Builder.SetCurrentDebugLocation(std::move(L));
435 }
436
437 /// Get location information used by debugging information.
439 return Builder.getCurrentDebugLocation();
440 }
441
442 /// Return true if the specified instruction was inserted by the code
443 /// rewriter. If so, the client should not modify the instruction. Note that
444 /// this also includes instructions re-used during expansion.
446 return InsertedValues.count(I) || InsertedPostIncValues.count(I);
447 }
448
449 void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
450
451 /// Determine whether there is an existing expansion of S that can be reused.
452 /// This is used to check whether S can be expanded cheaply.
453 ///
454 /// L is a hint which tells in which loop to look for the suitable value.
455 ///
456 /// Note that this function does not perform an exhaustive search. I.e if it
457 /// didn't find any value it does not mean that there is no such value.
459 const Instruction *At, Loop *L);
460
461 /// Returns a suitable insert point after \p I, that dominates \p
462 /// MustDominate. Skips instructions inserted by the expander.
464 findInsertPointAfter(Instruction *I, Instruction *MustDominate) const;
465
466 /// Remove inserted instructions that are dead, e.g. due to InstSimplifyFolder
467 /// simplifications. \p Root is assumed to be used and won't be removed.
469
470private:
471 LLVMContext &getContext() const { return SE.getContext(); }
472
473 /// Recursive helper function for isHighCostExpansion.
474 LLVM_ABI bool
475 isHighCostExpansionHelper(const SCEVOperand &WorkItem, Loop *L,
476 const Instruction &At, InstructionCost &Cost,
477 unsigned Budget, const TargetTransformInfo &TTI,
478 SmallPtrSetImpl<const SCEV *> &Processed,
479 SmallVectorImpl<SCEVOperand> &Worklist);
480
481 /// Insert the specified binary operator, doing a small amount of work to
482 /// avoid inserting an obviously redundant operation, and hoisting to an
483 /// outer loop when the opportunity is there and it is safe.
484 Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
485 SCEVFlags Flags, bool IsSafeToHoist);
486
487 /// We want to cast \p V. What would be the best place for such a cast?
488 BasicBlock::iterator GetOptimalInsertionPointForCastOf(Value *V) const;
489
490 /// Arrange for there to be a cast of V to Ty at IP, reusing an existing
491 /// cast if a suitable one exists, moving an existing cast if a suitable one
492 /// exists but isn't in the right place, or creating a new one.
493 Value *ReuseOrCreateCast(Value *V, Type *Ty, Instruction::CastOps Op,
495
496 /// Insert a cast of V to the specified type, which must be possible with a
497 /// noop cast, doing what we can to share the casts.
498 Value *InsertNoopCastOfTo(Value *V, Type *Ty);
499
500 /// Expand a SCEVAddExpr with a pointer type into a GEP instead of using
501 /// ptrtoint+arithmetic+inttoptr.
502 Value *expandAddToGEP(SCEVUse Op, Value *V, SCEVFlags Flags);
503
504 /// Find a previous Value in ExprValueMap for expand.
505 /// DropPoisonGeneratingInsts is populated with instructions for which
506 /// poison-generating flags must be dropped if the value is reused.
507 Value *FindValueInExprValueMap(
508 SCEVUse S, const Instruction *InsertPt,
509 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts);
510
511 /// Like FindValueInExprValueMap, but on a successful lookup also drops the
512 /// poison-generating flags that reusing the value requires.
513 Value *findExistingExpansionAndDropPoisonFlags(SCEVUse S,
514 const Instruction *InsertPt);
515
516 LLVM_ABI Value *expand(SCEVUse S);
519 return expand(S);
520 }
521 Value *expand(SCEVUse S, Instruction *I) {
523 return expand(S);
524 }
525
526 /// Determine the most "relevant" loop for the given SCEV.
527 const Loop *getRelevantLoop(const SCEV *);
528
529 Value *expandMinMaxExpr(SCEVUseT<const SCEVNAryExpr *> S,
530 Intrinsic::ID IntrinID, Twine Name,
531 bool IsSequential = false);
532
533 Value *visitConstant(SCEVUseT<const SCEVConstant *> S) {
534 return S->getValue();
535 }
536
537 Value *visitVScale(SCEVUseT<const SCEVVScale *> S);
538
539 Value *visitPtrToAddrExpr(SCEVUseT<const SCEVPtrToAddrExpr *> S);
540
541 Value *visitTruncateExpr(SCEVUseT<const SCEVTruncateExpr *> S);
542
543 Value *visitZeroExtendExpr(SCEVUseT<const SCEVZeroExtendExpr *> S);
544
545 Value *visitSignExtendExpr(SCEVUseT<const SCEVSignExtendExpr *> S);
546
547 Value *visitAddExpr(SCEVUseT<const SCEVAddExpr *> S);
548
549 Value *visitMulExpr(SCEVUseT<const SCEVMulExpr *> S);
550
551 Value *visitUDivExpr(SCEVUseT<const SCEVUDivExpr *> S);
552
553 Value *visitAddRecExpr(SCEVUseT<const SCEVAddRecExpr *> S);
554
555 Value *visitSMaxExpr(SCEVUseT<const SCEVSMaxExpr *> S);
556
557 Value *visitUMaxExpr(SCEVUseT<const SCEVUMaxExpr *> S);
558
559 Value *visitSMinExpr(SCEVUseT<const SCEVSMinExpr *> S);
560
561 Value *visitUMinExpr(SCEVUseT<const SCEVUMinExpr *> S);
562
563 Value *visitSequentialUMinExpr(SCEVUseT<const SCEVSequentialUMinExpr *> S);
564
565 Value *visitUnknown(SCEVUseT<const SCEVUnknown *> S) { return S->getValue(); }
566
567 LLVM_ABI void rememberInstruction(Value *I);
568
569 void rememberFlags(Instruction *I);
570
571 bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
572
573 bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
574
575 Value *tryToReuseLCSSAPhi(SCEVUseT<const SCEVAddRecExpr *> S);
576 Value *expandAddRecExprLiterally(SCEVUseT<const SCEVAddRecExpr *> S);
577 PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
578 const Loop *L, Type *&TruncTy,
579 bool &InvertStep);
580 Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
581 bool useSubtract);
582
583 void fixupInsertPoints(Instruction *I);
584
585 /// Create LCSSA PHIs for \p V, if it is required for uses at the Builder's
586 /// current insertion point.
587 Value *fixupLCSSAFormFor(Value *V);
588
589 /// Replace congruent phi increments with their most canonical representative.
590 /// May swap \p Phi and \p OrigPhi, if \p Phi is more canonical, due to its
591 /// increment.
592 void replaceCongruentIVInc(PHINode *&Phi, PHINode *&OrigPhi, Loop *L,
593 const DominatorTree *DT,
594 SmallVectorImpl<WeakTrackingVH> &DeadInsts);
595};
596
597/// Helper to remove instructions inserted during SCEV expansion, unless they
598/// are marked as used.
600 SCEVExpander &Expander;
601
602 /// Indicates whether the result of the expansion is used. If false, the
603 /// instructions added during expansion are removed.
604 bool ResultUsed;
605
606public:
608 : Expander(Expander), ResultUsed(false) {}
609
611
612 /// Indicate that the result of the expansion is used.
613 void markResultUsed() { ResultUsed = true; }
614
615 LLVM_ABI void cleanup();
616};
617} // namespace llvm
618
619#endif
SDValue Pred
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:211
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
LLVM Basic Block Representation.
Definition BasicBlock.h:62
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:283
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents flags for the getelementptr instruction/expression.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2987
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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...
SCEVExpander(ScalarEvolution &SE, const char *Name, bool PreserveLCSSA=true, bool SafeUDivMode=false)
Construct a SCEVExpander in "canonical" mode.
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...
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.
static LLVM_ABI std::pair< PHINode *, const SCEV * > findReusableLCSSAPhi(ScalarEvolution &SE, SCEVUseT< const SCEVAddRecExpr * > S, const BasicBlock *InsertBB)
Find a phi in the exit block of S's loop, which must dominate InsertBB, such that S can be expanded i...
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.
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.