xref: /llvm-project/llvm/include/llvm/Analysis/IVDescriptors.h (revision b3cba9be41bfa89bc0ec212706c6028a901e127a)
1 //===- llvm/Analysis/IVDescriptors.h - IndVar Descriptors -------*- 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 "describes" induction and recurrence variables.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_ANALYSIS_IVDESCRIPTORS_H
14 #define LLVM_ANALYSIS_IVDESCRIPTORS_H
15 
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/ValueHandle.h"
20 
21 namespace llvm {
22 
23 class AssumptionCache;
24 class DemandedBits;
25 class DominatorTree;
26 class Loop;
27 class PredicatedScalarEvolution;
28 class ScalarEvolution;
29 class SCEV;
30 class StoreInst;
31 
32 /// These are the kinds of recurrences that we support.
33 enum class RecurKind {
34   None,     ///< Not a recurrence.
35   Add,      ///< Sum of integers.
36   Mul,      ///< Product of integers.
37   Or,       ///< Bitwise or logical OR of integers.
38   And,      ///< Bitwise or logical AND of integers.
39   Xor,      ///< Bitwise or logical XOR of integers.
40   SMin,     ///< Signed integer min implemented in terms of select(cmp()).
41   SMax,     ///< Signed integer max implemented in terms of select(cmp()).
42   UMin,     ///< Unsigned integer min implemented in terms of select(cmp()).
43   UMax,     ///< Unsigned integer max implemented in terms of select(cmp()).
44   FAdd,     ///< Sum of floats.
45   FMul,     ///< Product of floats.
46   FMin,     ///< FP min implemented in terms of select(cmp()).
47   FMax,     ///< FP max implemented in terms of select(cmp()).
48   FMinimum, ///< FP min with llvm.minimum semantics
49   FMaximum, ///< FP max with llvm.maximum semantics
50   FMulAdd,  ///< Sum of float products with llvm.fmuladd(a * b + sum).
51   IAnyOf,   ///< Any_of reduction with select(icmp(),x,y) where one of (x,y) is
52             ///< loop invariant, and both x and y are integer type.
53   FAnyOf,   ///< Any_of reduction with select(fcmp(),x,y) where one of (x,y) is
54             ///< loop invariant, and both x and y are integer type.
55   IFindLastIV, ///< FindLast reduction with select(icmp(),x,y) where one of
56                ///< (x,y) is increasing loop induction, and both x and y are
57                ///< integer type.
58   FFindLastIV ///< FindLast reduction with select(fcmp(),x,y) where one of (x,y)
59               ///< is increasing loop induction, and both x and y are integer
60               ///< type.
61   // TODO: Any_of and FindLast reduction need not be restricted to integer type
62   // only.
63 };
64 
65 /// The RecurrenceDescriptor is used to identify recurrences variables in a
66 /// loop. Reduction is a special case of recurrence that has uses of the
67 /// recurrence variable outside the loop. The method isReductionPHI identifies
68 /// reductions that are basic recurrences.
69 ///
70 /// Basic recurrences are defined as the summation, product, OR, AND, XOR, min,
71 /// or max of a set of terms. For example: for(i=0; i<n; i++) { total +=
72 /// array[i]; } is a summation of array elements. Basic recurrences are a
73 /// special case of chains of recurrences (CR). See ScalarEvolution for CR
74 /// references.
75 
76 /// This struct holds information about recurrence variables.
77 class RecurrenceDescriptor {
78 public:
79   RecurrenceDescriptor() = default;
80 
81   RecurrenceDescriptor(Value *Start, Instruction *Exit, StoreInst *Store,
82                        RecurKind K, FastMathFlags FMF, Instruction *ExactFP,
83                        Type *RT, bool Signed, bool Ordered,
84                        SmallPtrSetImpl<Instruction *> &CI,
85                        unsigned MinWidthCastToRecurTy)
86       : IntermediateStore(Store), StartValue(Start), LoopExitInstr(Exit),
87         Kind(K), FMF(FMF), ExactFPMathInst(ExactFP), RecurrenceType(RT),
88         IsSigned(Signed), IsOrdered(Ordered),
89         MinWidthCastToRecurrenceType(MinWidthCastToRecurTy) {
90     CastInsts.insert(CI.begin(), CI.end());
91   }
92 
93   /// This POD struct holds information about a potential recurrence operation.
94   class InstDesc {
95   public:
96     InstDesc(bool IsRecur, Instruction *I, Instruction *ExactFP = nullptr)
97         : IsRecurrence(IsRecur), PatternLastInst(I),
98           RecKind(RecurKind::None), ExactFPMathInst(ExactFP) {}
99 
100     InstDesc(Instruction *I, RecurKind K, Instruction *ExactFP = nullptr)
101         : IsRecurrence(true), PatternLastInst(I), RecKind(K),
102           ExactFPMathInst(ExactFP) {}
103 
104     bool isRecurrence() const { return IsRecurrence; }
105 
106     bool needsExactFPMath() const { return ExactFPMathInst != nullptr; }
107 
108     Instruction *getExactFPMathInst() const { return ExactFPMathInst; }
109 
110     RecurKind getRecKind() const { return RecKind; }
111 
112     Instruction *getPatternInst() const { return PatternLastInst; }
113 
114   private:
115     // Is this instruction a recurrence candidate.
116     bool IsRecurrence;
117     // The last instruction in a min/max pattern (select of the select(icmp())
118     // pattern), or the current recurrence instruction otherwise.
119     Instruction *PatternLastInst;
120     // If this is a min/max pattern.
121     RecurKind RecKind;
122     // Recurrence does not allow floating-point reassociation.
123     Instruction *ExactFPMathInst;
124   };
125 
126   /// Returns a struct describing if the instruction 'I' can be a recurrence
127   /// variable of type 'Kind' for a Loop \p L and reduction PHI \p Phi.
128   /// If the recurrence is a min/max pattern of select(icmp()) this function
129   /// advances the instruction pointer 'I' from the compare instruction to the
130   /// select instruction and stores this pointer in 'PatternLastInst' member of
131   /// the returned struct.
132   static InstDesc isRecurrenceInstr(Loop *L, PHINode *Phi, Instruction *I,
133                                     RecurKind Kind, InstDesc &Prev,
134                                     FastMathFlags FuncFMF, ScalarEvolution *SE);
135 
136   /// Returns true if instruction I has multiple uses in Insts
137   static bool hasMultipleUsesOf(Instruction *I,
138                                 SmallPtrSetImpl<Instruction *> &Insts,
139                                 unsigned MaxNumUses);
140 
141   /// Returns true if all uses of the instruction I is within the Set.
142   static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set);
143 
144   /// Returns a struct describing if the instruction is a llvm.(s/u)(min/max),
145   /// llvm.minnum/maxnum or a Select(ICmp(X, Y), X, Y) pair of instructions
146   /// corresponding to a min(X, Y) or max(X, Y), matching the recurrence kind \p
147   /// Kind. \p Prev specifies the description of an already processed select
148   /// instruction, so its corresponding cmp can be matched to it.
149   static InstDesc isMinMaxPattern(Instruction *I, RecurKind Kind,
150                                   const InstDesc &Prev);
151 
152   /// Returns a struct describing whether the instruction is either a
153   ///   Select(ICmp(A, B), X, Y), or
154   ///   Select(FCmp(A, B), X, Y)
155   /// where one of (X, Y) is a loop invariant integer and the other is a PHI
156   /// value. \p Prev specifies the description of an already processed select
157   /// instruction, so its corresponding cmp can be matched to it.
158   static InstDesc isAnyOfPattern(Loop *Loop, PHINode *OrigPhi, Instruction *I,
159                                  InstDesc &Prev);
160 
161   /// Returns a struct describing whether the instruction is either a
162   ///   Select(ICmp(A, B), X, Y), or
163   ///   Select(FCmp(A, B), X, Y)
164   /// where one of (X, Y) is an increasing loop induction variable, and the
165   /// other is a PHI value.
166   // TODO: Support non-monotonic variable. FindLast does not need be restricted
167   // to increasing loop induction variables.
168   static InstDesc isFindLastIVPattern(Loop *TheLoop, PHINode *OrigPhi,
169                                       Instruction *I, ScalarEvolution &SE);
170 
171   /// Returns a struct describing if the instruction is a
172   /// Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern.
173   static InstDesc isConditionalRdxPattern(RecurKind Kind, Instruction *I);
174 
175   /// Returns the opcode corresponding to the RecurrenceKind.
176   static unsigned getOpcode(RecurKind Kind);
177 
178   /// Returns true if Phi is a reduction of type Kind and adds it to the
179   /// RecurrenceDescriptor. If either \p DB is non-null or \p AC and \p DT are
180   /// non-null, the minimal bit width needed to compute the reduction will be
181   /// computed.
182   static bool
183   AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop,
184                   FastMathFlags FuncFMF, RecurrenceDescriptor &RedDes,
185                   DemandedBits *DB = nullptr, AssumptionCache *AC = nullptr,
186                   DominatorTree *DT = nullptr, ScalarEvolution *SE = nullptr);
187 
188   /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor
189   /// is returned in RedDes. If either \p DB is non-null or \p AC and \p DT are
190   /// non-null, the minimal bit width needed to compute the reduction will be
191   /// computed. If \p SE is non-null, store instructions to loop invariant
192   /// addresses are processed.
193   static bool
194   isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes,
195                  DemandedBits *DB = nullptr, AssumptionCache *AC = nullptr,
196                  DominatorTree *DT = nullptr, ScalarEvolution *SE = nullptr);
197 
198   /// Returns true if Phi is a fixed-order recurrence. A fixed-order recurrence
199   /// is a non-reduction recurrence relation in which the value of the
200   /// recurrence in the current loop iteration equals a value defined in a
201   /// previous iteration (e.g. if the value is defined in the previous
202   /// iteration, we refer to it as first-order recurrence, if it is defined in
203   /// the iteration before the previous, we refer to it as second-order
204   /// recurrence and so on). Note that this function optimistically assumes that
205   /// uses of the recurrence can be re-ordered if necessary and users need to
206   /// check and perform the re-ordering.
207   static bool isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop,
208                                      DominatorTree *DT);
209 
210   RecurKind getRecurrenceKind() const { return Kind; }
211 
212   unsigned getOpcode() const { return getOpcode(getRecurrenceKind()); }
213 
214   FastMathFlags getFastMathFlags() const { return FMF; }
215 
216   TrackingVH<Value> getRecurrenceStartValue() const { return StartValue; }
217 
218   Instruction *getLoopExitInstr() const { return LoopExitInstr; }
219 
220   /// Returns true if the recurrence has floating-point math that requires
221   /// precise (ordered) operations.
222   bool hasExactFPMath() const { return ExactFPMathInst != nullptr; }
223 
224   /// Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
225   Instruction *getExactFPMathInst() const { return ExactFPMathInst; }
226 
227   /// Returns true if the recurrence kind is an integer kind.
228   static bool isIntegerRecurrenceKind(RecurKind Kind);
229 
230   /// Returns true if the recurrence kind is a floating point kind.
231   static bool isFloatingPointRecurrenceKind(RecurKind Kind);
232 
233   /// Returns true if the recurrence kind is an integer min/max kind.
234   static bool isIntMinMaxRecurrenceKind(RecurKind Kind) {
235     return Kind == RecurKind::UMin || Kind == RecurKind::UMax ||
236            Kind == RecurKind::SMin || Kind == RecurKind::SMax;
237   }
238 
239   /// Returns true if the recurrence kind is a floating-point min/max kind.
240   static bool isFPMinMaxRecurrenceKind(RecurKind Kind) {
241     return Kind == RecurKind::FMin || Kind == RecurKind::FMax ||
242            Kind == RecurKind::FMinimum || Kind == RecurKind::FMaximum;
243   }
244 
245   /// Returns true if the recurrence kind is any min/max kind.
246   static bool isMinMaxRecurrenceKind(RecurKind Kind) {
247     return isIntMinMaxRecurrenceKind(Kind) || isFPMinMaxRecurrenceKind(Kind);
248   }
249 
250   /// Returns true if the recurrence kind is of the form
251   ///   select(cmp(),x,y) where one of (x,y) is loop invariant.
252   static bool isAnyOfRecurrenceKind(RecurKind Kind) {
253     return Kind == RecurKind::IAnyOf || Kind == RecurKind::FAnyOf;
254   }
255 
256   /// Returns true if the recurrence kind is of the form
257   ///   select(cmp(),x,y) where one of (x,y) is increasing loop induction.
258   static bool isFindLastIVRecurrenceKind(RecurKind Kind) {
259     return Kind == RecurKind::IFindLastIV || Kind == RecurKind::FFindLastIV;
260   }
261 
262   /// Returns the type of the recurrence. This type can be narrower than the
263   /// actual type of the Phi if the recurrence has been type-promoted.
264   Type *getRecurrenceType() const { return RecurrenceType; }
265 
266   /// Returns the sentinel value for FindLastIV recurrences to replace the start
267   /// value.
268   Value *getSentinelValue() const {
269     assert(isFindLastIVRecurrenceKind(Kind) && "Unexpected recurrence kind");
270     Type *Ty = StartValue->getType();
271     return ConstantInt::get(Ty,
272                             APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
273   }
274 
275   /// Returns a reference to the instructions used for type-promoting the
276   /// recurrence.
277   const SmallPtrSet<Instruction *, 8> &getCastInsts() const { return CastInsts; }
278 
279   /// Returns the minimum width used by the recurrence in bits.
280   unsigned getMinWidthCastToRecurrenceTypeInBits() const {
281     return MinWidthCastToRecurrenceType;
282   }
283 
284   /// Returns true if all source operands of the recurrence are SExtInsts.
285   bool isSigned() const { return IsSigned; }
286 
287   /// Expose an ordered FP reduction to the instance users.
288   bool isOrdered() const { return IsOrdered; }
289 
290   /// Attempts to find a chain of operations from Phi to LoopExitInst that can
291   /// be treated as a set of reductions instructions for in-loop reductions.
292   SmallVector<Instruction *, 4> getReductionOpChain(PHINode *Phi,
293                                                     Loop *L) const;
294 
295   /// Returns true if the instruction is a call to the llvm.fmuladd intrinsic.
296   static bool isFMulAddIntrinsic(Instruction *I) {
297     return isa<IntrinsicInst>(I) &&
298            cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fmuladd;
299   }
300 
301   /// Reductions may store temporary or final result to an invariant address.
302   /// If there is such a store in the loop then, after successfull run of
303   /// AddReductionVar method, this field will be assigned the last met store.
304   StoreInst *IntermediateStore = nullptr;
305 
306 private:
307   // The starting value of the recurrence.
308   // It does not have to be zero!
309   TrackingVH<Value> StartValue;
310   // The instruction who's value is used outside the loop.
311   Instruction *LoopExitInstr = nullptr;
312   // The kind of the recurrence.
313   RecurKind Kind = RecurKind::None;
314   // The fast-math flags on the recurrent instructions.  We propagate these
315   // fast-math flags into the vectorized FP instructions we generate.
316   FastMathFlags FMF;
317   // First instance of non-reassociative floating-point in the PHI's use-chain.
318   Instruction *ExactFPMathInst = nullptr;
319   // The type of the recurrence.
320   Type *RecurrenceType = nullptr;
321   // True if all source operands of the recurrence are SExtInsts.
322   bool IsSigned = false;
323   // True if this recurrence can be treated as an in-order reduction.
324   // Currently only a non-reassociative FAdd can be considered in-order,
325   // if it is also the only FAdd in the PHI's use chain.
326   bool IsOrdered = false;
327   // Instructions used for type-promoting the recurrence.
328   SmallPtrSet<Instruction *, 8> CastInsts;
329   // The minimum width used by the recurrence.
330   unsigned MinWidthCastToRecurrenceType;
331 };
332 
333 /// A struct for saving information about induction variables.
334 class InductionDescriptor {
335 public:
336   /// This enum represents the kinds of inductions that we support.
337   enum InductionKind {
338     IK_NoInduction,  ///< Not an induction variable.
339     IK_IntInduction, ///< Integer induction variable. Step = C.
340     IK_PtrInduction, ///< Pointer induction var. Step = C.
341     IK_FpInduction   ///< Floating point induction variable.
342   };
343 
344 public:
345   /// Default constructor - creates an invalid induction.
346   InductionDescriptor() = default;
347 
348   Value *getStartValue() const { return StartValue; }
349   InductionKind getKind() const { return IK; }
350   const SCEV *getStep() const { return Step; }
351   BinaryOperator *getInductionBinOp() const { return InductionBinOp; }
352   ConstantInt *getConstIntStepValue() const;
353 
354   /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an
355   /// induction, the induction descriptor \p D will contain the data describing
356   /// this induction. Since Induction Phis can only be present inside loop
357   /// headers, the function will assert if it is passed a Phi whose parent is
358   /// not the loop header. If by some other means the caller has a better SCEV
359   /// expression for \p Phi than the one returned by the ScalarEvolution
360   /// analysis, it can be passed through \p Expr. If the def-use chain
361   /// associated with the phi includes casts (that we know we can ignore
362   /// under proper runtime checks), they are passed through \p CastsToIgnore.
363   static bool
364   isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
365                  InductionDescriptor &D, const SCEV *Expr = nullptr,
366                  SmallVectorImpl<Instruction *> *CastsToIgnore = nullptr);
367 
368   /// Returns true if \p Phi is a floating point induction in the loop \p L.
369   /// If \p Phi is an induction, the induction descriptor \p D will contain
370   /// the data describing this induction.
371   static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
372                                InductionDescriptor &D);
373 
374   /// Returns true if \p Phi is a loop \p L induction, in the context associated
375   /// with the run-time predicate of PSE. If \p Assume is true, this can add
376   /// further SCEV predicates to \p PSE in order to prove that \p Phi is an
377   /// induction.
378   /// If \p Phi is an induction, \p D will contain the data describing this
379   /// induction.
380   static bool isInductionPHI(PHINode *Phi, const Loop *L,
381                              PredicatedScalarEvolution &PSE,
382                              InductionDescriptor &D, bool Assume = false);
383 
384   /// Returns floating-point induction operator that does not allow
385   /// reassociation (transforming the induction requires an override of normal
386   /// floating-point rules).
387   Instruction *getExactFPMathInst() {
388     if (IK == IK_FpInduction && InductionBinOp &&
389         !InductionBinOp->hasAllowReassoc())
390       return InductionBinOp;
391     return nullptr;
392   }
393 
394   /// Returns binary opcode of the induction operator.
395   Instruction::BinaryOps getInductionOpcode() const {
396     return InductionBinOp ? InductionBinOp->getOpcode()
397                           : Instruction::BinaryOpsEnd;
398   }
399 
400   /// Returns a reference to the type cast instructions in the induction
401   /// update chain, that are redundant when guarded with a runtime
402   /// SCEV overflow check.
403   const SmallVectorImpl<Instruction *> &getCastInsts() const {
404     return RedundantCasts;
405   }
406 
407 private:
408   /// Private constructor - used by \c isInductionPHI.
409   InductionDescriptor(Value *Start, InductionKind K, const SCEV *Step,
410                       BinaryOperator *InductionBinOp = nullptr,
411                       SmallVectorImpl<Instruction *> *Casts = nullptr);
412 
413   /// Start value.
414   TrackingVH<Value> StartValue;
415   /// Induction kind.
416   InductionKind IK = IK_NoInduction;
417   /// Step value.
418   const SCEV *Step = nullptr;
419   // Instruction that advances induction variable.
420   BinaryOperator *InductionBinOp = nullptr;
421   // Instructions used for type-casts of the induction variable,
422   // that are redundant when guarded with a runtime SCEV overflow check.
423   SmallVector<Instruction *, 2> RedundantCasts;
424 };
425 
426 } // end namespace llvm
427 
428 #endif // LLVM_ANALYSIS_IVDESCRIPTORS_H
429