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