LoopVectorizationPlanner.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===//
  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. /// \file
  10. /// This file provides a LoopVectorizationPlanner class.
  11. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  12. /// LoopVectorizationPlanner - drives the vectorization process after having
  13. /// passed Legality checks.
  14. /// The planner builds and optimizes the Vectorization Plans which record the
  15. /// decisions how to vectorize the given loop. In particular, represent the
  16. /// control-flow of the vectorized version, the replication of instructions that
  17. /// are to be scalarized, and interleave access groups.
  18. ///
  19. /// Also provides a VPlan-based builder utility analogous to IRBuilder.
  20. /// It provides an instruction-level API for generating VPInstructions while
  21. /// abstracting away the Recipe manipulation details.
  22. //===----------------------------------------------------------------------===//
  23. #ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
  24. #define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
  25. #include "VPlan.h"
  26. #include "llvm/Support/InstructionCost.h"
  27. namespace llvm {
  28. class LoopInfo;
  29. class LoopVectorizationLegality;
  30. class LoopVectorizationCostModel;
  31. class PredicatedScalarEvolution;
  32. class LoopVectorizeHints;
  33. class OptimizationRemarkEmitter;
  34. class TargetTransformInfo;
  35. class TargetLibraryInfo;
  36. class VPRecipeBuilder;
  37. /// VPlan-based builder utility analogous to IRBuilder.
  38. class VPBuilder {
  39. VPBasicBlock *BB = nullptr;
  40. VPBasicBlock::iterator InsertPt = VPBasicBlock::iterator();
  41. VPInstruction *createInstruction(unsigned Opcode,
  42. ArrayRef<VPValue *> Operands, DebugLoc DL,
  43. const Twine &Name = "") {
  44. VPInstruction *Instr = new VPInstruction(Opcode, Operands, DL, Name);
  45. if (BB)
  46. BB->insert(Instr, InsertPt);
  47. return Instr;
  48. }
  49. VPInstruction *createInstruction(unsigned Opcode,
  50. std::initializer_list<VPValue *> Operands,
  51. DebugLoc DL, const Twine &Name = "") {
  52. return createInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL, Name);
  53. }
  54. public:
  55. VPBuilder() = default;
  56. /// Clear the insertion point: created instructions will not be inserted into
  57. /// a block.
  58. void clearInsertionPoint() {
  59. BB = nullptr;
  60. InsertPt = VPBasicBlock::iterator();
  61. }
  62. VPBasicBlock *getInsertBlock() const { return BB; }
  63. VPBasicBlock::iterator getInsertPoint() const { return InsertPt; }
  64. /// InsertPoint - A saved insertion point.
  65. class VPInsertPoint {
  66. VPBasicBlock *Block = nullptr;
  67. VPBasicBlock::iterator Point;
  68. public:
  69. /// Creates a new insertion point which doesn't point to anything.
  70. VPInsertPoint() = default;
  71. /// Creates a new insertion point at the given location.
  72. VPInsertPoint(VPBasicBlock *InsertBlock, VPBasicBlock::iterator InsertPoint)
  73. : Block(InsertBlock), Point(InsertPoint) {}
  74. /// Returns true if this insert point is set.
  75. bool isSet() const { return Block != nullptr; }
  76. VPBasicBlock *getBlock() const { return Block; }
  77. VPBasicBlock::iterator getPoint() const { return Point; }
  78. };
  79. /// Sets the current insert point to a previously-saved location.
  80. void restoreIP(VPInsertPoint IP) {
  81. if (IP.isSet())
  82. setInsertPoint(IP.getBlock(), IP.getPoint());
  83. else
  84. clearInsertionPoint();
  85. }
  86. /// This specifies that created VPInstructions should be appended to the end
  87. /// of the specified block.
  88. void setInsertPoint(VPBasicBlock *TheBB) {
  89. assert(TheBB && "Attempting to set a null insert point");
  90. BB = TheBB;
  91. InsertPt = BB->end();
  92. }
  93. /// This specifies that created instructions should be inserted at the
  94. /// specified point.
  95. void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP) {
  96. BB = TheBB;
  97. InsertPt = IP;
  98. }
  99. /// Insert and return the specified instruction.
  100. VPInstruction *insert(VPInstruction *I) const {
  101. BB->insert(I, InsertPt);
  102. return I;
  103. }
  104. /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
  105. /// its underlying Instruction.
  106. VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
  107. Instruction *Inst = nullptr, const Twine &Name = "") {
  108. DebugLoc DL;
  109. if (Inst)
  110. DL = Inst->getDebugLoc();
  111. VPInstruction *NewVPInst = createInstruction(Opcode, Operands, DL, Name);
  112. NewVPInst->setUnderlyingValue(Inst);
  113. return NewVPInst;
  114. }
  115. VPValue *createNaryOp(unsigned Opcode, ArrayRef<VPValue *> Operands,
  116. DebugLoc DL, const Twine &Name = "") {
  117. return createInstruction(Opcode, Operands, DL, Name);
  118. }
  119. VPValue *createNot(VPValue *Operand, DebugLoc DL, const Twine &Name = "") {
  120. return createInstruction(VPInstruction::Not, {Operand}, DL, Name);
  121. }
  122. VPValue *createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL,
  123. const Twine &Name = "") {
  124. return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, DL, Name);
  125. }
  126. VPValue *createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL,
  127. const Twine &Name = "") {
  128. return createInstruction(Instruction::BinaryOps::Or, {LHS, RHS}, DL, Name);
  129. }
  130. VPValue *createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal,
  131. DebugLoc DL, const Twine &Name = "") {
  132. return createNaryOp(Instruction::Select, {Cond, TrueVal, FalseVal}, DL,
  133. Name);
  134. }
  135. //===--------------------------------------------------------------------===//
  136. // RAII helpers.
  137. //===--------------------------------------------------------------------===//
  138. /// RAII object that stores the current insertion point and restores it when
  139. /// the object is destroyed.
  140. class InsertPointGuard {
  141. VPBuilder &Builder;
  142. VPBasicBlock *Block;
  143. VPBasicBlock::iterator Point;
  144. public:
  145. InsertPointGuard(VPBuilder &B)
  146. : Builder(B), Block(B.getInsertBlock()), Point(B.getInsertPoint()) {}
  147. InsertPointGuard(const InsertPointGuard &) = delete;
  148. InsertPointGuard &operator=(const InsertPointGuard &) = delete;
  149. ~InsertPointGuard() { Builder.restoreIP(VPInsertPoint(Block, Point)); }
  150. };
  151. };
  152. /// TODO: The following VectorizationFactor was pulled out of
  153. /// LoopVectorizationCostModel class. LV also deals with
  154. /// VectorizerParams::VectorizationFactor and VectorizationCostTy.
  155. /// We need to streamline them.
  156. /// Information about vectorization costs.
  157. struct VectorizationFactor {
  158. /// Vector width with best cost.
  159. ElementCount Width;
  160. /// Cost of the loop with that width.
  161. InstructionCost Cost;
  162. /// Cost of the scalar loop.
  163. InstructionCost ScalarCost;
  164. /// The minimum trip count required to make vectorization profitable, e.g. due
  165. /// to runtime checks.
  166. ElementCount MinProfitableTripCount;
  167. VectorizationFactor(ElementCount Width, InstructionCost Cost,
  168. InstructionCost ScalarCost)
  169. : Width(Width), Cost(Cost), ScalarCost(ScalarCost) {}
  170. /// Width 1 means no vectorization, cost 0 means uncomputed cost.
  171. static VectorizationFactor Disabled() {
  172. return {ElementCount::getFixed(1), 0, 0};
  173. }
  174. bool operator==(const VectorizationFactor &rhs) const {
  175. return Width == rhs.Width && Cost == rhs.Cost;
  176. }
  177. bool operator!=(const VectorizationFactor &rhs) const {
  178. return !(*this == rhs);
  179. }
  180. };
  181. /// A class that represents two vectorization factors (initialized with 0 by
  182. /// default). One for fixed-width vectorization and one for scalable
  183. /// vectorization. This can be used by the vectorizer to choose from a range of
  184. /// fixed and/or scalable VFs in order to find the most cost-effective VF to
  185. /// vectorize with.
  186. struct FixedScalableVFPair {
  187. ElementCount FixedVF;
  188. ElementCount ScalableVF;
  189. FixedScalableVFPair()
  190. : FixedVF(ElementCount::getFixed(0)),
  191. ScalableVF(ElementCount::getScalable(0)) {}
  192. FixedScalableVFPair(const ElementCount &Max) : FixedScalableVFPair() {
  193. *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
  194. }
  195. FixedScalableVFPair(const ElementCount &FixedVF,
  196. const ElementCount &ScalableVF)
  197. : FixedVF(FixedVF), ScalableVF(ScalableVF) {
  198. assert(!FixedVF.isScalable() && ScalableVF.isScalable() &&
  199. "Invalid scalable properties");
  200. }
  201. static FixedScalableVFPair getNone() { return FixedScalableVFPair(); }
  202. /// \return true if either fixed- or scalable VF is non-zero.
  203. explicit operator bool() const { return FixedVF || ScalableVF; }
  204. /// \return true if either fixed- or scalable VF is a valid vector VF.
  205. bool hasVector() const { return FixedVF.isVector() || ScalableVF.isVector(); }
  206. };
  207. /// Planner drives the vectorization process after having passed
  208. /// Legality checks.
  209. class LoopVectorizationPlanner {
  210. /// The loop that we evaluate.
  211. Loop *OrigLoop;
  212. /// Loop Info analysis.
  213. LoopInfo *LI;
  214. /// Target Library Info.
  215. const TargetLibraryInfo *TLI;
  216. /// Target Transform Info.
  217. const TargetTransformInfo *TTI;
  218. /// The legality analysis.
  219. LoopVectorizationLegality *Legal;
  220. /// The profitability analysis.
  221. LoopVectorizationCostModel &CM;
  222. /// The interleaved access analysis.
  223. InterleavedAccessInfo &IAI;
  224. PredicatedScalarEvolution &PSE;
  225. const LoopVectorizeHints &Hints;
  226. OptimizationRemarkEmitter *ORE;
  227. SmallVector<VPlanPtr, 4> VPlans;
  228. /// A builder used to construct the current plan.
  229. VPBuilder Builder;
  230. public:
  231. LoopVectorizationPlanner(Loop *L, LoopInfo *LI, const TargetLibraryInfo *TLI,
  232. const TargetTransformInfo *TTI,
  233. LoopVectorizationLegality *Legal,
  234. LoopVectorizationCostModel &CM,
  235. InterleavedAccessInfo &IAI,
  236. PredicatedScalarEvolution &PSE,
  237. const LoopVectorizeHints &Hints,
  238. OptimizationRemarkEmitter *ORE)
  239. : OrigLoop(L), LI(LI), TLI(TLI), TTI(TTI), Legal(Legal), CM(CM), IAI(IAI),
  240. PSE(PSE), Hints(Hints), ORE(ORE) {}
  241. /// Plan how to best vectorize, return the best VF and its cost, or
  242. /// std::nullopt if vectorization and interleaving should be avoided up front.
  243. std::optional<VectorizationFactor> plan(ElementCount UserVF, unsigned UserIC);
  244. /// Use the VPlan-native path to plan how to best vectorize, return the best
  245. /// VF and its cost.
  246. VectorizationFactor planInVPlanNativePath(ElementCount UserVF);
  247. /// Return the best VPlan for \p VF.
  248. VPlan &getBestPlanFor(ElementCount VF) const;
  249. /// Generate the IR code for the body of the vectorized loop according to the
  250. /// best selected \p VF, \p UF and VPlan \p BestPlan.
  251. /// TODO: \p IsEpilogueVectorization is needed to avoid issues due to epilogue
  252. /// vectorization re-using plans for both the main and epilogue vector loops.
  253. /// It should be removed once the re-use issue has been fixed.
  254. void executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
  255. InnerLoopVectorizer &LB, DominatorTree *DT,
  256. bool IsEpilogueVectorization);
  257. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  258. void printPlans(raw_ostream &O);
  259. #endif
  260. /// Look through the existing plans and return true if we have one with all
  261. /// the vectorization factors in question.
  262. bool hasPlanWithVF(ElementCount VF) const {
  263. return any_of(VPlans,
  264. [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
  265. }
  266. /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
  267. /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
  268. /// returned value holds for the entire \p Range.
  269. static bool
  270. getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
  271. VFRange &Range);
  272. /// Check if the number of runtime checks exceeds the threshold.
  273. bool requiresTooManyRuntimeChecks() const;
  274. protected:
  275. /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
  276. /// according to the information gathered by Legal when it checked if it is
  277. /// legal to vectorize the loop.
  278. void buildVPlans(ElementCount MinVF, ElementCount MaxVF);
  279. private:
  280. /// Build a VPlan according to the information gathered by Legal. \return a
  281. /// VPlan for vectorization factors \p Range.Start and up to \p Range.End
  282. /// exclusive, possibly decreasing \p Range.End.
  283. VPlanPtr buildVPlan(VFRange &Range);
  284. /// Build a VPlan using VPRecipes according to the information gather by
  285. /// Legal. This method is only used for the legacy inner loop vectorizer.
  286. VPlanPtr buildVPlanWithVPRecipes(
  287. VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
  288. const MapVector<Instruction *, Instruction *> &SinkAfter);
  289. /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
  290. /// according to the information gathered by Legal when it checked if it is
  291. /// legal to vectorize the loop. This method creates VPlans using VPRecipes.
  292. void buildVPlansWithVPRecipes(ElementCount MinVF, ElementCount MaxVF);
  293. // Adjust the recipes for reductions. For in-loop reductions the chain of
  294. // instructions leading from the loop exit instr to the phi need to be
  295. // converted to reductions, with one operand being vector and the other being
  296. // the scalar reduction chain. For other reductions, a select is introduced
  297. // between the phi and live-out recipes when folding the tail.
  298. void adjustRecipesForReductions(VPBasicBlock *LatchVPBB, VPlanPtr &Plan,
  299. VPRecipeBuilder &RecipeBuilder,
  300. ElementCount MinVF);
  301. };
  302. } // namespace llvm
  303. #endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H