1 //===- VPlan.h - Represent A Vectorizer Plan --------------------*- 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 /// \file
10 /// This file contains the declarations of the Vectorization Plan base classes:
11 /// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12 ///    VPBlockBase, together implementing a Hierarchical CFG;
13 /// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
14 ///    treated as proper graphs for generic algorithms;
15 /// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
16 ///    within VPBasicBlocks;
17 /// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18 ///    instruction;
19 /// 5. The VPlan class holding a candidate for vectorization;
20 /// 6. The VPlanPrinter class providing a way to print a plan in dot format;
21 /// These are documented in docs/VectorizationPlan.rst.
22 //
23 //===----------------------------------------------------------------------===//
24 
25 #ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26 #define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27 
28 #include "VPlanLoopInfo.h"
29 #include "VPlanValue.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/DepthFirstIterator.h"
32 #include "llvm/ADT/GraphTraits.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/SmallBitVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/ADT/ilist.h"
40 #include "llvm/ADT/ilist_node.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <cstddef>
46 #include <map>
47 #include <string>
48 
49 namespace llvm {
50 
51 class BasicBlock;
52 class DominatorTree;
53 class InnerLoopVectorizer;
54 class LoopInfo;
55 class raw_ostream;
56 class RecurrenceDescriptor;
57 class Value;
58 class VPBasicBlock;
59 class VPRegionBlock;
60 class VPlan;
61 class VPlanSlp;
62 
63 /// Returns a calculation for the total number of elements for a given \p VF.
64 /// For fixed width vectors this value is a constant, whereas for scalable
65 /// vectors it is an expression determined at runtime.
66 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF);
67 
68 /// A range of powers-of-2 vectorization factors with fixed start and
69 /// adjustable end. The range includes start and excludes end, e.g.,:
70 /// [1, 9) = {1, 2, 4, 8}
71 struct VFRange {
72   // A power of 2.
73   const ElementCount Start;
74 
75   // Need not be a power of 2. If End <= Start range is empty.
76   ElementCount End;
77 
78   bool isEmpty() const {
79     return End.getKnownMinValue() <= Start.getKnownMinValue();
80   }
81 
82   VFRange(const ElementCount &Start, const ElementCount &End)
83       : Start(Start), End(End) {
84     assert(Start.isScalable() == End.isScalable() &&
85            "Both Start and End should have the same scalable flag");
86     assert(isPowerOf2_32(Start.getKnownMinValue()) &&
87            "Expected Start to be a power of 2");
88   }
89 };
90 
91 using VPlanPtr = std::unique_ptr<VPlan>;
92 
93 /// In what follows, the term "input IR" refers to code that is fed into the
94 /// vectorizer whereas the term "output IR" refers to code that is generated by
95 /// the vectorizer.
96 
97 /// VPLane provides a way to access lanes in both fixed width and scalable
98 /// vectors, where for the latter the lane index sometimes needs calculating
99 /// as a runtime expression.
100 class VPLane {
101 public:
102   /// Kind describes how to interpret Lane.
103   enum class Kind : uint8_t {
104     /// For First, Lane is the index into the first N elements of a
105     /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>.
106     First,
107     /// For ScalableLast, Lane is the offset from the start of the last
108     /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For
109     /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of
110     /// 1 corresponds to `((vscale - 1) * N) + 1`, etc.
111     ScalableLast
112   };
113 
114 private:
115   /// in [0..VF)
116   unsigned Lane;
117 
118   /// Indicates how the Lane should be interpreted, as described above.
119   Kind LaneKind;
120 
121 public:
122   VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {}
123 
124   static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); }
125 
126   static VPLane getLastLaneForVF(const ElementCount &VF) {
127     unsigned LaneOffset = VF.getKnownMinValue() - 1;
128     Kind LaneKind;
129     if (VF.isScalable())
130       // In this case 'LaneOffset' refers to the offset from the start of the
131       // last subvector with VF.getKnownMinValue() elements.
132       LaneKind = VPLane::Kind::ScalableLast;
133     else
134       LaneKind = VPLane::Kind::First;
135     return VPLane(LaneOffset, LaneKind);
136   }
137 
138   /// Returns a compile-time known value for the lane index and asserts if the
139   /// lane can only be calculated at runtime.
140   unsigned getKnownLane() const {
141     assert(LaneKind == Kind::First);
142     return Lane;
143   }
144 
145   /// Returns an expression describing the lane index that can be used at
146   /// runtime.
147   Value *getAsRuntimeExpr(IRBuilder<> &Builder, const ElementCount &VF) const;
148 
149   /// Returns the Kind of lane offset.
150   Kind getKind() const { return LaneKind; }
151 
152   /// Returns true if this is the first lane of the whole vector.
153   bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; }
154 
155   /// Maps the lane to a cache index based on \p VF.
156   unsigned mapToCacheIndex(const ElementCount &VF) const {
157     switch (LaneKind) {
158     case VPLane::Kind::ScalableLast:
159       assert(VF.isScalable() && Lane < VF.getKnownMinValue());
160       return VF.getKnownMinValue() + Lane;
161     default:
162       assert(Lane < VF.getKnownMinValue());
163       return Lane;
164     }
165   }
166 
167   /// Returns the maxmimum number of lanes that we are able to consider
168   /// caching for \p VF.
169   static unsigned getNumCachedLanes(const ElementCount &VF) {
170     return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1);
171   }
172 };
173 
174 /// VPIteration represents a single point in the iteration space of the output
175 /// (vectorized and/or unrolled) IR loop.
176 struct VPIteration {
177   /// in [0..UF)
178   unsigned Part;
179 
180   VPLane Lane;
181 
182   VPIteration(unsigned Part, unsigned Lane,
183               VPLane::Kind Kind = VPLane::Kind::First)
184       : Part(Part), Lane(Lane, Kind) {}
185 
186   VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {}
187 
188   bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); }
189 };
190 
191 /// VPTransformState holds information passed down when "executing" a VPlan,
192 /// needed for generating the output IR.
193 struct VPTransformState {
194   VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
195                    DominatorTree *DT, IRBuilder<> &Builder,
196                    InnerLoopVectorizer *ILV, VPlan *Plan)
197       : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder), ILV(ILV),
198         Plan(Plan) {}
199 
200   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
201   ElementCount VF;
202   unsigned UF;
203 
204   /// Hold the indices to generate specific scalar instructions. Null indicates
205   /// that all instances are to be generated, using either scalar or vector
206   /// instructions.
207   Optional<VPIteration> Instance;
208 
209   struct DataState {
210     /// A type for vectorized values in the new loop. Each value from the
211     /// original loop, when vectorized, is represented by UF vector values in
212     /// the new unrolled loop, where UF is the unroll factor.
213     typedef SmallVector<Value *, 2> PerPartValuesTy;
214 
215     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
216 
217     using ScalarsPerPartValuesTy = SmallVector<SmallVector<Value *, 4>, 2>;
218     DenseMap<VPValue *, ScalarsPerPartValuesTy> PerPartScalars;
219   } Data;
220 
221   /// Get the generated Value for a given VPValue and a given Part. Note that
222   /// as some Defs are still created by ILV and managed in its ValueMap, this
223   /// method will delegate the call to ILV in such cases in order to provide
224   /// callers a consistent API.
225   /// \see set.
226   Value *get(VPValue *Def, unsigned Part);
227 
228   /// Get the generated Value for a given VPValue and given Part and Lane.
229   Value *get(VPValue *Def, const VPIteration &Instance);
230 
231   bool hasVectorValue(VPValue *Def, unsigned Part) {
232     auto I = Data.PerPartOutput.find(Def);
233     return I != Data.PerPartOutput.end() && Part < I->second.size() &&
234            I->second[Part];
235   }
236 
237   bool hasAnyVectorValue(VPValue *Def) const {
238     return Data.PerPartOutput.find(Def) != Data.PerPartOutput.end();
239   }
240 
241   bool hasScalarValue(VPValue *Def, VPIteration Instance) {
242     auto I = Data.PerPartScalars.find(Def);
243     if (I == Data.PerPartScalars.end())
244       return false;
245     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
246     return Instance.Part < I->second.size() &&
247            CacheIdx < I->second[Instance.Part].size() &&
248            I->second[Instance.Part][CacheIdx];
249   }
250 
251   /// Set the generated Value for a given VPValue and a given Part.
252   void set(VPValue *Def, Value *V, unsigned Part) {
253     if (!Data.PerPartOutput.count(Def)) {
254       DataState::PerPartValuesTy Entry(UF);
255       Data.PerPartOutput[Def] = Entry;
256     }
257     Data.PerPartOutput[Def][Part] = V;
258   }
259   /// Reset an existing vector value for \p Def and a given \p Part.
260   void reset(VPValue *Def, Value *V, unsigned Part) {
261     auto Iter = Data.PerPartOutput.find(Def);
262     assert(Iter != Data.PerPartOutput.end() &&
263            "need to overwrite existing value");
264     Iter->second[Part] = V;
265   }
266 
267   /// Set the generated scalar \p V for \p Def and the given \p Instance.
268   void set(VPValue *Def, Value *V, const VPIteration &Instance) {
269     auto Iter = Data.PerPartScalars.insert({Def, {}});
270     auto &PerPartVec = Iter.first->second;
271     while (PerPartVec.size() <= Instance.Part)
272       PerPartVec.emplace_back();
273     auto &Scalars = PerPartVec[Instance.Part];
274     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
275     while (Scalars.size() <= CacheIdx)
276       Scalars.push_back(nullptr);
277     assert(!Scalars[CacheIdx] && "should overwrite existing value");
278     Scalars[CacheIdx] = V;
279   }
280 
281   /// Reset an existing scalar value for \p Def and a given \p Instance.
282   void reset(VPValue *Def, Value *V, const VPIteration &Instance) {
283     auto Iter = Data.PerPartScalars.find(Def);
284     assert(Iter != Data.PerPartScalars.end() &&
285            "need to overwrite existing value");
286     assert(Instance.Part < Iter->second.size() &&
287            "need to overwrite existing value");
288     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
289     assert(CacheIdx < Iter->second[Instance.Part].size() &&
290            "need to overwrite existing value");
291     Iter->second[Instance.Part][CacheIdx] = V;
292   }
293 
294   /// Hold state information used when constructing the CFG of the output IR,
295   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
296   struct CFGState {
297     /// The previous VPBasicBlock visited. Initially set to null.
298     VPBasicBlock *PrevVPBB = nullptr;
299 
300     /// The previous IR BasicBlock created or used. Initially set to the new
301     /// header BasicBlock.
302     BasicBlock *PrevBB = nullptr;
303 
304     /// The last IR BasicBlock in the output IR. Set to the new latch
305     /// BasicBlock, used for placing the newly created BasicBlocks.
306     BasicBlock *LastBB = nullptr;
307 
308     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
309     /// of replication, maps the BasicBlock of the last replica created.
310     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
311 
312     /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
313     /// up at the end of vector code generation.
314     SmallVector<VPBasicBlock *, 8> VPBBsToFix;
315 
316     CFGState() = default;
317   } CFG;
318 
319   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
320   LoopInfo *LI;
321 
322   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
323   DominatorTree *DT;
324 
325   /// Hold a reference to the IRBuilder used to generate output IR code.
326   IRBuilder<> &Builder;
327 
328   VPValue2ValueTy VPValue2Value;
329 
330   /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF).
331   Value *CanonicalIV = nullptr;
332 
333   /// Hold the trip count of the scalar loop.
334   Value *TripCount = nullptr;
335 
336   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
337   InnerLoopVectorizer *ILV;
338 
339   /// Pointer to the VPlan code is generated for.
340   VPlan *Plan;
341 };
342 
343 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
344 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
345 class VPBlockBase {
346   friend class VPBlockUtils;
347 
348   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
349 
350   /// An optional name for the block.
351   std::string Name;
352 
353   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
354   /// it is a topmost VPBlockBase.
355   VPRegionBlock *Parent = nullptr;
356 
357   /// List of predecessor blocks.
358   SmallVector<VPBlockBase *, 1> Predecessors;
359 
360   /// List of successor blocks.
361   SmallVector<VPBlockBase *, 1> Successors;
362 
363   /// Successor selector managed by a VPUser. For blocks with zero or one
364   /// successors, there is no operand. Otherwise there is exactly one operand
365   /// which is the branch condition.
366   VPUser CondBitUser;
367 
368   /// If the block is predicated, its predicate is stored as an operand of this
369   /// VPUser to maintain the def-use relations. Otherwise there is no operand
370   /// here.
371   VPUser PredicateUser;
372 
373   /// VPlan containing the block. Can only be set on the entry block of the
374   /// plan.
375   VPlan *Plan = nullptr;
376 
377   /// Add \p Successor as the last successor to this block.
378   void appendSuccessor(VPBlockBase *Successor) {
379     assert(Successor && "Cannot add nullptr successor!");
380     Successors.push_back(Successor);
381   }
382 
383   /// Add \p Predecessor as the last predecessor to this block.
384   void appendPredecessor(VPBlockBase *Predecessor) {
385     assert(Predecessor && "Cannot add nullptr predecessor!");
386     Predecessors.push_back(Predecessor);
387   }
388 
389   /// Remove \p Predecessor from the predecessors of this block.
390   void removePredecessor(VPBlockBase *Predecessor) {
391     auto Pos = find(Predecessors, Predecessor);
392     assert(Pos && "Predecessor does not exist");
393     Predecessors.erase(Pos);
394   }
395 
396   /// Remove \p Successor from the successors of this block.
397   void removeSuccessor(VPBlockBase *Successor) {
398     auto Pos = find(Successors, Successor);
399     assert(Pos && "Successor does not exist");
400     Successors.erase(Pos);
401   }
402 
403 protected:
404   VPBlockBase(const unsigned char SC, const std::string &N)
405       : SubclassID(SC), Name(N) {}
406 
407 public:
408   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
409   /// that are actually instantiated. Values of this enumeration are kept in the
410   /// SubclassID field of the VPBlockBase objects. They are used for concrete
411   /// type identification.
412   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
413 
414   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
415 
416   virtual ~VPBlockBase() = default;
417 
418   const std::string &getName() const { return Name; }
419 
420   void setName(const Twine &newName) { Name = newName.str(); }
421 
422   /// \return an ID for the concrete type of this object.
423   /// This is used to implement the classof checks. This should not be used
424   /// for any other purpose, as the values may change as LLVM evolves.
425   unsigned getVPBlockID() const { return SubclassID; }
426 
427   VPRegionBlock *getParent() { return Parent; }
428   const VPRegionBlock *getParent() const { return Parent; }
429 
430   /// \return A pointer to the plan containing the current block.
431   VPlan *getPlan();
432   const VPlan *getPlan() const;
433 
434   /// Sets the pointer of the plan containing the block. The block must be the
435   /// entry block into the VPlan.
436   void setPlan(VPlan *ParentPlan);
437 
438   void setParent(VPRegionBlock *P) { Parent = P; }
439 
440   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
441   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
442   /// VPBlockBase is a VPBasicBlock, it is returned.
443   const VPBasicBlock *getEntryBasicBlock() const;
444   VPBasicBlock *getEntryBasicBlock();
445 
446   /// \return the VPBasicBlock that is the exit of this VPBlockBase,
447   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
448   /// VPBlockBase is a VPBasicBlock, it is returned.
449   const VPBasicBlock *getExitBasicBlock() const;
450   VPBasicBlock *getExitBasicBlock();
451 
452   const VPBlocksTy &getSuccessors() const { return Successors; }
453   VPBlocksTy &getSuccessors() { return Successors; }
454 
455   const VPBlocksTy &getPredecessors() const { return Predecessors; }
456   VPBlocksTy &getPredecessors() { return Predecessors; }
457 
458   /// \return the successor of this VPBlockBase if it has a single successor.
459   /// Otherwise return a null pointer.
460   VPBlockBase *getSingleSuccessor() const {
461     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
462   }
463 
464   /// \return the predecessor of this VPBlockBase if it has a single
465   /// predecessor. Otherwise return a null pointer.
466   VPBlockBase *getSinglePredecessor() const {
467     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
468   }
469 
470   size_t getNumSuccessors() const { return Successors.size(); }
471   size_t getNumPredecessors() const { return Predecessors.size(); }
472 
473   /// An Enclosing Block of a block B is any block containing B, including B
474   /// itself. \return the closest enclosing block starting from "this", which
475   /// has successors. \return the root enclosing block if all enclosing blocks
476   /// have no successors.
477   VPBlockBase *getEnclosingBlockWithSuccessors();
478 
479   /// \return the closest enclosing block starting from "this", which has
480   /// predecessors. \return the root enclosing block if all enclosing blocks
481   /// have no predecessors.
482   VPBlockBase *getEnclosingBlockWithPredecessors();
483 
484   /// \return the successors either attached directly to this VPBlockBase or, if
485   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
486   /// successors of its own, search recursively for the first enclosing
487   /// VPRegionBlock that has successors and return them. If no such
488   /// VPRegionBlock exists, return the (empty) successors of the topmost
489   /// VPBlockBase reached.
490   const VPBlocksTy &getHierarchicalSuccessors() {
491     return getEnclosingBlockWithSuccessors()->getSuccessors();
492   }
493 
494   /// \return the hierarchical successor of this VPBlockBase if it has a single
495   /// hierarchical successor. Otherwise return a null pointer.
496   VPBlockBase *getSingleHierarchicalSuccessor() {
497     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
498   }
499 
500   /// \return the predecessors either attached directly to this VPBlockBase or,
501   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
502   /// predecessors of its own, search recursively for the first enclosing
503   /// VPRegionBlock that has predecessors and return them. If no such
504   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
505   /// VPBlockBase reached.
506   const VPBlocksTy &getHierarchicalPredecessors() {
507     return getEnclosingBlockWithPredecessors()->getPredecessors();
508   }
509 
510   /// \return the hierarchical predecessor of this VPBlockBase if it has a
511   /// single hierarchical predecessor. Otherwise return a null pointer.
512   VPBlockBase *getSingleHierarchicalPredecessor() {
513     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
514   }
515 
516   /// \return the condition bit selecting the successor.
517   VPValue *getCondBit();
518   /// \return the condition bit selecting the successor.
519   const VPValue *getCondBit() const;
520   /// Set the condition bit selecting the successor.
521   void setCondBit(VPValue *CV);
522 
523   /// \return the block's predicate.
524   VPValue *getPredicate();
525   /// \return the block's predicate.
526   const VPValue *getPredicate() const;
527   /// Set the block's predicate.
528   void setPredicate(VPValue *Pred);
529 
530   /// Set a given VPBlockBase \p Successor as the single successor of this
531   /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
532   /// This VPBlockBase must have no successors.
533   void setOneSuccessor(VPBlockBase *Successor) {
534     assert(Successors.empty() && "Setting one successor when others exist.");
535     appendSuccessor(Successor);
536   }
537 
538   /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
539   /// successors of this VPBlockBase. \p Condition is set as the successor
540   /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
541   /// IfFalse. This VPBlockBase must have no successors.
542   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
543                         VPValue *Condition) {
544     assert(Successors.empty() && "Setting two successors when others exist.");
545     assert(Condition && "Setting two successors without condition!");
546     setCondBit(Condition);
547     appendSuccessor(IfTrue);
548     appendSuccessor(IfFalse);
549   }
550 
551   /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
552   /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
553   /// as successor of any VPBasicBlock in \p NewPreds.
554   void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
555     assert(Predecessors.empty() && "Block predecessors already set.");
556     for (auto *Pred : NewPreds)
557       appendPredecessor(Pred);
558   }
559 
560   /// Remove all the predecessor of this block.
561   void clearPredecessors() { Predecessors.clear(); }
562 
563   /// Remove all the successors of this block and set to null its condition bit
564   void clearSuccessors() {
565     Successors.clear();
566     setCondBit(nullptr);
567   }
568 
569   /// The method which generates the output IR that correspond to this
570   /// VPBlockBase, thereby "executing" the VPlan.
571   virtual void execute(struct VPTransformState *State) = 0;
572 
573   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
574   static void deleteCFG(VPBlockBase *Entry);
575 
576   /// Return true if it is legal to hoist instructions into this block.
577   bool isLegalToHoistInto() {
578     // There are currently no constraints that prevent an instruction to be
579     // hoisted into a VPBlockBase.
580     return true;
581   }
582 
583   /// Replace all operands of VPUsers in the block with \p NewValue and also
584   /// replaces all uses of VPValues defined in the block with NewValue.
585   virtual void dropAllReferences(VPValue *NewValue) = 0;
586 
587 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
588   void printAsOperand(raw_ostream &OS, bool PrintType) const {
589     OS << getName();
590   }
591 
592   /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
593   /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
594   /// consequtive numbers.
595   ///
596   /// Note that the numbering is applied to the whole VPlan, so printing
597   /// individual blocks is consistent with the whole VPlan printing.
598   virtual void print(raw_ostream &O, const Twine &Indent,
599                      VPSlotTracker &SlotTracker) const = 0;
600 
601   /// Print plain-text dump of this VPlan to \p O.
602   void print(raw_ostream &O) const {
603     VPSlotTracker SlotTracker(getPlan());
604     print(O, "", SlotTracker);
605   }
606 
607   /// Dump this VPBlockBase to dbgs().
608   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
609 #endif
610 };
611 
612 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
613 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef
614 /// and is responsible for deleting its defined values. Single-value
615 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from
616 /// VPRecipeBase before VPValue.
617 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>,
618                      public VPDef,
619                      public VPUser {
620   friend VPBasicBlock;
621   friend class VPBlockUtils;
622 
623 
624   /// Each VPRecipe belongs to a single VPBasicBlock.
625   VPBasicBlock *Parent = nullptr;
626 
627 public:
628   VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands)
629       : VPDef(SC), VPUser(Operands) {}
630 
631   template <typename IterT>
632   VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands)
633       : VPDef(SC), VPUser(Operands) {}
634   virtual ~VPRecipeBase() = default;
635 
636   /// \return the VPBasicBlock which this VPRecipe belongs to.
637   VPBasicBlock *getParent() { return Parent; }
638   const VPBasicBlock *getParent() const { return Parent; }
639 
640   /// The method which generates the output IR instructions that correspond to
641   /// this VPRecipe, thereby "executing" the VPlan.
642   virtual void execute(struct VPTransformState &State) = 0;
643 
644   /// Insert an unlinked recipe into a basic block immediately before
645   /// the specified recipe.
646   void insertBefore(VPRecipeBase *InsertPos);
647 
648   /// Insert an unlinked Recipe into a basic block immediately after
649   /// the specified Recipe.
650   void insertAfter(VPRecipeBase *InsertPos);
651 
652   /// Unlink this recipe from its current VPBasicBlock and insert it into
653   /// the VPBasicBlock that MovePos lives in, right after MovePos.
654   void moveAfter(VPRecipeBase *MovePos);
655 
656   /// Unlink this recipe and insert into BB before I.
657   ///
658   /// \pre I is a valid iterator into BB.
659   void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I);
660 
661   /// This method unlinks 'this' from the containing basic block, but does not
662   /// delete it.
663   void removeFromParent();
664 
665   /// This method unlinks 'this' from the containing basic block and deletes it.
666   ///
667   /// \returns an iterator pointing to the element after the erased one
668   iplist<VPRecipeBase>::iterator eraseFromParent();
669 
670   /// Returns the underlying instruction, if the recipe is a VPValue or nullptr
671   /// otherwise.
672   Instruction *getUnderlyingInstr() {
673     return cast<Instruction>(getVPValue()->getUnderlyingValue());
674   }
675   const Instruction *getUnderlyingInstr() const {
676     return cast<Instruction>(getVPValue()->getUnderlyingValue());
677   }
678 
679   /// Method to support type inquiry through isa, cast, and dyn_cast.
680   static inline bool classof(const VPDef *D) {
681     // All VPDefs are also VPRecipeBases.
682     return true;
683   }
684 };
685 
686 inline bool VPUser::classof(const VPDef *Def) {
687   return Def->getVPDefID() == VPRecipeBase::VPInstructionSC ||
688          Def->getVPDefID() == VPRecipeBase::VPWidenSC ||
689          Def->getVPDefID() == VPRecipeBase::VPWidenCallSC ||
690          Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC ||
691          Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC ||
692          Def->getVPDefID() == VPRecipeBase::VPBlendSC ||
693          Def->getVPDefID() == VPRecipeBase::VPInterleaveSC ||
694          Def->getVPDefID() == VPRecipeBase::VPReplicateSC ||
695          Def->getVPDefID() == VPRecipeBase::VPReductionSC ||
696          Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC ||
697          Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
698 }
699 
700 /// This is a concrete Recipe that models a single VPlan-level instruction.
701 /// While as any Recipe it may generate a sequence of IR instructions when
702 /// executed, these instructions would always form a single-def expression as
703 /// the VPInstruction is also a single def-use vertex.
704 class VPInstruction : public VPRecipeBase, public VPValue {
705   friend class VPlanSlp;
706 
707 public:
708   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
709   enum {
710     Not = Instruction::OtherOpsEnd + 1,
711     ICmpULE,
712     SLPLoad,
713     SLPStore,
714     ActiveLaneMask,
715   };
716 
717 private:
718   typedef unsigned char OpcodeTy;
719   OpcodeTy Opcode;
720 
721   /// Utility method serving execute(): generates a single instance of the
722   /// modeled instruction.
723   void generateInstruction(VPTransformState &State, unsigned Part);
724 
725 protected:
726   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
727 
728 public:
729   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
730       : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands),
731         VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode) {}
732 
733   VPInstruction(unsigned Opcode, ArrayRef<VPInstruction *> Operands)
734       : VPRecipeBase(VPRecipeBase::VPInstructionSC, {}),
735         VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode) {
736     for (auto *I : Operands)
737       addOperand(I->getVPValue());
738   }
739 
740   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
741       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
742 
743   /// Method to support type inquiry through isa, cast, and dyn_cast.
744   static inline bool classof(const VPValue *V) {
745     return V->getVPValueID() == VPValue::VPVInstructionSC;
746   }
747 
748   VPInstruction *clone() const {
749     SmallVector<VPValue *, 2> Operands(operands());
750     return new VPInstruction(Opcode, Operands);
751   }
752 
753   /// Method to support type inquiry through isa, cast, and dyn_cast.
754   static inline bool classof(const VPDef *R) {
755     return R->getVPDefID() == VPRecipeBase::VPInstructionSC;
756   }
757 
758   unsigned getOpcode() const { return Opcode; }
759 
760   /// Generate the instruction.
761   /// TODO: We currently execute only per-part unless a specific instance is
762   /// provided.
763   void execute(VPTransformState &State) override;
764 
765 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
766   /// Print the VPInstruction to \p O.
767   void print(raw_ostream &O, const Twine &Indent,
768              VPSlotTracker &SlotTracker) const override;
769 
770   /// Print the VPInstruction to dbgs() (for debugging).
771   LLVM_DUMP_METHOD void dump() const;
772 #endif
773 
774   /// Return true if this instruction may modify memory.
775   bool mayWriteToMemory() const {
776     // TODO: we can use attributes of the called function to rule out memory
777     //       modifications.
778     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
779            Opcode == Instruction::Invoke || Opcode == SLPStore;
780   }
781 
782   bool hasResult() const {
783     // CallInst may or may not have a result, depending on the called function.
784     // Conservatively return calls have results for now.
785     switch (getOpcode()) {
786     case Instruction::Ret:
787     case Instruction::Br:
788     case Instruction::Store:
789     case Instruction::Switch:
790     case Instruction::IndirectBr:
791     case Instruction::Resume:
792     case Instruction::CatchRet:
793     case Instruction::Unreachable:
794     case Instruction::Fence:
795     case Instruction::AtomicRMW:
796       return false;
797     default:
798       return true;
799     }
800   }
801 };
802 
803 /// VPWidenRecipe is a recipe for producing a copy of vector type its
804 /// ingredient. This recipe covers most of the traditional vectorization cases
805 /// where each ingredient transforms into a vectorized version of itself.
806 class VPWidenRecipe : public VPRecipeBase, public VPValue {
807 public:
808   template <typename IterT>
809   VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands)
810       : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands),
811         VPValue(VPValue::VPVWidenSC, &I, this) {}
812 
813   ~VPWidenRecipe() override = default;
814 
815   /// Method to support type inquiry through isa, cast, and dyn_cast.
816   static inline bool classof(const VPDef *D) {
817     return D->getVPDefID() == VPRecipeBase::VPWidenSC;
818   }
819   static inline bool classof(const VPValue *V) {
820     return V->getVPValueID() == VPValue::VPVWidenSC;
821   }
822 
823   /// Produce widened copies of all Ingredients.
824   void execute(VPTransformState &State) override;
825 
826 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
827   /// Print the recipe.
828   void print(raw_ostream &O, const Twine &Indent,
829              VPSlotTracker &SlotTracker) const override;
830 #endif
831 };
832 
833 /// A recipe for widening Call instructions.
834 class VPWidenCallRecipe : public VPRecipeBase, public VPValue {
835 
836 public:
837   template <typename IterT>
838   VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments)
839       : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments),
840         VPValue(VPValue::VPVWidenCallSC, &I, this) {}
841 
842   ~VPWidenCallRecipe() override = default;
843 
844   /// Method to support type inquiry through isa, cast, and dyn_cast.
845   static inline bool classof(const VPDef *D) {
846     return D->getVPDefID() == VPRecipeBase::VPWidenCallSC;
847   }
848 
849   /// Produce a widened version of the call instruction.
850   void execute(VPTransformState &State) override;
851 
852 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
853   /// Print the recipe.
854   void print(raw_ostream &O, const Twine &Indent,
855              VPSlotTracker &SlotTracker) const override;
856 #endif
857 };
858 
859 /// A recipe for widening select instructions.
860 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue {
861 
862   /// Is the condition of the select loop invariant?
863   bool InvariantCond;
864 
865 public:
866   template <typename IterT>
867   VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands,
868                       bool InvariantCond)
869       : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands),
870         VPValue(VPValue::VPVWidenSelectSC, &I, this),
871         InvariantCond(InvariantCond) {}
872 
873   ~VPWidenSelectRecipe() override = default;
874 
875   /// Method to support type inquiry through isa, cast, and dyn_cast.
876   static inline bool classof(const VPDef *D) {
877     return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC;
878   }
879 
880   /// Produce a widened version of the select instruction.
881   void execute(VPTransformState &State) override;
882 
883 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
884   /// Print the recipe.
885   void print(raw_ostream &O, const Twine &Indent,
886              VPSlotTracker &SlotTracker) const override;
887 #endif
888 };
889 
890 /// A recipe for handling GEP instructions.
891 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue {
892   bool IsPtrLoopInvariant;
893   SmallBitVector IsIndexLoopInvariant;
894 
895 public:
896   template <typename IterT>
897   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands)
898       : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands),
899         VPValue(VPWidenGEPSC, GEP, this),
900         IsIndexLoopInvariant(GEP->getNumIndices(), false) {}
901 
902   template <typename IterT>
903   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands,
904                    Loop *OrigLoop)
905       : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands),
906         VPValue(VPValue::VPVWidenGEPSC, GEP, this),
907         IsIndexLoopInvariant(GEP->getNumIndices(), false) {
908     IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
909     for (auto Index : enumerate(GEP->indices()))
910       IsIndexLoopInvariant[Index.index()] =
911           OrigLoop->isLoopInvariant(Index.value().get());
912   }
913   ~VPWidenGEPRecipe() override = default;
914 
915   /// Method to support type inquiry through isa, cast, and dyn_cast.
916   static inline bool classof(const VPDef *D) {
917     return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC;
918   }
919 
920   /// Generate the gep nodes.
921   void execute(VPTransformState &State) override;
922 
923 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
924   /// Print the recipe.
925   void print(raw_ostream &O, const Twine &Indent,
926              VPSlotTracker &SlotTracker) const override;
927 #endif
928 };
929 
930 /// A recipe for handling phi nodes of integer and floating-point inductions,
931 /// producing their vector and scalar values.
932 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
933   PHINode *IV;
934 
935 public:
936   VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, Instruction *Cast,
937                                 TruncInst *Trunc = nullptr)
938       : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start}), IV(IV) {
939     if (Trunc)
940       new VPValue(Trunc, this);
941     else
942       new VPValue(IV, this);
943 
944     if (Cast)
945       new VPValue(Cast, this);
946   }
947   ~VPWidenIntOrFpInductionRecipe() override = default;
948 
949   /// Method to support type inquiry through isa, cast, and dyn_cast.
950   static inline bool classof(const VPDef *D) {
951     return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
952   }
953 
954   /// Generate the vectorized and scalarized versions of the phi node as
955   /// needed by their users.
956   void execute(VPTransformState &State) override;
957 
958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
959   /// Print the recipe.
960   void print(raw_ostream &O, const Twine &Indent,
961              VPSlotTracker &SlotTracker) const override;
962 #endif
963 
964   /// Returns the start value of the induction.
965   VPValue *getStartValue() { return getOperand(0); }
966 
967   /// Returns the cast VPValue, if one is attached, or nullptr otherwise.
968   VPValue *getCastValue() {
969     if (getNumDefinedValues() != 2)
970       return nullptr;
971     return getVPValue(1);
972   }
973 
974   /// Returns the first defined value as TruncInst, if it is one or nullptr
975   /// otherwise.
976   TruncInst *getTruncInst() {
977     return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue());
978   }
979   const TruncInst *getTruncInst() const {
980     return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue());
981   }
982 };
983 
984 /// A recipe for handling all phi nodes except for integer and FP inductions.
985 /// For reduction PHIs, RdxDesc must point to the corresponding recurrence
986 /// descriptor and the start value is the first operand of the recipe.
987 /// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are
988 /// managed in the recipe directly.
989 class VPWidenPHIRecipe : public VPRecipeBase, public VPValue {
990   /// Descriptor for a reduction PHI.
991   RecurrenceDescriptor *RdxDesc = nullptr;
992 
993   /// List of incoming blocks. Only used in the VPlan native path.
994   SmallVector<VPBasicBlock *, 2> IncomingBlocks;
995 
996 public:
997   /// Create a new VPWidenPHIRecipe for the reduction \p Phi described by \p
998   /// RdxDesc.
999   VPWidenPHIRecipe(PHINode *Phi, RecurrenceDescriptor &RdxDesc, VPValue &Start)
1000       : VPWidenPHIRecipe(Phi) {
1001     this->RdxDesc = &RdxDesc;
1002     addOperand(&Start);
1003   }
1004 
1005   /// Create a VPWidenPHIRecipe for \p Phi
1006   VPWidenPHIRecipe(PHINode *Phi)
1007       : VPRecipeBase(VPWidenPHISC, {}),
1008         VPValue(VPValue::VPVWidenPHISC, Phi, this) {}
1009   ~VPWidenPHIRecipe() override = default;
1010 
1011   /// Method to support type inquiry through isa, cast, and dyn_cast.
1012   static inline bool classof(const VPDef *D) {
1013     return D->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1014   }
1015   static inline bool classof(const VPValue *V) {
1016     return V->getVPValueID() == VPValue::VPVWidenPHISC;
1017   }
1018 
1019   /// Generate the phi/select nodes.
1020   void execute(VPTransformState &State) override;
1021 
1022 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1023   /// Print the recipe.
1024   void print(raw_ostream &O, const Twine &Indent,
1025              VPSlotTracker &SlotTracker) const override;
1026 #endif
1027 
1028   /// Returns the start value of the phi, if it is a reduction.
1029   VPValue *getStartValue() {
1030     return getNumOperands() == 0 ? nullptr : getOperand(0);
1031   }
1032 
1033   /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi.
1034   void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) {
1035     addOperand(IncomingV);
1036     IncomingBlocks.push_back(IncomingBlock);
1037   }
1038 
1039   /// Returns the \p I th incoming VPValue.
1040   VPValue *getIncomingValue(unsigned I) { return getOperand(I); }
1041 
1042   /// Returns the \p I th incoming VPBasicBlock.
1043   VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; }
1044 };
1045 
1046 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
1047 /// instructions.
1048 class VPBlendRecipe : public VPRecipeBase, public VPValue {
1049   PHINode *Phi;
1050 
1051 public:
1052   /// The blend operation is a User of the incoming values and of their
1053   /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value
1054   /// might be incoming with a full mask for which there is no VPValue.
1055   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands)
1056       : VPRecipeBase(VPBlendSC, Operands),
1057         VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) {
1058     assert(Operands.size() > 0 &&
1059            ((Operands.size() == 1) || (Operands.size() % 2 == 0)) &&
1060            "Expected either a single incoming value or a positive even number "
1061            "of operands");
1062   }
1063 
1064   /// Method to support type inquiry through isa, cast, and dyn_cast.
1065   static inline bool classof(const VPDef *D) {
1066     return D->getVPDefID() == VPRecipeBase::VPBlendSC;
1067   }
1068 
1069   /// Return the number of incoming values, taking into account that a single
1070   /// incoming value has no mask.
1071   unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; }
1072 
1073   /// Return incoming value number \p Idx.
1074   VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); }
1075 
1076   /// Return mask number \p Idx.
1077   VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); }
1078 
1079   /// Generate the phi/select nodes.
1080   void execute(VPTransformState &State) override;
1081 
1082 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1083   /// Print the recipe.
1084   void print(raw_ostream &O, const Twine &Indent,
1085              VPSlotTracker &SlotTracker) const override;
1086 #endif
1087 };
1088 
1089 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
1090 /// or stores into one wide load/store and shuffles. The first operand of a
1091 /// VPInterleave recipe is the address, followed by the stored values, followed
1092 /// by an optional mask.
1093 class VPInterleaveRecipe : public VPRecipeBase {
1094   const InterleaveGroup<Instruction> *IG;
1095 
1096   bool HasMask = false;
1097 
1098 public:
1099   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr,
1100                      ArrayRef<VPValue *> StoredValues, VPValue *Mask)
1101       : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) {
1102     for (unsigned i = 0; i < IG->getFactor(); ++i)
1103       if (Instruction *I = IG->getMember(i)) {
1104         if (I->getType()->isVoidTy())
1105           continue;
1106         new VPValue(I, this);
1107       }
1108 
1109     for (auto *SV : StoredValues)
1110       addOperand(SV);
1111     if (Mask) {
1112       HasMask = true;
1113       addOperand(Mask);
1114     }
1115   }
1116   ~VPInterleaveRecipe() override = default;
1117 
1118   /// Method to support type inquiry through isa, cast, and dyn_cast.
1119   static inline bool classof(const VPDef *D) {
1120     return D->getVPDefID() == VPRecipeBase::VPInterleaveSC;
1121   }
1122 
1123   /// Return the address accessed by this recipe.
1124   VPValue *getAddr() const {
1125     return getOperand(0); // Address is the 1st, mandatory operand.
1126   }
1127 
1128   /// Return the mask used by this recipe. Note that a full mask is represented
1129   /// by a nullptr.
1130   VPValue *getMask() const {
1131     // Mask is optional and therefore the last, currently 2nd operand.
1132     return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
1133   }
1134 
1135   /// Return the VPValues stored by this interleave group. If it is a load
1136   /// interleave group, return an empty ArrayRef.
1137   ArrayRef<VPValue *> getStoredValues() const {
1138     // The first operand is the address, followed by the stored values, followed
1139     // by an optional mask.
1140     return ArrayRef<VPValue *>(op_begin(), getNumOperands())
1141         .slice(1, getNumOperands() - (HasMask ? 2 : 1));
1142   }
1143 
1144   /// Generate the wide load or store, and shuffles.
1145   void execute(VPTransformState &State) override;
1146 
1147 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1148   /// Print the recipe.
1149   void print(raw_ostream &O, const Twine &Indent,
1150              VPSlotTracker &SlotTracker) const override;
1151 #endif
1152 
1153   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
1154 };
1155 
1156 /// A recipe to represent inloop reduction operations, performing a reduction on
1157 /// a vector operand into a scalar value, and adding the result to a chain.
1158 /// The Operands are {ChainOp, VecOp, [Condition]}.
1159 class VPReductionRecipe : public VPRecipeBase, public VPValue {
1160   /// The recurrence decriptor for the reduction in question.
1161   RecurrenceDescriptor *RdxDesc;
1162   /// Pointer to the TTI, needed to create the target reduction
1163   const TargetTransformInfo *TTI;
1164 
1165 public:
1166   VPReductionRecipe(RecurrenceDescriptor *R, Instruction *I, VPValue *ChainOp,
1167                     VPValue *VecOp, VPValue *CondOp,
1168                     const TargetTransformInfo *TTI)
1169       : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}),
1170         VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) {
1171     if (CondOp)
1172       addOperand(CondOp);
1173   }
1174 
1175   ~VPReductionRecipe() override = default;
1176 
1177   /// Method to support type inquiry through isa, cast, and dyn_cast.
1178   static inline bool classof(const VPValue *V) {
1179     return V->getVPValueID() == VPValue::VPVReductionSC;
1180   }
1181 
1182   static inline bool classof(const VPDef *D) {
1183     return D->getVPDefID() == VPRecipeBase::VPReductionSC;
1184   }
1185 
1186   /// Generate the reduction in the loop
1187   void execute(VPTransformState &State) override;
1188 
1189 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1190   /// Print the recipe.
1191   void print(raw_ostream &O, const Twine &Indent,
1192              VPSlotTracker &SlotTracker) const override;
1193 #endif
1194 
1195   /// The VPValue of the scalar Chain being accumulated.
1196   VPValue *getChainOp() const { return getOperand(0); }
1197   /// The VPValue of the vector value to be reduced.
1198   VPValue *getVecOp() const { return getOperand(1); }
1199   /// The VPValue of the condition for the block.
1200   VPValue *getCondOp() const {
1201     return getNumOperands() > 2 ? getOperand(2) : nullptr;
1202   }
1203 };
1204 
1205 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
1206 /// copies of the original scalar type, one per lane, instead of producing a
1207 /// single copy of widened type for all lanes. If the instruction is known to be
1208 /// uniform only one copy, per lane zero, will be generated.
1209 class VPReplicateRecipe : public VPRecipeBase, public VPValue {
1210   /// Indicator if only a single replica per lane is needed.
1211   bool IsUniform;
1212 
1213   /// Indicator if the replicas are also predicated.
1214   bool IsPredicated;
1215 
1216   /// Indicator if the scalar values should also be packed into a vector.
1217   bool AlsoPack;
1218 
1219 public:
1220   template <typename IterT>
1221   VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands,
1222                     bool IsUniform, bool IsPredicated = false)
1223       : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this),
1224         IsUniform(IsUniform), IsPredicated(IsPredicated) {
1225     // Retain the previous behavior of predicateInstructions(), where an
1226     // insert-element of a predicated instruction got hoisted into the
1227     // predicated basic block iff it was its only user. This is achieved by
1228     // having predicated instructions also pack their values into a vector by
1229     // default unless they have a replicated user which uses their scalar value.
1230     AlsoPack = IsPredicated && !I->use_empty();
1231   }
1232 
1233   ~VPReplicateRecipe() override = default;
1234 
1235   /// Method to support type inquiry through isa, cast, and dyn_cast.
1236   static inline bool classof(const VPDef *D) {
1237     return D->getVPDefID() == VPRecipeBase::VPReplicateSC;
1238   }
1239 
1240   static inline bool classof(const VPValue *V) {
1241     return V->getVPValueID() == VPValue::VPVReplicateSC;
1242   }
1243 
1244   /// Generate replicas of the desired Ingredient. Replicas will be generated
1245   /// for all parts and lanes unless a specific part and lane are specified in
1246   /// the \p State.
1247   void execute(VPTransformState &State) override;
1248 
1249   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
1250 
1251 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1252   /// Print the recipe.
1253   void print(raw_ostream &O, const Twine &Indent,
1254              VPSlotTracker &SlotTracker) const override;
1255 #endif
1256 
1257   bool isUniform() const { return IsUniform; }
1258 
1259   bool isPacked() const { return AlsoPack; }
1260 
1261   bool isPredicated() const { return IsPredicated; }
1262 };
1263 
1264 /// A recipe for generating conditional branches on the bits of a mask.
1265 class VPBranchOnMaskRecipe : public VPRecipeBase {
1266 public:
1267   VPBranchOnMaskRecipe(VPValue *BlockInMask)
1268       : VPRecipeBase(VPBranchOnMaskSC, {}) {
1269     if (BlockInMask) // nullptr means all-one mask.
1270       addOperand(BlockInMask);
1271   }
1272 
1273   /// Method to support type inquiry through isa, cast, and dyn_cast.
1274   static inline bool classof(const VPDef *D) {
1275     return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC;
1276   }
1277 
1278   /// Generate the extraction of the appropriate bit from the block mask and the
1279   /// conditional branch.
1280   void execute(VPTransformState &State) override;
1281 
1282 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1283   /// Print the recipe.
1284   void print(raw_ostream &O, const Twine &Indent,
1285              VPSlotTracker &SlotTracker) const override {
1286     O << Indent << "BRANCH-ON-MASK ";
1287     if (VPValue *Mask = getMask())
1288       Mask->printAsOperand(O, SlotTracker);
1289     else
1290       O << " All-One";
1291   }
1292 #endif
1293 
1294   /// Return the mask used by this recipe. Note that a full mask is represented
1295   /// by a nullptr.
1296   VPValue *getMask() const {
1297     assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
1298     // Mask is optional.
1299     return getNumOperands() == 1 ? getOperand(0) : nullptr;
1300   }
1301 };
1302 
1303 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1304 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1305 /// order to merge values that are set under such a branch and feed their uses.
1306 /// The phi nodes can be scalar or vector depending on the users of the value.
1307 /// This recipe works in concert with VPBranchOnMaskRecipe.
1308 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue {
1309 public:
1310   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1311   /// nodes after merging back from a Branch-on-Mask.
1312   VPPredInstPHIRecipe(VPValue *PredV)
1313       : VPRecipeBase(VPPredInstPHISC, PredV),
1314         VPValue(VPValue::VPVPredInstPHI, nullptr, this) {}
1315   ~VPPredInstPHIRecipe() override = default;
1316 
1317   /// Method to support type inquiry through isa, cast, and dyn_cast.
1318   static inline bool classof(const VPDef *D) {
1319     return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC;
1320   }
1321 
1322   /// Generates phi nodes for live-outs as needed to retain SSA form.
1323   void execute(VPTransformState &State) override;
1324 
1325 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1326   /// Print the recipe.
1327   void print(raw_ostream &O, const Twine &Indent,
1328              VPSlotTracker &SlotTracker) const override;
1329 #endif
1330 };
1331 
1332 /// A Recipe for widening load/store operations.
1333 /// The recipe uses the following VPValues:
1334 /// - For load: Address, optional mask
1335 /// - For store: Address, stored value, optional mask
1336 /// TODO: We currently execute only per-part unless a specific instance is
1337 /// provided.
1338 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
1339   Instruction &Ingredient;
1340 
1341   void setMask(VPValue *Mask) {
1342     if (!Mask)
1343       return;
1344     addOperand(Mask);
1345   }
1346 
1347   bool isMasked() const {
1348     return isStore() ? getNumOperands() == 3 : getNumOperands() == 2;
1349   }
1350 
1351 public:
1352   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask)
1353       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), Ingredient(Load) {
1354     new VPValue(VPValue::VPVMemoryInstructionSC, &Load, this);
1355     setMask(Mask);
1356   }
1357 
1358   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1359                                  VPValue *StoredValue, VPValue *Mask)
1360       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}),
1361         Ingredient(Store) {
1362     setMask(Mask);
1363   }
1364 
1365   /// Method to support type inquiry through isa, cast, and dyn_cast.
1366   static inline bool classof(const VPDef *D) {
1367     return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1368   }
1369 
1370   /// Return the address accessed by this recipe.
1371   VPValue *getAddr() const {
1372     return getOperand(0); // Address is the 1st, mandatory operand.
1373   }
1374 
1375   /// Return the mask used by this recipe. Note that a full mask is represented
1376   /// by a nullptr.
1377   VPValue *getMask() const {
1378     // Mask is optional and therefore the last operand.
1379     return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1380   }
1381 
1382   /// Returns true if this recipe is a store.
1383   bool isStore() const { return isa<StoreInst>(Ingredient); }
1384 
1385   /// Return the address accessed by this recipe.
1386   VPValue *getStoredValue() const {
1387     assert(isStore() && "Stored value only available for store instructions");
1388     return getOperand(1); // Stored value is the 2nd, mandatory operand.
1389   }
1390 
1391   /// Generate the wide load/store.
1392   void execute(VPTransformState &State) override;
1393 
1394 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1395   /// Print the recipe.
1396   void print(raw_ostream &O, const Twine &Indent,
1397              VPSlotTracker &SlotTracker) const override;
1398 #endif
1399 };
1400 
1401 /// A Recipe for widening the canonical induction variable of the vector loop.
1402 class VPWidenCanonicalIVRecipe : public VPRecipeBase {
1403 public:
1404   VPWidenCanonicalIVRecipe() : VPRecipeBase(VPWidenCanonicalIVSC, {}) {
1405     new VPValue(nullptr, this);
1406   }
1407 
1408   ~VPWidenCanonicalIVRecipe() override = default;
1409 
1410   /// Method to support type inquiry through isa, cast, and dyn_cast.
1411   static inline bool classof(const VPDef *D) {
1412     return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1413   }
1414 
1415   /// Generate a canonical vector induction variable of the vector loop, with
1416   /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
1417   /// step = <VF*UF, VF*UF, ..., VF*UF>.
1418   void execute(VPTransformState &State) override;
1419 
1420 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1421   /// Print the recipe.
1422   void print(raw_ostream &O, const Twine &Indent,
1423              VPSlotTracker &SlotTracker) const override;
1424 #endif
1425 };
1426 
1427 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1428 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1429 /// output IR instructions.
1430 class VPBasicBlock : public VPBlockBase {
1431 public:
1432   using RecipeListTy = iplist<VPRecipeBase>;
1433 
1434 private:
1435   /// The VPRecipes held in the order of output instructions to generate.
1436   RecipeListTy Recipes;
1437 
1438 public:
1439   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1440       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1441     if (Recipe)
1442       appendRecipe(Recipe);
1443   }
1444 
1445   ~VPBasicBlock() override {
1446     while (!Recipes.empty())
1447       Recipes.pop_back();
1448   }
1449 
1450   /// Instruction iterators...
1451   using iterator = RecipeListTy::iterator;
1452   using const_iterator = RecipeListTy::const_iterator;
1453   using reverse_iterator = RecipeListTy::reverse_iterator;
1454   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1455 
1456   //===--------------------------------------------------------------------===//
1457   /// Recipe iterator methods
1458   ///
1459   inline iterator begin() { return Recipes.begin(); }
1460   inline const_iterator begin() const { return Recipes.begin(); }
1461   inline iterator end() { return Recipes.end(); }
1462   inline const_iterator end() const { return Recipes.end(); }
1463 
1464   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1465   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1466   inline reverse_iterator rend() { return Recipes.rend(); }
1467   inline const_reverse_iterator rend() const { return Recipes.rend(); }
1468 
1469   inline size_t size() const { return Recipes.size(); }
1470   inline bool empty() const { return Recipes.empty(); }
1471   inline const VPRecipeBase &front() const { return Recipes.front(); }
1472   inline VPRecipeBase &front() { return Recipes.front(); }
1473   inline const VPRecipeBase &back() const { return Recipes.back(); }
1474   inline VPRecipeBase &back() { return Recipes.back(); }
1475 
1476   /// Returns a reference to the list of recipes.
1477   RecipeListTy &getRecipeList() { return Recipes; }
1478 
1479   /// Returns a pointer to a member of the recipe list.
1480   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1481     return &VPBasicBlock::Recipes;
1482   }
1483 
1484   /// Method to support type inquiry through isa, cast, and dyn_cast.
1485   static inline bool classof(const VPBlockBase *V) {
1486     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1487   }
1488 
1489   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
1490     assert(Recipe && "No recipe to append.");
1491     assert(!Recipe->Parent && "Recipe already in VPlan");
1492     Recipe->Parent = this;
1493     Recipes.insert(InsertPt, Recipe);
1494   }
1495 
1496   /// Augment the existing recipes of a VPBasicBlock with an additional
1497   /// \p Recipe as the last recipe.
1498   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1499 
1500   /// The method which generates the output IR instructions that correspond to
1501   /// this VPBasicBlock, thereby "executing" the VPlan.
1502   void execute(struct VPTransformState *State) override;
1503 
1504   /// Return the position of the first non-phi node recipe in the block.
1505   iterator getFirstNonPhi();
1506 
1507   void dropAllReferences(VPValue *NewValue) override;
1508 
1509 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1510   /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
1511   /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
1512   ///
1513   /// Note that the numbering is applied to the whole VPlan, so printing
1514   /// individual blocks is consistent with the whole VPlan printing.
1515   void print(raw_ostream &O, const Twine &Indent,
1516              VPSlotTracker &SlotTracker) const override;
1517   using VPBlockBase::print; // Get the print(raw_stream &O) version.
1518 #endif
1519 
1520 private:
1521   /// Create an IR BasicBlock to hold the output instructions generated by this
1522   /// VPBasicBlock, and return it. Update the CFGState accordingly.
1523   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1524 };
1525 
1526 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1527 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1528 /// A VPRegionBlock may indicate that its contents are to be replicated several
1529 /// times. This is designed to support predicated scalarization, in which a
1530 /// scalar if-then code structure needs to be generated VF * UF times. Having
1531 /// this replication indicator helps to keep a single model for multiple
1532 /// candidate VF's. The actual replication takes place only once the desired VF
1533 /// and UF have been determined.
1534 class VPRegionBlock : public VPBlockBase {
1535   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1536   VPBlockBase *Entry;
1537 
1538   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1539   VPBlockBase *Exit;
1540 
1541   /// An indicator whether this region is to generate multiple replicated
1542   /// instances of output IR corresponding to its VPBlockBases.
1543   bool IsReplicator;
1544 
1545 public:
1546   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1547                 const std::string &Name = "", bool IsReplicator = false)
1548       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1549         IsReplicator(IsReplicator) {
1550     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1551     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1552     Entry->setParent(this);
1553     Exit->setParent(this);
1554   }
1555   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1556       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1557         IsReplicator(IsReplicator) {}
1558 
1559   ~VPRegionBlock() override {
1560     if (Entry) {
1561       VPValue DummyValue;
1562       Entry->dropAllReferences(&DummyValue);
1563       deleteCFG(Entry);
1564     }
1565   }
1566 
1567   /// Method to support type inquiry through isa, cast, and dyn_cast.
1568   static inline bool classof(const VPBlockBase *V) {
1569     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1570   }
1571 
1572   const VPBlockBase *getEntry() const { return Entry; }
1573   VPBlockBase *getEntry() { return Entry; }
1574 
1575   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1576   /// EntryBlock must have no predecessors.
1577   void setEntry(VPBlockBase *EntryBlock) {
1578     assert(EntryBlock->getPredecessors().empty() &&
1579            "Entry block cannot have predecessors.");
1580     Entry = EntryBlock;
1581     EntryBlock->setParent(this);
1582   }
1583 
1584   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1585   // specific interface of llvm::Function, instead of using
1586   // GraphTraints::getEntryNode. We should add a new template parameter to
1587   // DominatorTreeBase representing the Graph type.
1588   VPBlockBase &front() const { return *Entry; }
1589 
1590   const VPBlockBase *getExit() const { return Exit; }
1591   VPBlockBase *getExit() { return Exit; }
1592 
1593   /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1594   /// ExitBlock must have no successors.
1595   void setExit(VPBlockBase *ExitBlock) {
1596     assert(ExitBlock->getSuccessors().empty() &&
1597            "Exit block cannot have successors.");
1598     Exit = ExitBlock;
1599     ExitBlock->setParent(this);
1600   }
1601 
1602   /// An indicator whether this region is to generate multiple replicated
1603   /// instances of output IR corresponding to its VPBlockBases.
1604   bool isReplicator() const { return IsReplicator; }
1605 
1606   /// The method which generates the output IR instructions that correspond to
1607   /// this VPRegionBlock, thereby "executing" the VPlan.
1608   void execute(struct VPTransformState *State) override;
1609 
1610   void dropAllReferences(VPValue *NewValue) override;
1611 
1612 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1613   /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
1614   /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
1615   /// consequtive numbers.
1616   ///
1617   /// Note that the numbering is applied to the whole VPlan, so printing
1618   /// individual regions is consistent with the whole VPlan printing.
1619   void print(raw_ostream &O, const Twine &Indent,
1620              VPSlotTracker &SlotTracker) const override;
1621   using VPBlockBase::print; // Get the print(raw_stream &O) version.
1622 #endif
1623 };
1624 
1625 //===----------------------------------------------------------------------===//
1626 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
1627 //===----------------------------------------------------------------------===//
1628 
1629 // The following set of template specializations implement GraphTraits to treat
1630 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1631 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1632 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1633 // successors/predecessors but not to the blocks inside the region.
1634 
1635 template <> struct GraphTraits<VPBlockBase *> {
1636   using NodeRef = VPBlockBase *;
1637   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1638 
1639   static NodeRef getEntryNode(NodeRef N) { return N; }
1640 
1641   static inline ChildIteratorType child_begin(NodeRef N) {
1642     return N->getSuccessors().begin();
1643   }
1644 
1645   static inline ChildIteratorType child_end(NodeRef N) {
1646     return N->getSuccessors().end();
1647   }
1648 };
1649 
1650 template <> struct GraphTraits<const VPBlockBase *> {
1651   using NodeRef = const VPBlockBase *;
1652   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1653 
1654   static NodeRef getEntryNode(NodeRef N) { return N; }
1655 
1656   static inline ChildIteratorType child_begin(NodeRef N) {
1657     return N->getSuccessors().begin();
1658   }
1659 
1660   static inline ChildIteratorType child_end(NodeRef N) {
1661     return N->getSuccessors().end();
1662   }
1663 };
1664 
1665 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1666 // of successors for the inverse traversal.
1667 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1668   using NodeRef = VPBlockBase *;
1669   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1670 
1671   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1672 
1673   static inline ChildIteratorType child_begin(NodeRef N) {
1674     return N->getPredecessors().begin();
1675   }
1676 
1677   static inline ChildIteratorType child_end(NodeRef N) {
1678     return N->getPredecessors().end();
1679   }
1680 };
1681 
1682 // The following set of template specializations implement GraphTraits to
1683 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1684 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1685 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1686 // there won't be automatic recursion into other VPBlockBases that turn to be
1687 // VPRegionBlocks.
1688 
1689 template <>
1690 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1691   using GraphRef = VPRegionBlock *;
1692   using nodes_iterator = df_iterator<NodeRef>;
1693 
1694   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1695 
1696   static nodes_iterator nodes_begin(GraphRef N) {
1697     return nodes_iterator::begin(N->getEntry());
1698   }
1699 
1700   static nodes_iterator nodes_end(GraphRef N) {
1701     // df_iterator::end() returns an empty iterator so the node used doesn't
1702     // matter.
1703     return nodes_iterator::end(N);
1704   }
1705 };
1706 
1707 template <>
1708 struct GraphTraits<const VPRegionBlock *>
1709     : public GraphTraits<const VPBlockBase *> {
1710   using GraphRef = const VPRegionBlock *;
1711   using nodes_iterator = df_iterator<NodeRef>;
1712 
1713   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1714 
1715   static nodes_iterator nodes_begin(GraphRef N) {
1716     return nodes_iterator::begin(N->getEntry());
1717   }
1718 
1719   static nodes_iterator nodes_end(GraphRef N) {
1720     // df_iterator::end() returns an empty iterator so the node used doesn't
1721     // matter.
1722     return nodes_iterator::end(N);
1723   }
1724 };
1725 
1726 template <>
1727 struct GraphTraits<Inverse<VPRegionBlock *>>
1728     : public GraphTraits<Inverse<VPBlockBase *>> {
1729   using GraphRef = VPRegionBlock *;
1730   using nodes_iterator = df_iterator<NodeRef>;
1731 
1732   static NodeRef getEntryNode(Inverse<GraphRef> N) {
1733     return N.Graph->getExit();
1734   }
1735 
1736   static nodes_iterator nodes_begin(GraphRef N) {
1737     return nodes_iterator::begin(N->getExit());
1738   }
1739 
1740   static nodes_iterator nodes_end(GraphRef N) {
1741     // df_iterator::end() returns an empty iterator so the node used doesn't
1742     // matter.
1743     return nodes_iterator::end(N);
1744   }
1745 };
1746 
1747 /// VPlan models a candidate for vectorization, encoding various decisions take
1748 /// to produce efficient output IR, including which branches, basic-blocks and
1749 /// output IR instructions to generate, and their cost. VPlan holds a
1750 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1751 /// VPBlock.
1752 class VPlan {
1753   friend class VPlanPrinter;
1754   friend class VPSlotTracker;
1755 
1756   /// Hold the single entry to the Hierarchical CFG of the VPlan.
1757   VPBlockBase *Entry;
1758 
1759   /// Holds the VFs applicable to this VPlan.
1760   SmallSetVector<ElementCount, 2> VFs;
1761 
1762   /// Holds the name of the VPlan, for printing.
1763   std::string Name;
1764 
1765   /// Holds all the external definitions created for this VPlan.
1766   // TODO: Introduce a specific representation for external definitions in
1767   // VPlan. External definitions must be immutable and hold a pointer to its
1768   // underlying IR that will be used to implement its structural comparison
1769   // (operators '==' and '<').
1770   SmallPtrSet<VPValue *, 16> VPExternalDefs;
1771 
1772   /// Represents the backedge taken count of the original loop, for folding
1773   /// the tail.
1774   VPValue *BackedgeTakenCount = nullptr;
1775 
1776   /// Holds a mapping between Values and their corresponding VPValue inside
1777   /// VPlan.
1778   Value2VPValueTy Value2VPValue;
1779 
1780   /// Contains all VPValues that been allocated by addVPValue directly and need
1781   /// to be free when the plan's destructor is called.
1782   SmallVector<VPValue *, 16> VPValuesToFree;
1783 
1784   /// Holds the VPLoopInfo analysis for this VPlan.
1785   VPLoopInfo VPLInfo;
1786 
1787 public:
1788   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
1789     if (Entry)
1790       Entry->setPlan(this);
1791   }
1792 
1793   ~VPlan() {
1794     if (Entry) {
1795       VPValue DummyValue;
1796       for (VPBlockBase *Block : depth_first(Entry))
1797         Block->dropAllReferences(&DummyValue);
1798 
1799       VPBlockBase::deleteCFG(Entry);
1800     }
1801     for (VPValue *VPV : VPValuesToFree)
1802       delete VPV;
1803     if (BackedgeTakenCount)
1804       delete BackedgeTakenCount;
1805     for (VPValue *Def : VPExternalDefs)
1806       delete Def;
1807   }
1808 
1809   /// Generate the IR code for this VPlan.
1810   void execute(struct VPTransformState *State);
1811 
1812   VPBlockBase *getEntry() { return Entry; }
1813   const VPBlockBase *getEntry() const { return Entry; }
1814 
1815   VPBlockBase *setEntry(VPBlockBase *Block) {
1816     Entry = Block;
1817     Block->setPlan(this);
1818     return Entry;
1819   }
1820 
1821   /// The backedge taken count of the original loop.
1822   VPValue *getOrCreateBackedgeTakenCount() {
1823     if (!BackedgeTakenCount)
1824       BackedgeTakenCount = new VPValue();
1825     return BackedgeTakenCount;
1826   }
1827 
1828   void addVF(ElementCount VF) { VFs.insert(VF); }
1829 
1830   bool hasVF(ElementCount VF) { return VFs.count(VF); }
1831 
1832   const std::string &getName() const { return Name; }
1833 
1834   void setName(const Twine &newName) { Name = newName.str(); }
1835 
1836   /// Add \p VPVal to the pool of external definitions if it's not already
1837   /// in the pool.
1838   void addExternalDef(VPValue *VPVal) {
1839     VPExternalDefs.insert(VPVal);
1840   }
1841 
1842   void addVPValue(Value *V) {
1843     assert(V && "Trying to add a null Value to VPlan");
1844     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1845     VPValue *VPV = new VPValue(V);
1846     Value2VPValue[V] = VPV;
1847     VPValuesToFree.push_back(VPV);
1848   }
1849 
1850   void addVPValue(Value *V, VPValue *VPV) {
1851     assert(V && "Trying to add a null Value to VPlan");
1852     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1853     Value2VPValue[V] = VPV;
1854   }
1855 
1856   VPValue *getVPValue(Value *V) {
1857     assert(V && "Trying to get the VPValue of a null Value");
1858     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1859     return Value2VPValue[V];
1860   }
1861 
1862   VPValue *getOrAddVPValue(Value *V) {
1863     assert(V && "Trying to get or add the VPValue of a null Value");
1864     if (!Value2VPValue.count(V))
1865       addVPValue(V);
1866     return getVPValue(V);
1867   }
1868 
1869   void removeVPValueFor(Value *V) { Value2VPValue.erase(V); }
1870 
1871   /// Return the VPLoopInfo analysis for this VPlan.
1872   VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1873   const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1874 
1875 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1876   /// Print this VPlan to \p O.
1877   void print(raw_ostream &O) const;
1878 
1879   /// Print this VPlan in DOT format to \p O.
1880   void printDOT(raw_ostream &O) const;
1881 
1882   /// Dump the plan to stderr (for debugging).
1883   LLVM_DUMP_METHOD void dump() const;
1884 #endif
1885 
1886   /// Returns a range mapping the values the range \p Operands to their
1887   /// corresponding VPValues.
1888   iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>>
1889   mapToVPValues(User::op_range Operands) {
1890     std::function<VPValue *(Value *)> Fn = [this](Value *Op) {
1891       return getOrAddVPValue(Op);
1892     };
1893     return map_range(Operands, Fn);
1894   }
1895 
1896 private:
1897   /// Add to the given dominator tree the header block and every new basic block
1898   /// that was created between it and the latch block, inclusive.
1899   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
1900                                   BasicBlock *LoopPreHeaderBB,
1901                                   BasicBlock *LoopExitBB);
1902 };
1903 
1904 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1905 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1906 /// indented and follows the dot format.
1907 class VPlanPrinter {
1908   raw_ostream &OS;
1909   const VPlan &Plan;
1910   unsigned Depth = 0;
1911   unsigned TabWidth = 2;
1912   std::string Indent;
1913   unsigned BID = 0;
1914   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1915 
1916   VPSlotTracker SlotTracker;
1917 
1918   /// Handle indentation.
1919   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1920 
1921   /// Print a given \p Block of the Plan.
1922   void dumpBlock(const VPBlockBase *Block);
1923 
1924   /// Print the information related to the CFG edges going out of a given
1925   /// \p Block, followed by printing the successor blocks themselves.
1926   void dumpEdges(const VPBlockBase *Block);
1927 
1928   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1929   /// its successor blocks.
1930   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1931 
1932   /// Print a given \p Region of the Plan.
1933   void dumpRegion(const VPRegionBlock *Region);
1934 
1935   unsigned getOrCreateBID(const VPBlockBase *Block) {
1936     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1937   }
1938 
1939   const Twine getOrCreateName(const VPBlockBase *Block);
1940 
1941   const Twine getUID(const VPBlockBase *Block);
1942 
1943   /// Print the information related to a CFG edge between two VPBlockBases.
1944   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1945                 const Twine &Label);
1946 
1947 public:
1948   VPlanPrinter(raw_ostream &O, const VPlan &P)
1949       : OS(O), Plan(P), SlotTracker(&P) {}
1950 
1951   LLVM_DUMP_METHOD void dump();
1952 };
1953 
1954 struct VPlanIngredient {
1955   const Value *V;
1956 
1957   VPlanIngredient(const Value *V) : V(V) {}
1958 
1959   void print(raw_ostream &O) const;
1960 };
1961 
1962 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1963   I.print(OS);
1964   return OS;
1965 }
1966 
1967 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
1968   Plan.print(OS);
1969   return OS;
1970 }
1971 #endif
1972 
1973 //===----------------------------------------------------------------------===//
1974 // VPlan Utilities
1975 //===----------------------------------------------------------------------===//
1976 
1977 /// Class that provides utilities for VPBlockBases in VPlan.
1978 class VPBlockUtils {
1979 public:
1980   VPBlockUtils() = delete;
1981 
1982   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1983   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1984   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1985   /// has more than one successor, its conditional bit is propagated to \p
1986   /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1987   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1988     assert(NewBlock->getSuccessors().empty() &&
1989            "Can't insert new block with successors.");
1990     // TODO: move successors from BlockPtr to NewBlock when this functionality
1991     // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1992     // already has successors.
1993     BlockPtr->setOneSuccessor(NewBlock);
1994     NewBlock->setPredecessors({BlockPtr});
1995     NewBlock->setParent(BlockPtr->getParent());
1996   }
1997 
1998   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1999   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
2000   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
2001   /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
2002   /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
2003   /// must have neither successors nor predecessors.
2004   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
2005                                    VPValue *Condition, VPBlockBase *BlockPtr) {
2006     assert(IfTrue->getSuccessors().empty() &&
2007            "Can't insert IfTrue with successors.");
2008     assert(IfFalse->getSuccessors().empty() &&
2009            "Can't insert IfFalse with successors.");
2010     BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
2011     IfTrue->setPredecessors({BlockPtr});
2012     IfFalse->setPredecessors({BlockPtr});
2013     IfTrue->setParent(BlockPtr->getParent());
2014     IfFalse->setParent(BlockPtr->getParent());
2015   }
2016 
2017   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
2018   /// the successors of \p From and \p From to the predecessors of \p To. Both
2019   /// VPBlockBases must have the same parent, which can be null. Both
2020   /// VPBlockBases can be already connected to other VPBlockBases.
2021   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
2022     assert((From->getParent() == To->getParent()) &&
2023            "Can't connect two block with different parents");
2024     assert(From->getNumSuccessors() < 2 &&
2025            "Blocks can't have more than two successors.");
2026     From->appendSuccessor(To);
2027     To->appendPredecessor(From);
2028   }
2029 
2030   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
2031   /// from the successors of \p From and \p From from the predecessors of \p To.
2032   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
2033     assert(To && "Successor to disconnect is null.");
2034     From->removeSuccessor(To);
2035     To->removePredecessor(From);
2036   }
2037 
2038   /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
2039   static bool isBackEdge(const VPBlockBase *FromBlock,
2040                          const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
2041     assert(FromBlock->getParent() == ToBlock->getParent() &&
2042            FromBlock->getParent() && "Must be in same region");
2043     const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
2044     const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
2045     if (!FromLoop || !ToLoop || FromLoop != ToLoop)
2046       return false;
2047 
2048     // A back-edge is a branch from the loop latch to its header.
2049     return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
2050   }
2051 
2052   /// Returns true if \p Block is a loop latch
2053   static bool blockIsLoopLatch(const VPBlockBase *Block,
2054                                const VPLoopInfo *VPLInfo) {
2055     if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
2056       return ParentVPL->isLoopLatch(Block);
2057 
2058     return false;
2059   }
2060 
2061   /// Count and return the number of succesors of \p PredBlock excluding any
2062   /// backedges.
2063   static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
2064                                       VPLoopInfo *VPLI) {
2065     unsigned Count = 0;
2066     for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
2067       if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
2068         Count++;
2069     }
2070     return Count;
2071   }
2072 };
2073 
2074 class VPInterleavedAccessInfo {
2075   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
2076       InterleaveGroupMap;
2077 
2078   /// Type for mapping of instruction based interleave groups to VPInstruction
2079   /// interleave groups
2080   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
2081                              InterleaveGroup<VPInstruction> *>;
2082 
2083   /// Recursively \p Region and populate VPlan based interleave groups based on
2084   /// \p IAI.
2085   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
2086                    InterleavedAccessInfo &IAI);
2087   /// Recursively traverse \p Block and populate VPlan based interleave groups
2088   /// based on \p IAI.
2089   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
2090                   InterleavedAccessInfo &IAI);
2091 
2092 public:
2093   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
2094 
2095   ~VPInterleavedAccessInfo() {
2096     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
2097     // Avoid releasing a pointer twice.
2098     for (auto &I : InterleaveGroupMap)
2099       DelSet.insert(I.second);
2100     for (auto *Ptr : DelSet)
2101       delete Ptr;
2102   }
2103 
2104   /// Get the interleave group that \p Instr belongs to.
2105   ///
2106   /// \returns nullptr if doesn't have such group.
2107   InterleaveGroup<VPInstruction> *
2108   getInterleaveGroup(VPInstruction *Instr) const {
2109     return InterleaveGroupMap.lookup(Instr);
2110   }
2111 };
2112 
2113 /// Class that maps (parts of) an existing VPlan to trees of combined
2114 /// VPInstructions.
2115 class VPlanSlp {
2116   enum class OpMode { Failed, Load, Opcode };
2117 
2118   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
2119   /// DenseMap keys.
2120   struct BundleDenseMapInfo {
2121     static SmallVector<VPValue *, 4> getEmptyKey() {
2122       return {reinterpret_cast<VPValue *>(-1)};
2123     }
2124 
2125     static SmallVector<VPValue *, 4> getTombstoneKey() {
2126       return {reinterpret_cast<VPValue *>(-2)};
2127     }
2128 
2129     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
2130       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2131     }
2132 
2133     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
2134                         const SmallVector<VPValue *, 4> &RHS) {
2135       return LHS == RHS;
2136     }
2137   };
2138 
2139   /// Mapping of values in the original VPlan to a combined VPInstruction.
2140   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
2141       BundleToCombined;
2142 
2143   VPInterleavedAccessInfo &IAI;
2144 
2145   /// Basic block to operate on. For now, only instructions in a single BB are
2146   /// considered.
2147   const VPBasicBlock &BB;
2148 
2149   /// Indicates whether we managed to combine all visited instructions or not.
2150   bool CompletelySLP = true;
2151 
2152   /// Width of the widest combined bundle in bits.
2153   unsigned WidestBundleBits = 0;
2154 
2155   using MultiNodeOpTy =
2156       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
2157 
2158   // Input operand bundles for the current multi node. Each multi node operand
2159   // bundle contains values not matching the multi node's opcode. They will
2160   // be reordered in reorderMultiNodeOps, once we completed building a
2161   // multi node.
2162   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
2163 
2164   /// Indicates whether we are building a multi node currently.
2165   bool MultiNodeActive = false;
2166 
2167   /// Check if we can vectorize Operands together.
2168   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
2169 
2170   /// Add combined instruction \p New for the bundle \p Operands.
2171   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
2172 
2173   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
2174   VPInstruction *markFailed();
2175 
2176   /// Reorder operands in the multi node to maximize sequential memory access
2177   /// and commutative operations.
2178   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
2179 
2180   /// Choose the best candidate to use for the lane after \p Last. The set of
2181   /// candidates to choose from are values with an opcode matching \p Last's
2182   /// or loads consecutive to \p Last.
2183   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
2184                                        SmallPtrSetImpl<VPValue *> &Candidates,
2185                                        VPInterleavedAccessInfo &IAI);
2186 
2187 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2188   /// Print bundle \p Values to dbgs().
2189   void dumpBundle(ArrayRef<VPValue *> Values);
2190 #endif
2191 
2192 public:
2193   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
2194 
2195   ~VPlanSlp() = default;
2196 
2197   /// Tries to build an SLP tree rooted at \p Operands and returns a
2198   /// VPInstruction combining \p Operands, if they can be combined.
2199   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
2200 
2201   /// Return the width of the widest combined bundle in bits.
2202   unsigned getWidestBundleBits() const { return WidestBundleBits; }
2203 
2204   /// Return true if all visited instruction can be combined.
2205   bool isCompletelySLP() const { return CompletelySLP; }
2206 };
2207 } // end namespace llvm
2208 
2209 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
2210