xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Transforms/Utils/ScalarEvolutionExpander.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
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"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/InstSimplifyFolder.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/ScalarEvolutionNormalization.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/InstructionCost.h"
28 
29 namespace llvm {
30 LLVM_ABI extern cl::opt<unsigned> SCEVCheapExpansionBudget;
31 
32 /// struct for holding enough information to help calculate the cost of the
33 /// given SCEV when expanded into IR.
34 struct SCEVOperand {
SCEVOperandSCEVOperand35   explicit SCEVOperand(unsigned Opc, int Idx, const SCEV *S) :
36     ParentOpcode(Opc), OperandIdx(Idx), S(S) { }
37   /// LLVM instruction opcode that uses the operand.
38   unsigned ParentOpcode;
39   /// The use index of an expanded instruction.
40   int OperandIdx;
41   /// The SCEV operand to be costed.
42   const SCEV* S;
43 };
44 
45 struct PoisonFlags {
46   unsigned NUW : 1;
47   unsigned NSW : 1;
48   unsigned Exact : 1;
49   unsigned Disjoint : 1;
50   unsigned NNeg : 1;
51   unsigned SameSign : 1;
52   GEPNoWrapFlags GEPNW;
53 
54   LLVM_ABI PoisonFlags(const Instruction *I);
55   LLVM_ABI void apply(Instruction *I);
56 };
57 
58 /// This class uses information about analyze scalars to rewrite expressions
59 /// in canonical form.
60 ///
61 /// Clients should create an instance of this class when rewriting is needed,
62 /// and destroy it when finished to allow the release of the associated
63 /// memory.
64 class SCEVExpander : public SCEVVisitor<SCEVExpander, Value *> {
65   friend class SCEVExpanderCleaner;
66 
67   ScalarEvolution &SE;
68   const DataLayout &DL;
69 
70   // New instructions receive a name to identify them with the current pass.
71   const char *IVName;
72 
73   /// Indicates whether LCSSA phis should be created for inserted values.
74   bool PreserveLCSSA;
75 
76   // InsertedExpressions caches Values for reuse, so must track RAUW.
77   DenseMap<std::pair<const SCEV *, Instruction *>, TrackingVH<Value>>
78       InsertedExpressions;
79 
80   // InsertedValues only flags inserted instructions so needs no RAUW.
81   DenseSet<AssertingVH<Value>> InsertedValues;
82   DenseSet<AssertingVH<Value>> InsertedPostIncValues;
83 
84   /// Keep track of the existing IR values re-used during expansion.
85   /// FIXME: Ideally re-used instructions would not be added to
86   /// InsertedValues/InsertedPostIncValues.
87   SmallPtrSet<Value *, 16> ReusedValues;
88 
89   /// Original flags of instructions for which they were modified. Used
90   /// by SCEVExpanderCleaner to undo changes.
91   DenseMap<PoisoningVH<Instruction>, PoisonFlags> OrigFlags;
92 
93   // The induction variables generated.
94   SmallVector<WeakVH, 2> InsertedIVs;
95 
96   /// A memoization of the "relevant" loop for a given SCEV.
97   DenseMap<const SCEV *, const Loop *> RelevantLoops;
98 
99   /// Addrecs referring to any of the given loops are expanded in post-inc
100   /// mode. For example, expanding {1,+,1}<L> in post-inc mode returns the add
101   /// instruction that adds one to the phi for {0,+,1}<L>, as opposed to a new
102   /// phi starting at 1. This is only supported in non-canonical mode.
103   PostIncLoopSet PostIncLoops;
104 
105   /// When this is non-null, addrecs expanded in the loop it indicates should
106   /// be inserted with increments at IVIncInsertPos.
107   const Loop *IVIncInsertLoop;
108 
109   /// When expanding addrecs in the IVIncInsertLoop loop, insert the IV
110   /// increment at this position.
111   Instruction *IVIncInsertPos;
112 
113   /// Phis that complete an IV chain. Reuse
114   DenseSet<AssertingVH<PHINode>> ChainedPhis;
115 
116   /// When true, SCEVExpander tries to expand expressions in "canonical" form.
117   /// When false, expressions are expanded in a more literal form.
118   ///
119   /// In "canonical" form addrecs are expanded as arithmetic based on a
120   /// canonical induction variable. Note that CanonicalMode doesn't guarantee
121   /// that all expressions are expanded in "canonical" form. For some
122   /// expressions literal mode can be preferred.
123   bool CanonicalMode;
124 
125   /// When invoked from LSR, the expander is in "strength reduction" mode. The
126   /// only difference is that phi's are only reused if they are already in
127   /// "expanded" form.
128   bool LSRMode;
129 
130   /// When true, rewrite any divisors of UDiv expressions that may be 0 to
131   /// umax(Divisor, 1) to avoid introducing UB. If the divisor may be poison,
132   /// freeze it first.
133   bool SafeUDivMode = false;
134 
135   typedef IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> BuilderType;
136   BuilderType Builder;
137 
138   // RAII object that stores the current insertion point and restores it when
139   // the object is destroyed. This includes the debug location.  Duplicated
140   // from InsertPointGuard to add SetInsertPoint() which is used to updated
141   // InsertPointGuards stack when insert points are moved during SCEV
142   // expansion.
143   class SCEVInsertPointGuard {
144     IRBuilderBase &Builder;
145     AssertingVH<BasicBlock> Block;
146     BasicBlock::iterator Point;
147     DebugLoc DbgLoc;
148     SCEVExpander *SE;
149 
150     SCEVInsertPointGuard(const SCEVInsertPointGuard &) = delete;
151     SCEVInsertPointGuard &operator=(const SCEVInsertPointGuard &) = delete;
152 
153   public:
SCEVInsertPointGuard(IRBuilderBase & B,SCEVExpander * SE)154     SCEVInsertPointGuard(IRBuilderBase &B, SCEVExpander *SE)
155         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
156           DbgLoc(B.getCurrentDebugLocation()), SE(SE) {
157       SE->InsertPointGuards.push_back(this);
158     }
159 
~SCEVInsertPointGuard()160     ~SCEVInsertPointGuard() {
161       // These guards should always created/destroyed in FIFO order since they
162       // are used to guard lexically scoped blocks of code in
163       // ScalarEvolutionExpander.
164       assert(SE->InsertPointGuards.back() == this);
165       SE->InsertPointGuards.pop_back();
166       Builder.restoreIP(IRBuilderBase::InsertPoint(Block, Point));
167       Builder.SetCurrentDebugLocation(DbgLoc);
168     }
169 
GetInsertPoint()170     BasicBlock::iterator GetInsertPoint() const { return Point; }
SetInsertPoint(BasicBlock::iterator I)171     void SetInsertPoint(BasicBlock::iterator I) { Point = I; }
172   };
173 
174   /// Stack of pointers to saved insert points, used to keep insert points
175   /// consistent when instructions are moved.
176   SmallVector<SCEVInsertPointGuard *, 8> InsertPointGuards;
177 
178 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
179   const char *DebugType;
180 #endif
181 
182   friend struct SCEVVisitor<SCEVExpander, Value *>;
183 
184 public:
185   /// Construct a SCEVExpander in "canonical" mode.
186   explicit SCEVExpander(ScalarEvolution &se, const DataLayout &DL,
187                         const char *name, bool PreserveLCSSA = true)
188       : SE(se), DL(DL), IVName(name), PreserveLCSSA(PreserveLCSSA),
189         IVIncInsertLoop(nullptr), IVIncInsertPos(nullptr), CanonicalMode(true),
190         LSRMode(false),
191         Builder(se.getContext(), InstSimplifyFolder(DL),
192                 IRBuilderCallbackInserter(
193                     [this](Instruction *I) { rememberInstruction(I); })) {
194 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
195     DebugType = "";
196 #endif
197   }
198 
199   ~SCEVExpander() {
200     // Make sure the insert point guard stack is consistent.
201     assert(InsertPointGuards.empty());
202   }
203 
204 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
205   void setDebugType(const char *s) { DebugType = s; }
206 #endif
207 
208   /// Erase the contents of the InsertedExpressions map so that users trying
209   /// to expand the same expression into multiple BasicBlocks or different
210   /// places within the same BasicBlock can do so.
211   void clear() {
212     InsertedExpressions.clear();
213     InsertedValues.clear();
214     InsertedPostIncValues.clear();
215     ReusedValues.clear();
216     OrigFlags.clear();
217     ChainedPhis.clear();
218     InsertedIVs.clear();
219   }
220 
221   ScalarEvolution *getSE() { return &SE; }
222   const SmallVectorImpl<WeakVH> &getInsertedIVs() const { return InsertedIVs; }
223 
224   /// Return a vector containing all instructions inserted during expansion.
225   SmallVector<Instruction *, 32> getAllInsertedInstructions() const {
226     SmallVector<Instruction *, 32> Result;
227     for (const auto &VH : InsertedValues) {
228       Value *V = VH;
229       if (ReusedValues.contains(V))
230         continue;
231       if (auto *Inst = dyn_cast<Instruction>(V))
232         Result.push_back(Inst);
233     }
234     for (const auto &VH : InsertedPostIncValues) {
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 
242     return Result;
243   }
244 
245   /// Return true for expressions that can't be evaluated at runtime
246   /// within given \b Budget.
247   ///
248   /// \p At is a parameter which specifies point in code where user is going to
249   /// expand these expressions. Sometimes this knowledge can lead to
250   /// a less pessimistic cost estimation.
251   bool isHighCostExpansion(ArrayRef<const SCEV *> Exprs, Loop *L,
252                            unsigned Budget, const TargetTransformInfo *TTI,
253                            const Instruction *At) {
254     assert(TTI && "This function requires TTI to be provided.");
255     assert(At && "This function requires At instruction to be provided.");
256     if (!TTI)      // In assert-less builds, avoid crashing
257       return true; // by always claiming to be high-cost.
258     SmallVector<SCEVOperand, 8> Worklist;
259     SmallPtrSet<const SCEV *, 8> Processed;
260     InstructionCost Cost = 0;
261     unsigned ScaledBudget = Budget * TargetTransformInfo::TCC_Basic;
262     for (auto *Expr : Exprs)
263       Worklist.emplace_back(-1, -1, Expr);
264     while (!Worklist.empty()) {
265       const SCEVOperand WorkItem = Worklist.pop_back_val();
266       if (isHighCostExpansionHelper(WorkItem, L, *At, Cost, ScaledBudget, *TTI,
267                                     Processed, Worklist))
268         return true;
269     }
270     assert(Cost <= ScaledBudget && "Should have returned from inner loop.");
271     return false;
272   }
273 
274   /// Return the induction variable increment's IV operand.
275   LLVM_ABI Instruction *
276   getIVIncOperand(Instruction *IncV, Instruction *InsertPos, bool allowScale);
277 
278   /// Utility for hoisting \p IncV (with all subexpressions requried for its
279   /// computation) before \p InsertPos. If \p RecomputePoisonFlags is set, drops
280   /// all poison-generating flags from instructions being hoisted and tries to
281   /// re-infer them in the new location. It should be used when we are going to
282   /// introduce a new use in the new position that didn't exist before, and may
283   /// trigger new UB in case of poison.
284   LLVM_ABI bool hoistIVInc(Instruction *IncV, Instruction *InsertPos,
285                            bool RecomputePoisonFlags = false);
286 
287   /// Return true if both increments directly increment the corresponding IV PHI
288   /// nodes and have the same opcode. It is not safe to re-use the flags from
289   /// the original increment, if it is more complex and SCEV expansion may have
290   /// yielded a more simplified wider increment.
291   LLVM_ABI static bool canReuseFlagsFromOriginalIVInc(PHINode *OrigPhi,
292                                                       PHINode *WidePhi,
293                                                       Instruction *OrigInc,
294                                                       Instruction *WideInc);
295 
296   /// replace congruent phis with their most canonical representative. Return
297   /// the number of phis eliminated.
298   LLVM_ABI unsigned
299   replaceCongruentIVs(Loop *L, const DominatorTree *DT,
300                       SmallVectorImpl<WeakTrackingVH> &DeadInsts,
301                       const TargetTransformInfo *TTI = nullptr);
302 
303   /// Return true if the given expression is safe to expand in the sense that
304   /// all materialized values are safe to speculate anywhere their operands are
305   /// defined, and the expander is capable of expanding the expression.
306   LLVM_ABI bool isSafeToExpand(const SCEV *S) const;
307 
308   /// Return true if the given expression is safe to expand in the sense that
309   /// all materialized values are defined and safe to speculate at the specified
310   /// location and their operands are defined at this location.
311   LLVM_ABI bool isSafeToExpandAt(const SCEV *S,
312                                  const Instruction *InsertionPoint) const;
313 
314   /// Insert code to directly compute the specified SCEV expression into the
315   /// program.  The code is inserted into the specified block.
316   LLVM_ABI Value *expandCodeFor(const SCEV *SH, Type *Ty,
317                                 BasicBlock::iterator I);
318   Value *expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I) {
319     return expandCodeFor(SH, Ty, I->getIterator());
320   }
321 
322   /// Insert code to directly compute the specified SCEV expression into the
323   /// program.  The code is inserted into the SCEVExpander's current
324   /// insertion point. If a type is specified, the result will be expanded to
325   /// have that type, with a cast if necessary.
326   LLVM_ABI Value *expandCodeFor(const SCEV *SH, Type *Ty = nullptr);
327 
328   /// Generates a code sequence that evaluates this predicate.  The inserted
329   /// instructions will be at position \p Loc.  The result will be of type i1
330   /// and will have a value of 0 when the predicate is false and 1 otherwise.
331   LLVM_ABI Value *expandCodeForPredicate(const SCEVPredicate *Pred,
332                                          Instruction *Loc);
333 
334   /// A specialized variant of expandCodeForPredicate, handling the case when
335   /// we are expanding code for a SCEVComparePredicate.
336   LLVM_ABI Value *expandComparePredicate(const SCEVComparePredicate *Pred,
337                                          Instruction *Loc);
338 
339   /// Generates code that evaluates if the \p AR expression will overflow.
340   LLVM_ABI Value *generateOverflowCheck(const SCEVAddRecExpr *AR,
341                                         Instruction *Loc, bool Signed);
342 
343   /// A specialized variant of expandCodeForPredicate, handling the case when
344   /// we are expanding code for a SCEVWrapPredicate.
345   LLVM_ABI Value *expandWrapPredicate(const SCEVWrapPredicate *P,
346                                       Instruction *Loc);
347 
348   /// A specialized variant of expandCodeForPredicate, handling the case when
349   /// we are expanding code for a SCEVUnionPredicate.
350   LLVM_ABI Value *expandUnionPredicate(const SCEVUnionPredicate *Pred,
351                                        Instruction *Loc);
352 
353   /// Set the current IV increment loop and position.
354   void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
355     assert(!CanonicalMode &&
356            "IV increment positions are not supported in CanonicalMode");
357     IVIncInsertLoop = L;
358     IVIncInsertPos = Pos;
359   }
360 
361   /// Enable post-inc expansion for addrecs referring to the given
362   /// loops. Post-inc expansion is only supported in non-canonical mode.
363   void setPostInc(const PostIncLoopSet &L) {
364     assert(!CanonicalMode &&
365            "Post-inc expansion is not supported in CanonicalMode");
366     PostIncLoops = L;
367   }
368 
369   /// Disable all post-inc expansion.
370   void clearPostInc() {
371     PostIncLoops.clear();
372 
373     // When we change the post-inc loop set, cached expansions may no
374     // longer be valid.
375     InsertedPostIncValues.clear();
376   }
377 
378   /// Disable the behavior of expanding expressions in canonical form rather
379   /// than in a more literal form. Non-canonical mode is useful for late
380   /// optimization passes.
381   void disableCanonicalMode() { CanonicalMode = false; }
382 
383   void enableLSRMode() { LSRMode = true; }
384 
385   /// Set the current insertion point. This is useful if multiple calls to
386   /// expandCodeFor() are going to be made with the same insert point and the
387   /// insert point may be moved during one of the expansions (e.g. if the
388   /// insert point is not a block terminator).
389   void setInsertPoint(Instruction *IP) {
390     assert(IP);
391     Builder.SetInsertPoint(IP);
392   }
393 
394   void setInsertPoint(BasicBlock::iterator IP) {
395     Builder.SetInsertPoint(IP->getParent(), IP);
396   }
397 
398   /// Clear the current insertion point. This is useful if the instruction
399   /// that had been serving as the insertion point may have been deleted.
400   void clearInsertPoint() { Builder.ClearInsertionPoint(); }
401 
402   /// Set location information used by debugging information.
403   void SetCurrentDebugLocation(DebugLoc L) {
404     Builder.SetCurrentDebugLocation(std::move(L));
405   }
406 
407   /// Get location information used by debugging information.
408   DebugLoc getCurrentDebugLocation() const {
409     return Builder.getCurrentDebugLocation();
410   }
411 
412   /// Return true if the specified instruction was inserted by the code
413   /// rewriter.  If so, the client should not modify the instruction. Note that
414   /// this also includes instructions re-used during expansion.
415   bool isInsertedInstruction(Instruction *I) const {
416     return InsertedValues.count(I) || InsertedPostIncValues.count(I);
417   }
418 
419   void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
420 
421   /// Determine whether there is an existing expansion of S that can be reused.
422   /// This is used to check whether S can be expanded cheaply.
423   ///
424   /// L is a hint which tells in which loop to look for the suitable value.
425   ///
426   /// Note that this function does not perform an exhaustive search. I.e if it
427   /// didn't find any value it does not mean that there is no such value.
428   LLVM_ABI bool hasRelatedExistingExpansion(const SCEV *S,
429                                             const Instruction *At, Loop *L);
430 
431   /// Returns a suitable insert point after \p I, that dominates \p
432   /// MustDominate. Skips instructions inserted by the expander.
433   LLVM_ABI BasicBlock::iterator
434   findInsertPointAfter(Instruction *I, Instruction *MustDominate) const;
435 
436 private:
437   LLVMContext &getContext() const { return SE.getContext(); }
438 
439   /// Recursive helper function for isHighCostExpansion.
440   LLVM_ABI bool
441   isHighCostExpansionHelper(const SCEVOperand &WorkItem, Loop *L,
442                             const Instruction &At, InstructionCost &Cost,
443                             unsigned Budget, const TargetTransformInfo &TTI,
444                             SmallPtrSetImpl<const SCEV *> &Processed,
445                             SmallVectorImpl<SCEVOperand> &Worklist);
446 
447   /// Insert the specified binary operator, doing a small amount of work to
448   /// avoid inserting an obviously redundant operation, and hoisting to an
449   /// outer loop when the opportunity is there and it is safe.
450   Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
451                      SCEV::NoWrapFlags Flags, bool IsSafeToHoist);
452 
453   /// We want to cast \p V. What would be the best place for such a cast?
454   BasicBlock::iterator GetOptimalInsertionPointForCastOf(Value *V) const;
455 
456   /// Arrange for there to be a cast of V to Ty at IP, reusing an existing
457   /// cast if a suitable one exists, moving an existing cast if a suitable one
458   /// exists but isn't in the right place, or creating a new one.
459   Value *ReuseOrCreateCast(Value *V, Type *Ty, Instruction::CastOps Op,
460                            BasicBlock::iterator IP);
461 
462   /// Insert a cast of V to the specified type, which must be possible with a
463   /// noop cast, doing what we can to share the casts.
464   Value *InsertNoopCastOfTo(Value *V, Type *Ty);
465 
466   /// Expand a SCEVAddExpr with a pointer type into a GEP instead of using
467   /// ptrtoint+arithmetic+inttoptr.
468   Value *expandAddToGEP(const SCEV *Op, Value *V, SCEV::NoWrapFlags Flags);
469 
470   /// Find a previous Value in ExprValueMap for expand.
471   /// DropPoisonGeneratingInsts is populated with instructions for which
472   /// poison-generating flags must be dropped if the value is reused.
473   Value *FindValueInExprValueMap(
474       const SCEV *S, const Instruction *InsertPt,
475       SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts);
476 
477   LLVM_ABI Value *expand(const SCEV *S);
478   Value *expand(const SCEV *S, BasicBlock::iterator I) {
479     setInsertPoint(I);
480     return expand(S);
481   }
482   Value *expand(const SCEV *S, Instruction *I) {
483     setInsertPoint(I);
484     return expand(S);
485   }
486 
487   /// Determine the most "relevant" loop for the given SCEV.
488   const Loop *getRelevantLoop(const SCEV *);
489 
490   Value *expandMinMaxExpr(const SCEVNAryExpr *S, Intrinsic::ID IntrinID,
491                           Twine Name, bool IsSequential = false);
492 
493   Value *visitConstant(const SCEVConstant *S) { return S->getValue(); }
494 
495   Value *visitVScale(const SCEVVScale *S);
496 
497   Value *visitPtrToIntExpr(const SCEVPtrToIntExpr *S);
498 
499   Value *visitTruncateExpr(const SCEVTruncateExpr *S);
500 
501   Value *visitZeroExtendExpr(const SCEVZeroExtendExpr *S);
502 
503   Value *visitSignExtendExpr(const SCEVSignExtendExpr *S);
504 
505   Value *visitAddExpr(const SCEVAddExpr *S);
506 
507   Value *visitMulExpr(const SCEVMulExpr *S);
508 
509   Value *visitUDivExpr(const SCEVUDivExpr *S);
510 
511   Value *visitAddRecExpr(const SCEVAddRecExpr *S);
512 
513   Value *visitSMaxExpr(const SCEVSMaxExpr *S);
514 
515   Value *visitUMaxExpr(const SCEVUMaxExpr *S);
516 
517   Value *visitSMinExpr(const SCEVSMinExpr *S);
518 
519   Value *visitUMinExpr(const SCEVUMinExpr *S);
520 
521   Value *visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S);
522 
523   Value *visitUnknown(const SCEVUnknown *S) { return S->getValue(); }
524 
525   LLVM_ABI void rememberInstruction(Value *I);
526 
527   void rememberFlags(Instruction *I);
528 
529   bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
530 
531   bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
532 
533   Value *expandAddRecExprLiterally(const SCEVAddRecExpr *);
534   PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
535                                      const Loop *L, Type *&TruncTy,
536                                      bool &InvertStep);
537   Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
538                      bool useSubtract);
539 
540   void fixupInsertPoints(Instruction *I);
541 
542   /// Create LCSSA PHIs for \p V, if it is required for uses at the Builder's
543   /// current insertion point.
544   Value *fixupLCSSAFormFor(Value *V);
545 
546   /// Replace congruent phi increments with their most canonical representative.
547   /// May swap \p Phi and \p OrigPhi, if \p Phi is more canonical, due to its
548   /// increment.
549   void replaceCongruentIVInc(PHINode *&Phi, PHINode *&OrigPhi, Loop *L,
550                              const DominatorTree *DT,
551                              SmallVectorImpl<WeakTrackingVH> &DeadInsts);
552 };
553 
554 /// Helper to remove instructions inserted during SCEV expansion, unless they
555 /// are marked as used.
556 class SCEVExpanderCleaner {
557   SCEVExpander &Expander;
558 
559   /// Indicates whether the result of the expansion is used. If false, the
560   /// instructions added during expansion are removed.
561   bool ResultUsed;
562 
563 public:
564   SCEVExpanderCleaner(SCEVExpander &Expander)
565       : Expander(Expander), ResultUsed(false) {}
566 
567   ~SCEVExpanderCleaner() { cleanup(); }
568 
569   /// Indicate that the result of the expansion is used.
570   void markResultUsed() { ResultUsed = true; }
571 
572   LLVM_ABI void cleanup();
573 };
574 } // namespace llvm
575 
576 #endif
577