IVDescriptors.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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/DenseMap.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/IR/InstrTypes.h"
  24. #include "llvm/IR/Instruction.h"
  25. #include "llvm/IR/Operator.h"
  26. #include "llvm/IR/ValueHandle.h"
  27. #include "llvm/Support/Casting.h"
  28. namespace llvm {
  29. class DemandedBits;
  30. class AssumptionCache;
  31. class Loop;
  32. class PredicatedScalarEvolution;
  33. class ScalarEvolution;
  34. class SCEV;
  35. class DominatorTree;
  36. /// These are the kinds of recurrences that we support.
  37. enum class RecurKind {
  38. None, ///< Not a recurrence.
  39. Add, ///< Sum of integers.
  40. Mul, ///< Product of integers.
  41. Or, ///< Bitwise or logical OR of integers.
  42. And, ///< Bitwise or logical AND of integers.
  43. Xor, ///< Bitwise or logical XOR of integers.
  44. SMin, ///< Signed integer min implemented in terms of select(cmp()).
  45. SMax, ///< Signed integer max implemented in terms of select(cmp()).
  46. UMin, ///< Unisgned integer min implemented in terms of select(cmp()).
  47. UMax, ///< Unsigned integer max implemented in terms of select(cmp()).
  48. FAdd, ///< Sum of floats.
  49. FMul, ///< Product of floats.
  50. FMin, ///< FP min implemented in terms of select(cmp()).
  51. FMax ///< FP max implemented in terms of select(cmp()).
  52. };
  53. /// The RecurrenceDescriptor is used to identify recurrences variables in a
  54. /// loop. Reduction is a special case of recurrence that has uses of the
  55. /// recurrence variable outside the loop. The method isReductionPHI identifies
  56. /// reductions that are basic recurrences.
  57. ///
  58. /// Basic recurrences are defined as the summation, product, OR, AND, XOR, min,
  59. /// or max of a set of terms. For example: for(i=0; i<n; i++) { total +=
  60. /// array[i]; } is a summation of array elements. Basic recurrences are a
  61. /// special case of chains of recurrences (CR). See ScalarEvolution for CR
  62. /// references.
  63. /// This struct holds information about recurrence variables.
  64. class RecurrenceDescriptor {
  65. public:
  66. RecurrenceDescriptor() = default;
  67. RecurrenceDescriptor(Value *Start, Instruction *Exit, RecurKind K,
  68. FastMathFlags FMF, Instruction *UAI, Type *RT,
  69. bool Signed, SmallPtrSetImpl<Instruction *> &CI)
  70. : StartValue(Start), LoopExitInstr(Exit), Kind(K), FMF(FMF),
  71. UnsafeAlgebraInst(UAI), RecurrenceType(RT), IsSigned(Signed) {
  72. CastInsts.insert(CI.begin(), CI.end());
  73. }
  74. /// This POD struct holds information about a potential recurrence operation.
  75. class InstDesc {
  76. public:
  77. InstDesc(bool IsRecur, Instruction *I, Instruction *UAI = nullptr)
  78. : IsRecurrence(IsRecur), PatternLastInst(I),
  79. RecKind(RecurKind::None), UnsafeAlgebraInst(UAI) {}
  80. InstDesc(Instruction *I, RecurKind K, Instruction *UAI = nullptr)
  81. : IsRecurrence(true), PatternLastInst(I), RecKind(K),
  82. UnsafeAlgebraInst(UAI) {}
  83. bool isRecurrence() const { return IsRecurrence; }
  84. bool hasUnsafeAlgebra() const { return UnsafeAlgebraInst != nullptr; }
  85. Instruction *getUnsafeAlgebraInst() const { return UnsafeAlgebraInst; }
  86. RecurKind getRecKind() const { return RecKind; }
  87. Instruction *getPatternInst() const { return PatternLastInst; }
  88. private:
  89. // Is this instruction a recurrence candidate.
  90. bool IsRecurrence;
  91. // The last instruction in a min/max pattern (select of the select(icmp())
  92. // pattern), or the current recurrence instruction otherwise.
  93. Instruction *PatternLastInst;
  94. // If this is a min/max pattern.
  95. RecurKind RecKind;
  96. // Recurrence has unsafe algebra.
  97. Instruction *UnsafeAlgebraInst;
  98. };
  99. /// Returns a struct describing if the instruction 'I' can be a recurrence
  100. /// variable of type 'Kind'. If the recurrence is a min/max pattern of
  101. /// select(icmp()) this function advances the instruction pointer 'I' from the
  102. /// compare instruction to the select instruction and stores this pointer in
  103. /// 'PatternLastInst' member of the returned struct.
  104. static InstDesc isRecurrenceInstr(Instruction *I, RecurKind Kind,
  105. InstDesc &Prev, bool HasFunNoNaNAttr);
  106. /// Returns true if instruction I has multiple uses in Insts
  107. static bool hasMultipleUsesOf(Instruction *I,
  108. SmallPtrSetImpl<Instruction *> &Insts,
  109. unsigned MaxNumUses);
  110. /// Returns true if all uses of the instruction I is within the Set.
  111. static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set);
  112. /// Returns a struct describing if the instruction is a
  113. /// Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y)
  114. /// or max(X, Y). \p Prev specifies the description of an already processed
  115. /// select instruction, so its corresponding cmp can be matched to it.
  116. static InstDesc isMinMaxSelectCmpPattern(Instruction *I,
  117. const InstDesc &Prev);
  118. /// Returns a struct describing if the instruction is a
  119. /// Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern.
  120. static InstDesc isConditionalRdxPattern(RecurKind Kind, Instruction *I);
  121. /// Returns identity corresponding to the RecurrenceKind.
  122. static Constant *getRecurrenceIdentity(RecurKind K, Type *Tp);
  123. /// Returns the opcode corresponding to the RecurrenceKind.
  124. static unsigned getOpcode(RecurKind Kind);
  125. /// Returns true if Phi is a reduction of type Kind and adds it to the
  126. /// RecurrenceDescriptor. If either \p DB is non-null or \p AC and \p DT are
  127. /// non-null, the minimal bit width needed to compute the reduction will be
  128. /// computed.
  129. static bool AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop,
  130. bool HasFunNoNaNAttr,
  131. RecurrenceDescriptor &RedDes,
  132. DemandedBits *DB = nullptr,
  133. AssumptionCache *AC = nullptr,
  134. DominatorTree *DT = nullptr);
  135. /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor
  136. /// is returned in RedDes. If either \p DB is non-null or \p AC and \p DT are
  137. /// non-null, the minimal bit width needed to compute the reduction will be
  138. /// computed.
  139. static bool isReductionPHI(PHINode *Phi, Loop *TheLoop,
  140. RecurrenceDescriptor &RedDes,
  141. DemandedBits *DB = nullptr,
  142. AssumptionCache *AC = nullptr,
  143. DominatorTree *DT = nullptr);
  144. /// Returns true if Phi is a first-order recurrence. A first-order recurrence
  145. /// is a non-reduction recurrence relation in which the value of the
  146. /// recurrence in the current loop iteration equals a value defined in the
  147. /// previous iteration. \p SinkAfter includes pairs of instructions where the
  148. /// first will be rescheduled to appear after the second if/when the loop is
  149. /// vectorized. It may be augmented with additional pairs if needed in order
  150. /// to handle Phi as a first-order recurrence.
  151. static bool
  152. isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
  153. DenseMap<Instruction *, Instruction *> &SinkAfter,
  154. DominatorTree *DT);
  155. RecurKind getRecurrenceKind() const { return Kind; }
  156. unsigned getOpcode() const { return getOpcode(getRecurrenceKind()); }
  157. FastMathFlags getFastMathFlags() const { return FMF; }
  158. TrackingVH<Value> getRecurrenceStartValue() const { return StartValue; }
  159. Instruction *getLoopExitInstr() const { return LoopExitInstr; }
  160. /// Returns true if the recurrence has unsafe algebra which requires a relaxed
  161. /// floating-point model.
  162. bool hasUnsafeAlgebra() const { return UnsafeAlgebraInst != nullptr; }
  163. /// Returns first unsafe algebra instruction in the PHI node's use-chain.
  164. Instruction *getUnsafeAlgebraInst() const { return UnsafeAlgebraInst; }
  165. /// Returns true if the recurrence kind is an integer kind.
  166. static bool isIntegerRecurrenceKind(RecurKind Kind);
  167. /// Returns true if the recurrence kind is a floating point kind.
  168. static bool isFloatingPointRecurrenceKind(RecurKind Kind);
  169. /// Returns true if the recurrence kind is an arithmetic kind.
  170. static bool isArithmeticRecurrenceKind(RecurKind Kind);
  171. /// Returns true if the recurrence kind is an integer min/max kind.
  172. static bool isIntMinMaxRecurrenceKind(RecurKind Kind) {
  173. return Kind == RecurKind::UMin || Kind == RecurKind::UMax ||
  174. Kind == RecurKind::SMin || Kind == RecurKind::SMax;
  175. }
  176. /// Returns true if the recurrence kind is a floating-point min/max kind.
  177. static bool isFPMinMaxRecurrenceKind(RecurKind Kind) {
  178. return Kind == RecurKind::FMin || Kind == RecurKind::FMax;
  179. }
  180. /// Returns true if the recurrence kind is any min/max kind.
  181. static bool isMinMaxRecurrenceKind(RecurKind Kind) {
  182. return isIntMinMaxRecurrenceKind(Kind) || isFPMinMaxRecurrenceKind(Kind);
  183. }
  184. /// Returns the type of the recurrence. This type can be narrower than the
  185. /// actual type of the Phi if the recurrence has been type-promoted.
  186. Type *getRecurrenceType() const { return RecurrenceType; }
  187. /// Returns a reference to the instructions used for type-promoting the
  188. /// recurrence.
  189. const SmallPtrSet<Instruction *, 8> &getCastInsts() const { return CastInsts; }
  190. /// Returns true if all source operands of the recurrence are SExtInsts.
  191. bool isSigned() const { return IsSigned; }
  192. /// Attempts to find a chain of operations from Phi to LoopExitInst that can
  193. /// be treated as a set of reductions instructions for in-loop reductions.
  194. SmallVector<Instruction *, 4> getReductionOpChain(PHINode *Phi,
  195. Loop *L) const;
  196. private:
  197. // The starting value of the recurrence.
  198. // It does not have to be zero!
  199. TrackingVH<Value> StartValue;
  200. // The instruction who's value is used outside the loop.
  201. Instruction *LoopExitInstr = nullptr;
  202. // The kind of the recurrence.
  203. RecurKind Kind = RecurKind::None;
  204. // The fast-math flags on the recurrent instructions. We propagate these
  205. // fast-math flags into the vectorized FP instructions we generate.
  206. FastMathFlags FMF;
  207. // First occurrence of unasfe algebra in the PHI's use-chain.
  208. Instruction *UnsafeAlgebraInst = nullptr;
  209. // The type of the recurrence.
  210. Type *RecurrenceType = nullptr;
  211. // True if all source operands of the recurrence are SExtInsts.
  212. bool IsSigned = false;
  213. // Instructions used for type-promoting the recurrence.
  214. SmallPtrSet<Instruction *, 8> CastInsts;
  215. };
  216. /// A struct for saving information about induction variables.
  217. class InductionDescriptor {
  218. public:
  219. /// This enum represents the kinds of inductions that we support.
  220. enum InductionKind {
  221. IK_NoInduction, ///< Not an induction variable.
  222. IK_IntInduction, ///< Integer induction variable. Step = C.
  223. IK_PtrInduction, ///< Pointer induction var. Step = C / sizeof(elem).
  224. IK_FpInduction ///< Floating point induction variable.
  225. };
  226. public:
  227. /// Default constructor - creates an invalid induction.
  228. InductionDescriptor() = default;
  229. Value *getStartValue() const { return StartValue; }
  230. InductionKind getKind() const { return IK; }
  231. const SCEV *getStep() const { return Step; }
  232. BinaryOperator *getInductionBinOp() const { return InductionBinOp; }
  233. ConstantInt *getConstIntStepValue() const;
  234. /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an
  235. /// induction, the induction descriptor \p D will contain the data describing
  236. /// this induction. If by some other means the caller has a better SCEV
  237. /// expression for \p Phi than the one returned by the ScalarEvolution
  238. /// analysis, it can be passed through \p Expr. If the def-use chain
  239. /// associated with the phi includes casts (that we know we can ignore
  240. /// under proper runtime checks), they are passed through \p CastsToIgnore.
  241. static bool
  242. isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
  243. InductionDescriptor &D, const SCEV *Expr = nullptr,
  244. SmallVectorImpl<Instruction *> *CastsToIgnore = nullptr);
  245. /// Returns true if \p Phi is a floating point induction in the loop \p L.
  246. /// If \p Phi is an induction, the induction descriptor \p D will contain
  247. /// the data describing this induction.
  248. static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
  249. InductionDescriptor &D);
  250. /// Returns true if \p Phi is a loop \p L induction, in the context associated
  251. /// with the run-time predicate of PSE. If \p Assume is true, this can add
  252. /// further SCEV predicates to \p PSE in order to prove that \p Phi is an
  253. /// induction.
  254. /// If \p Phi is an induction, \p D will contain the data describing this
  255. /// induction.
  256. static bool isInductionPHI(PHINode *Phi, const Loop *L,
  257. PredicatedScalarEvolution &PSE,
  258. InductionDescriptor &D, bool Assume = false);
  259. /// Returns true if the induction type is FP and the binary operator does
  260. /// not have the "fast-math" property. Such operation requires a relaxed FP
  261. /// mode.
  262. bool hasUnsafeAlgebra() {
  263. return (IK == IK_FpInduction) && InductionBinOp &&
  264. !cast<FPMathOperator>(InductionBinOp)->isFast();
  265. }
  266. /// Returns induction operator that does not have "fast-math" property
  267. /// and requires FP unsafe mode.
  268. Instruction *getUnsafeAlgebraInst() {
  269. if (IK != IK_FpInduction)
  270. return nullptr;
  271. if (!InductionBinOp || cast<FPMathOperator>(InductionBinOp)->isFast())
  272. return nullptr;
  273. return InductionBinOp;
  274. }
  275. /// Returns binary opcode of the induction operator.
  276. Instruction::BinaryOps getInductionOpcode() const {
  277. return InductionBinOp ? InductionBinOp->getOpcode()
  278. : Instruction::BinaryOpsEnd;
  279. }
  280. /// Returns a reference to the type cast instructions in the induction
  281. /// update chain, that are redundant when guarded with a runtime
  282. /// SCEV overflow check.
  283. const SmallVectorImpl<Instruction *> &getCastInsts() const {
  284. return RedundantCasts;
  285. }
  286. private:
  287. /// Private constructor - used by \c isInductionPHI.
  288. InductionDescriptor(Value *Start, InductionKind K, const SCEV *Step,
  289. BinaryOperator *InductionBinOp = nullptr,
  290. SmallVectorImpl<Instruction *> *Casts = nullptr);
  291. /// Start value.
  292. TrackingVH<Value> StartValue;
  293. /// Induction kind.
  294. InductionKind IK = IK_NoInduction;
  295. /// Step value.
  296. const SCEV *Step = nullptr;
  297. // Instruction that advances induction variable.
  298. BinaryOperator *InductionBinOp = nullptr;
  299. // Instructions used for type-casts of the induction variable,
  300. // that are redundant when guarded with a runtime SCEV overflow check.
  301. SmallVector<Instruction *, 2> RedundantCasts;
  302. };
  303. } // end namespace llvm
  304. #endif // LLVM_ANALYSIS_IVDESCRIPTORS_H
  305. #ifdef __GNUC__
  306. #pragma GCC diagnostic pop
  307. #endif