IVDescriptors.h 18 KB

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