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 LoopVectorizationLegality;
52 class LoopVectorizationCostModel;
53 class BasicBlock;
54 class DominatorTree;
55 class InnerLoopVectorizer;
56 template <class T> class InterleaveGroup;
57 class LoopInfo;
58 class raw_ostream;
59 class Value;
60 class VPBasicBlock;
61 class VPRegionBlock;
62 class VPlan;
63 class VPlanSlp;
64 
65 /// A range of powers-of-2 vectorization factors with fixed start and
66 /// adjustable end. The range includes start and excludes end, e.g.,:
67 /// [1, 9) = {1, 2, 4, 8}
68 struct VFRange {
69   // A power of 2.
70   const unsigned Start;
71 
72   // Need not be a power of 2. If End <= Start range is empty.
73   unsigned End;
74 };
75 
76 using VPlanPtr = std::unique_ptr<VPlan>;
77 
78 /// In what follows, the term "input IR" refers to code that is fed into the
79 /// vectorizer whereas the term "output IR" refers to code that is generated by
80 /// the vectorizer.
81 
82 /// VPIteration represents a single point in the iteration space of the output
83 /// (vectorized and/or unrolled) IR loop.
84 struct VPIteration {
85   /// in [0..UF)
86   unsigned Part;
87 
88   /// in [0..VF)
89   unsigned Lane;
90 };
91 
92 /// This is a helper struct for maintaining vectorization state. It's used for
93 /// mapping values from the original loop to their corresponding values in
94 /// the new loop. Two mappings are maintained: one for vectorized values and
95 /// one for scalarized values. Vectorized values are represented with UF
96 /// vector values in the new loop, and scalarized values are represented with
97 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
98 /// vectorization factors, respectively.
99 ///
100 /// Entries can be added to either map with setVectorValue and setScalarValue,
101 /// which assert that an entry was not already added before. If an entry is to
102 /// replace an existing one, call resetVectorValue and resetScalarValue. This is
103 /// currently needed to modify the mapped values during "fix-up" operations that
104 /// occur once the first phase of widening is complete. These operations include
105 /// type truncation and the second phase of recurrence widening.
106 ///
107 /// Entries from either map can be retrieved using the getVectorValue and
108 /// getScalarValue functions, which assert that the desired value exists.
109 struct VectorizerValueMap {
110   friend struct VPTransformState;
111 
112 private:
113   /// The unroll factor. Each entry in the vector map contains UF vector values.
114   unsigned UF;
115 
116   /// The vectorization factor. Each entry in the scalar map contains UF x VF
117   /// scalar values.
118   unsigned VF;
119 
120   /// The vector and scalar map storage. We use std::map and not DenseMap
121   /// because insertions to DenseMap invalidate its iterators.
122   using VectorParts = SmallVector<Value *, 2>;
123   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
124   std::map<Value *, VectorParts> VectorMapStorage;
125   std::map<Value *, ScalarParts> ScalarMapStorage;
126 
127 public:
128   /// Construct an empty map with the given unroll and vectorization factors.
129   VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
130 
131   /// \return True if the map has any vector entry for \p Key.
132   bool hasAnyVectorValue(Value *Key) const {
133     return VectorMapStorage.count(Key);
134   }
135 
136   /// \return True if the map has a vector entry for \p Key and \p Part.
137   bool hasVectorValue(Value *Key, unsigned Part) const {
138     assert(Part < UF && "Queried Vector Part is too large.");
139     if (!hasAnyVectorValue(Key))
140       return false;
141     const VectorParts &Entry = VectorMapStorage.find(Key)->second;
142     assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
143     return Entry[Part] != nullptr;
144   }
145 
146   /// \return True if the map has any scalar entry for \p Key.
147   bool hasAnyScalarValue(Value *Key) const {
148     return ScalarMapStorage.count(Key);
149   }
150 
151   /// \return True if the map has a scalar entry for \p Key and \p Instance.
152   bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
153     assert(Instance.Part < UF && "Queried Scalar Part is too large.");
154     assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
155     if (!hasAnyScalarValue(Key))
156       return false;
157     const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
158     assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
159     assert(Entry[Instance.Part].size() == VF &&
160            "ScalarParts has wrong dimensions.");
161     return Entry[Instance.Part][Instance.Lane] != nullptr;
162   }
163 
164   /// Retrieve the existing vector value that corresponds to \p Key and
165   /// \p Part.
166   Value *getVectorValue(Value *Key, unsigned Part) {
167     assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
168     return VectorMapStorage[Key][Part];
169   }
170 
171   /// Retrieve the existing scalar value that corresponds to \p Key and
172   /// \p Instance.
173   Value *getScalarValue(Value *Key, const VPIteration &Instance) {
174     assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
175     return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
176   }
177 
178   /// Set a vector value associated with \p Key and \p Part. Assumes such a
179   /// value is not already set. If it is, use resetVectorValue() instead.
180   void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
181     assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
182     if (!VectorMapStorage.count(Key)) {
183       VectorParts Entry(UF);
184       VectorMapStorage[Key] = Entry;
185     }
186     VectorMapStorage[Key][Part] = Vector;
187   }
188 
189   /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
190   /// value is not already set.
191   void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
192     assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
193     if (!ScalarMapStorage.count(Key)) {
194       ScalarParts Entry(UF);
195       // TODO: Consider storing uniform values only per-part, as they occupy
196       //       lane 0 only, keeping the other VF-1 redundant entries null.
197       for (unsigned Part = 0; Part < UF; ++Part)
198         Entry[Part].resize(VF, nullptr);
199       ScalarMapStorage[Key] = Entry;
200     }
201     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
202   }
203 
204   /// Reset the vector value associated with \p Key for the given \p Part.
205   /// This function can be used to update values that have already been
206   /// vectorized. This is the case for "fix-up" operations including type
207   /// truncation and the second phase of recurrence vectorization.
208   void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
209     assert(hasVectorValue(Key, Part) && "Vector value not set for part");
210     VectorMapStorage[Key][Part] = Vector;
211   }
212 
213   /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
214   /// This function can be used to update values that have already been
215   /// scalarized. This is the case for "fix-up" operations including scalar phi
216   /// nodes for scalarized and predicated instructions.
217   void resetScalarValue(Value *Key, const VPIteration &Instance,
218                         Value *Scalar) {
219     assert(hasScalarValue(Key, Instance) &&
220            "Scalar value not set for part and lane");
221     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
222   }
223 };
224 
225 /// This class is used to enable the VPlan to invoke a method of ILV. This is
226 /// needed until the method is refactored out of ILV and becomes reusable.
227 struct VPCallback {
228   virtual ~VPCallback() {}
229   virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
230   virtual Value *getOrCreateScalarValue(Value *V,
231                                         const VPIteration &Instance) = 0;
232 };
233 
234 /// VPTransformState holds information passed down when "executing" a VPlan,
235 /// needed for generating the output IR.
236 struct VPTransformState {
237   VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
238                    IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
239                    InnerLoopVectorizer *ILV, VPCallback &Callback)
240       : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
241         ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
242 
243   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
244   unsigned VF;
245   unsigned UF;
246 
247   /// Hold the indices to generate specific scalar instructions. Null indicates
248   /// that all instances are to be generated, using either scalar or vector
249   /// instructions.
250   Optional<VPIteration> Instance;
251 
252   struct DataState {
253     /// A type for vectorized values in the new loop. Each value from the
254     /// original loop, when vectorized, is represented by UF vector values in
255     /// the new unrolled loop, where UF is the unroll factor.
256     typedef SmallVector<Value *, 2> PerPartValuesTy;
257 
258     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
259   } Data;
260 
261   /// Get the generated Value for a given VPValue and a given Part. Note that
262   /// as some Defs are still created by ILV and managed in its ValueMap, this
263   /// method will delegate the call to ILV in such cases in order to provide
264   /// callers a consistent API.
265   /// \see set.
266   Value *get(VPValue *Def, unsigned Part) {
267     // If Values have been set for this Def return the one relevant for \p Part.
268     if (Data.PerPartOutput.count(Def))
269       return Data.PerPartOutput[Def][Part];
270     // Def is managed by ILV: bring the Values from ValueMap.
271     return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
272   }
273 
274   /// Get the generated Value for a given VPValue and given Part and Lane. Note
275   /// that as per-lane Defs are still created by ILV and managed in its ValueMap
276   /// this method currently just delegates the call to ILV.
277   Value *get(VPValue *Def, const VPIteration &Instance) {
278     return Callback.getOrCreateScalarValue(VPValue2Value[Def], Instance);
279   }
280 
281   /// Set the generated Value for a given VPValue and a given Part.
282   void set(VPValue *Def, Value *V, unsigned Part) {
283     if (!Data.PerPartOutput.count(Def)) {
284       DataState::PerPartValuesTy Entry(UF);
285       Data.PerPartOutput[Def] = Entry;
286     }
287     Data.PerPartOutput[Def][Part] = V;
288   }
289 
290   /// Hold state information used when constructing the CFG of the output IR,
291   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
292   struct CFGState {
293     /// The previous VPBasicBlock visited. Initially set to null.
294     VPBasicBlock *PrevVPBB = nullptr;
295 
296     /// The previous IR BasicBlock created or used. Initially set to the new
297     /// header BasicBlock.
298     BasicBlock *PrevBB = nullptr;
299 
300     /// The last IR BasicBlock in the output IR. Set to the new latch
301     /// BasicBlock, used for placing the newly created BasicBlocks.
302     BasicBlock *LastBB = nullptr;
303 
304     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
305     /// of replication, maps the BasicBlock of the last replica created.
306     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
307 
308     /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
309     /// up at the end of vector code generation.
310     SmallVector<VPBasicBlock *, 8> VPBBsToFix;
311 
312     CFGState() = default;
313   } CFG;
314 
315   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
316   LoopInfo *LI;
317 
318   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
319   DominatorTree *DT;
320 
321   /// Hold a reference to the IRBuilder used to generate output IR code.
322   IRBuilder<> &Builder;
323 
324   /// Hold a reference to the Value state information used when generating the
325   /// Values of the output IR.
326   VectorizerValueMap &ValueMap;
327 
328   /// Hold a reference to a mapping between VPValues in VPlan and original
329   /// Values they correspond to.
330   VPValue2ValueTy VPValue2Value;
331 
332   /// Hold the trip count of the scalar loop.
333   Value *TripCount = nullptr;
334 
335   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
336   InnerLoopVectorizer *ILV;
337 
338   VPCallback &Callback;
339 };
340 
341 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
342 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
343 class VPBlockBase {
344   friend class VPBlockUtils;
345 
346 private:
347   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
348 
349   /// An optional name for the block.
350   std::string Name;
351 
352   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
353   /// it is a topmost VPBlockBase.
354   VPRegionBlock *Parent = nullptr;
355 
356   /// List of predecessor blocks.
357   SmallVector<VPBlockBase *, 1> Predecessors;
358 
359   /// List of successor blocks.
360   SmallVector<VPBlockBase *, 1> Successors;
361 
362   /// Successor selector, null for zero or single successor blocks.
363   VPValue *CondBit = nullptr;
364 
365   /// Current block predicate - null if the block does not need a predicate.
366   VPValue *Predicate = nullptr;
367 
368   /// VPlan containing the block. Can only be set on the entry block of the
369   /// plan.
370   VPlan *Plan = nullptr;
371 
372   /// Add \p Successor as the last successor to this block.
373   void appendSuccessor(VPBlockBase *Successor) {
374     assert(Successor && "Cannot add nullptr successor!");
375     Successors.push_back(Successor);
376   }
377 
378   /// Add \p Predecessor as the last predecessor to this block.
379   void appendPredecessor(VPBlockBase *Predecessor) {
380     assert(Predecessor && "Cannot add nullptr predecessor!");
381     Predecessors.push_back(Predecessor);
382   }
383 
384   /// Remove \p Predecessor from the predecessors of this block.
385   void removePredecessor(VPBlockBase *Predecessor) {
386     auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
387     assert(Pos && "Predecessor does not exist");
388     Predecessors.erase(Pos);
389   }
390 
391   /// Remove \p Successor from the successors of this block.
392   void removeSuccessor(VPBlockBase *Successor) {
393     auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
394     assert(Pos && "Successor does not exist");
395     Successors.erase(Pos);
396   }
397 
398 protected:
399   VPBlockBase(const unsigned char SC, const std::string &N)
400       : SubclassID(SC), Name(N) {}
401 
402 public:
403   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
404   /// that are actually instantiated. Values of this enumeration are kept in the
405   /// SubclassID field of the VPBlockBase objects. They are used for concrete
406   /// type identification.
407   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
408 
409   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
410 
411   virtual ~VPBlockBase() = default;
412 
413   const std::string &getName() const { return Name; }
414 
415   void setName(const Twine &newName) { Name = newName.str(); }
416 
417   /// \return an ID for the concrete type of this object.
418   /// This is used to implement the classof checks. This should not be used
419   /// for any other purpose, as the values may change as LLVM evolves.
420   unsigned getVPBlockID() const { return SubclassID; }
421 
422   VPRegionBlock *getParent() { return Parent; }
423   const VPRegionBlock *getParent() const { return Parent; }
424 
425   /// \return A pointer to the plan containing the current block.
426   VPlan *getPlan();
427   const VPlan *getPlan() const;
428 
429   /// Sets the pointer of the plan containing the block. The block must be the
430   /// entry block into the VPlan.
431   void setPlan(VPlan *ParentPlan);
432 
433   void setParent(VPRegionBlock *P) { Parent = P; }
434 
435   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
436   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
437   /// VPBlockBase is a VPBasicBlock, it is returned.
438   const VPBasicBlock *getEntryBasicBlock() const;
439   VPBasicBlock *getEntryBasicBlock();
440 
441   /// \return the VPBasicBlock that is the exit of this VPBlockBase,
442   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
443   /// VPBlockBase is a VPBasicBlock, it is returned.
444   const VPBasicBlock *getExitBasicBlock() const;
445   VPBasicBlock *getExitBasicBlock();
446 
447   const VPBlocksTy &getSuccessors() const { return Successors; }
448   VPBlocksTy &getSuccessors() { return Successors; }
449 
450   const VPBlocksTy &getPredecessors() const { return Predecessors; }
451   VPBlocksTy &getPredecessors() { return Predecessors; }
452 
453   /// \return the successor of this VPBlockBase if it has a single successor.
454   /// Otherwise return a null pointer.
455   VPBlockBase *getSingleSuccessor() const {
456     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
457   }
458 
459   /// \return the predecessor of this VPBlockBase if it has a single
460   /// predecessor. Otherwise return a null pointer.
461   VPBlockBase *getSinglePredecessor() const {
462     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
463   }
464 
465   size_t getNumSuccessors() const { return Successors.size(); }
466   size_t getNumPredecessors() const { return Predecessors.size(); }
467 
468   /// An Enclosing Block of a block B is any block containing B, including B
469   /// itself. \return the closest enclosing block starting from "this", which
470   /// has successors. \return the root enclosing block if all enclosing blocks
471   /// have no successors.
472   VPBlockBase *getEnclosingBlockWithSuccessors();
473 
474   /// \return the closest enclosing block starting from "this", which has
475   /// predecessors. \return the root enclosing block if all enclosing blocks
476   /// have no predecessors.
477   VPBlockBase *getEnclosingBlockWithPredecessors();
478 
479   /// \return the successors either attached directly to this VPBlockBase or, if
480   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
481   /// successors of its own, search recursively for the first enclosing
482   /// VPRegionBlock that has successors and return them. If no such
483   /// VPRegionBlock exists, return the (empty) successors of the topmost
484   /// VPBlockBase reached.
485   const VPBlocksTy &getHierarchicalSuccessors() {
486     return getEnclosingBlockWithSuccessors()->getSuccessors();
487   }
488 
489   /// \return the hierarchical successor of this VPBlockBase if it has a single
490   /// hierarchical successor. Otherwise return a null pointer.
491   VPBlockBase *getSingleHierarchicalSuccessor() {
492     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
493   }
494 
495   /// \return the predecessors either attached directly to this VPBlockBase or,
496   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
497   /// predecessors of its own, search recursively for the first enclosing
498   /// VPRegionBlock that has predecessors and return them. If no such
499   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
500   /// VPBlockBase reached.
501   const VPBlocksTy &getHierarchicalPredecessors() {
502     return getEnclosingBlockWithPredecessors()->getPredecessors();
503   }
504 
505   /// \return the hierarchical predecessor of this VPBlockBase if it has a
506   /// single hierarchical predecessor. Otherwise return a null pointer.
507   VPBlockBase *getSingleHierarchicalPredecessor() {
508     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
509   }
510 
511   /// \return the condition bit selecting the successor.
512   VPValue *getCondBit() { return CondBit; }
513 
514   const VPValue *getCondBit() const { return CondBit; }
515 
516   void setCondBit(VPValue *CV) { CondBit = CV; }
517 
518   VPValue *getPredicate() { return Predicate; }
519 
520   const VPValue *getPredicate() const { return Predicate; }
521 
522   void setPredicate(VPValue *Pred) { Predicate = Pred; }
523 
524   /// Set a given VPBlockBase \p Successor as the single successor of this
525   /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
526   /// This VPBlockBase must have no successors.
527   void setOneSuccessor(VPBlockBase *Successor) {
528     assert(Successors.empty() && "Setting one successor when others exist.");
529     appendSuccessor(Successor);
530   }
531 
532   /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
533   /// successors of this VPBlockBase. \p Condition is set as the successor
534   /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
535   /// IfFalse. This VPBlockBase must have no successors.
536   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
537                         VPValue *Condition) {
538     assert(Successors.empty() && "Setting two successors when others exist.");
539     assert(Condition && "Setting two successors without condition!");
540     CondBit = Condition;
541     appendSuccessor(IfTrue);
542     appendSuccessor(IfFalse);
543   }
544 
545   /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
546   /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
547   /// as successor of any VPBasicBlock in \p NewPreds.
548   void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
549     assert(Predecessors.empty() && "Block predecessors already set.");
550     for (auto *Pred : NewPreds)
551       appendPredecessor(Pred);
552   }
553 
554   /// Remove all the predecessor of this block.
555   void clearPredecessors() { Predecessors.clear(); }
556 
557   /// Remove all the successors of this block and set to null its condition bit
558   void clearSuccessors() {
559     Successors.clear();
560     CondBit = nullptr;
561   }
562 
563   /// The method which generates the output IR that correspond to this
564   /// VPBlockBase, thereby "executing" the VPlan.
565   virtual void execute(struct VPTransformState *State) = 0;
566 
567   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
568   static void deleteCFG(VPBlockBase *Entry);
569 
570   void printAsOperand(raw_ostream &OS, bool PrintType) const {
571     OS << getName();
572   }
573 
574   void print(raw_ostream &OS) const {
575     // TODO: Only printing VPBB name for now since we only have dot printing
576     // support for VPInstructions/Recipes.
577     printAsOperand(OS, false);
578   }
579 
580   /// Return true if it is legal to hoist instructions into this block.
581   bool isLegalToHoistInto() {
582     // There are currently no constraints that prevent an instruction to be
583     // hoisted into a VPBlockBase.
584     return true;
585   }
586 };
587 
588 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
589 /// instructions.
590 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
591   friend VPBasicBlock;
592   friend class VPBlockUtils;
593 
594 private:
595   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
596 
597   /// Each VPRecipe belongs to a single VPBasicBlock.
598   VPBasicBlock *Parent = nullptr;
599 
600 public:
601   /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
602   /// that is actually instantiated. Values of this enumeration are kept in the
603   /// SubclassID field of the VPRecipeBase objects. They are used for concrete
604   /// type identification.
605   using VPRecipeTy = enum {
606     VPBlendSC,
607     VPBranchOnMaskSC,
608     VPInstructionSC,
609     VPInterleaveSC,
610     VPPredInstPHISC,
611     VPReplicateSC,
612     VPWidenGEPSC,
613     VPWidenIntOrFpInductionSC,
614     VPWidenMemoryInstructionSC,
615     VPWidenPHISC,
616     VPWidenSC,
617   };
618 
619   VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
620   virtual ~VPRecipeBase() = default;
621 
622   /// \return an ID for the concrete type of this object.
623   /// This is used to implement the classof checks. This should not be used
624   /// for any other purpose, as the values may change as LLVM evolves.
625   unsigned getVPRecipeID() const { return SubclassID; }
626 
627   /// \return the VPBasicBlock which this VPRecipe belongs to.
628   VPBasicBlock *getParent() { return Parent; }
629   const VPBasicBlock *getParent() const { return Parent; }
630 
631   /// The method which generates the output IR instructions that correspond to
632   /// this VPRecipe, thereby "executing" the VPlan.
633   virtual void execute(struct VPTransformState &State) = 0;
634 
635   /// Each recipe prints itself.
636   void print(raw_ostream &O, const Twine &Indent);
637   virtual void print(raw_ostream &O, const Twine &Indent,
638                      VPSlotTracker &SlotTracker) const = 0;
639 
640   /// Insert an unlinked recipe into a basic block immediately before
641   /// the specified recipe.
642   void insertBefore(VPRecipeBase *InsertPos);
643 
644   /// Insert an unlinked Recipe into a basic block immediately after
645   /// the specified Recipe.
646   void insertAfter(VPRecipeBase *InsertPos);
647 
648   /// Unlink this recipe from its current VPBasicBlock and insert it into
649   /// the VPBasicBlock that MovePos lives in, right after MovePos.
650   void moveAfter(VPRecipeBase *MovePos);
651 
652   /// This method unlinks 'this' from the containing basic block, but does not
653   /// delete it.
654   void removeFromParent();
655 
656   /// This method unlinks 'this' from the containing basic block and deletes it.
657   ///
658   /// \returns an iterator pointing to the element after the erased one
659   iplist<VPRecipeBase>::iterator eraseFromParent();
660 };
661 
662 /// This is a concrete Recipe that models a single VPlan-level instruction.
663 /// While as any Recipe it may generate a sequence of IR instructions when
664 /// executed, these instructions would always form a single-def expression as
665 /// the VPInstruction is also a single def-use vertex.
666 class VPInstruction : public VPUser, public VPRecipeBase {
667   friend class VPlanSlp;
668 
669 public:
670   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
671   enum {
672     Not = Instruction::OtherOpsEnd + 1,
673     ICmpULE,
674     SLPLoad,
675     SLPStore,
676   };
677 
678 private:
679   typedef unsigned char OpcodeTy;
680   OpcodeTy Opcode;
681 
682   /// Utility method serving execute(): generates a single instance of the
683   /// modeled instruction.
684   void generateInstruction(VPTransformState &State, unsigned Part);
685 
686 protected:
687   Instruction *getUnderlyingInstr() {
688     return cast_or_null<Instruction>(getUnderlyingValue());
689   }
690 
691   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
692 
693 public:
694   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
695       : VPUser(VPValue::VPInstructionSC, Operands),
696         VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
697 
698   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
699       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
700 
701   /// Method to support type inquiry through isa, cast, and dyn_cast.
702   static inline bool classof(const VPValue *V) {
703     return V->getVPValueID() == VPValue::VPInstructionSC;
704   }
705 
706   VPInstruction *clone() const {
707     SmallVector<VPValue *, 2> Operands(operands());
708     return new VPInstruction(Opcode, Operands);
709   }
710 
711   /// Method to support type inquiry through isa, cast, and dyn_cast.
712   static inline bool classof(const VPRecipeBase *R) {
713     return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
714   }
715 
716   unsigned getOpcode() const { return Opcode; }
717 
718   /// Generate the instruction.
719   /// TODO: We currently execute only per-part unless a specific instance is
720   /// provided.
721   void execute(VPTransformState &State) override;
722 
723   /// Print the Recipe.
724   void print(raw_ostream &O, const Twine &Indent,
725              VPSlotTracker &SlotTracker) const override;
726 
727   /// Print the VPInstruction.
728   void print(raw_ostream &O) const;
729   void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
730 
731   /// Return true if this instruction may modify memory.
732   bool mayWriteToMemory() const {
733     // TODO: we can use attributes of the called function to rule out memory
734     //       modifications.
735     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
736            Opcode == Instruction::Invoke || Opcode == SLPStore;
737   }
738 
739   bool hasResult() const {
740     // CallInst may or may not have a result, depending on the called function.
741     // Conservatively return calls have results for now.
742     switch (getOpcode()) {
743     case Instruction::Ret:
744     case Instruction::Br:
745     case Instruction::Store:
746     case Instruction::Switch:
747     case Instruction::IndirectBr:
748     case Instruction::Resume:
749     case Instruction::CatchRet:
750     case Instruction::Unreachable:
751     case Instruction::Fence:
752     case Instruction::AtomicRMW:
753       return false;
754     default:
755       return true;
756     }
757   }
758 };
759 
760 /// VPWidenRecipe is a recipe for producing a copy of vector type for each
761 /// Instruction in its ingredients independently, in order. This recipe covers
762 /// most of the traditional vectorization cases where each ingredient transforms
763 /// into a vectorized version of itself.
764 class VPWidenRecipe : public VPRecipeBase {
765 private:
766   /// Hold the ingredients by pointing to their original BasicBlock location.
767   BasicBlock::iterator Begin;
768   BasicBlock::iterator End;
769 
770 public:
771   VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
772     End = I->getIterator();
773     Begin = End++;
774   }
775 
776   ~VPWidenRecipe() override = default;
777 
778   /// Method to support type inquiry through isa, cast, and dyn_cast.
779   static inline bool classof(const VPRecipeBase *V) {
780     return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
781   }
782 
783   /// Produce widened copies of all Ingredients.
784   void execute(VPTransformState &State) override;
785 
786   /// Augment the recipe to include Instr, if it lies at its End.
787   bool appendInstruction(Instruction *Instr) {
788     if (End != Instr->getIterator())
789       return false;
790     End++;
791     return true;
792   }
793 
794   /// Print the recipe.
795   void print(raw_ostream &O, const Twine &Indent,
796              VPSlotTracker &SlotTracker) const override;
797 };
798 
799 /// A recipe for handling GEP instructions.
800 class VPWidenGEPRecipe : public VPRecipeBase {
801 private:
802   GetElementPtrInst *GEP;
803   bool IsPtrLoopInvariant;
804   SmallBitVector IsIndexLoopInvariant;
805 
806 public:
807   VPWidenGEPRecipe(GetElementPtrInst *GEP, Loop *OrigLoop)
808       : VPRecipeBase(VPWidenGEPSC), GEP(GEP),
809         IsIndexLoopInvariant(GEP->getNumIndices(), false) {
810     IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
811     for (auto Index : enumerate(GEP->indices()))
812       IsIndexLoopInvariant[Index.index()] =
813           OrigLoop->isLoopInvariant(Index.value().get());
814   }
815   ~VPWidenGEPRecipe() override = default;
816 
817   /// Method to support type inquiry through isa, cast, and dyn_cast.
818   static inline bool classof(const VPRecipeBase *V) {
819     return V->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC;
820   }
821 
822   /// Generate the gep nodes.
823   void execute(VPTransformState &State) override;
824 
825   /// Print the recipe.
826   void print(raw_ostream &O, const Twine &Indent,
827              VPSlotTracker &SlotTracker) const override;
828 };
829 
830 /// A recipe for handling phi nodes of integer and floating-point inductions,
831 /// producing their vector and scalar values.
832 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
833 private:
834   PHINode *IV;
835   TruncInst *Trunc;
836 
837 public:
838   VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
839       : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
840   ~VPWidenIntOrFpInductionRecipe() override = default;
841 
842   /// Method to support type inquiry through isa, cast, and dyn_cast.
843   static inline bool classof(const VPRecipeBase *V) {
844     return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
845   }
846 
847   /// Generate the vectorized and scalarized versions of the phi node as
848   /// needed by their users.
849   void execute(VPTransformState &State) override;
850 
851   /// Print the recipe.
852   void print(raw_ostream &O, const Twine &Indent,
853              VPSlotTracker &SlotTracker) const override;
854 };
855 
856 /// A recipe for handling all phi nodes except for integer and FP inductions.
857 class VPWidenPHIRecipe : public VPRecipeBase {
858 private:
859   PHINode *Phi;
860 
861 public:
862   VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
863   ~VPWidenPHIRecipe() override = default;
864 
865   /// Method to support type inquiry through isa, cast, and dyn_cast.
866   static inline bool classof(const VPRecipeBase *V) {
867     return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
868   }
869 
870   /// Generate the phi/select nodes.
871   void execute(VPTransformState &State) override;
872 
873   /// Print the recipe.
874   void print(raw_ostream &O, const Twine &Indent,
875              VPSlotTracker &SlotTracker) const override;
876 };
877 
878 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
879 /// instructions.
880 class VPBlendRecipe : public VPRecipeBase {
881 private:
882   PHINode *Phi;
883 
884   /// The blend operation is a User of a mask, if not null.
885   std::unique_ptr<VPUser> User;
886 
887 public:
888   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
889       : VPRecipeBase(VPBlendSC), Phi(Phi) {
890     assert((Phi->getNumIncomingValues() == 1 ||
891             Phi->getNumIncomingValues() == Masks.size()) &&
892            "Expected the same number of incoming values and masks");
893     if (!Masks.empty())
894       User.reset(new VPUser(Masks));
895   }
896 
897   /// Method to support type inquiry through isa, cast, and dyn_cast.
898   static inline bool classof(const VPRecipeBase *V) {
899     return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
900   }
901 
902   /// Generate the phi/select nodes.
903   void execute(VPTransformState &State) override;
904 
905   /// Print the recipe.
906   void print(raw_ostream &O, const Twine &Indent,
907              VPSlotTracker &SlotTracker) const override;
908 };
909 
910 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
911 /// or stores into one wide load/store and shuffles.
912 class VPInterleaveRecipe : public VPRecipeBase {
913 private:
914   const InterleaveGroup<Instruction> *IG;
915   VPUser User;
916 
917 public:
918   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr,
919                      VPValue *Mask)
920       : VPRecipeBase(VPInterleaveSC), IG(IG), User({Addr}) {
921     if (Mask)
922       User.addOperand(Mask);
923   }
924   ~VPInterleaveRecipe() override = default;
925 
926   /// Method to support type inquiry through isa, cast, and dyn_cast.
927   static inline bool classof(const VPRecipeBase *V) {
928     return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
929   }
930 
931   /// Return the address accessed by this recipe.
932   VPValue *getAddr() const {
933     return User.getOperand(0); // Address is the 1st, mandatory operand.
934   }
935 
936   /// Return the mask used by this recipe. Note that a full mask is represented
937   /// by a nullptr.
938   VPValue *getMask() const {
939     // Mask is optional and therefore the last, currently 2nd operand.
940     return User.getNumOperands() == 2 ? User.getOperand(1) : nullptr;
941   }
942 
943   /// Generate the wide load or store, and shuffles.
944   void execute(VPTransformState &State) override;
945 
946   /// Print the recipe.
947   void print(raw_ostream &O, const Twine &Indent,
948              VPSlotTracker &SlotTracker) const override;
949 
950   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
951 };
952 
953 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
954 /// copies of the original scalar type, one per lane, instead of producing a
955 /// single copy of widened type for all lanes. If the instruction is known to be
956 /// uniform only one copy, per lane zero, will be generated.
957 class VPReplicateRecipe : public VPRecipeBase {
958 private:
959   /// The instruction being replicated.
960   Instruction *Ingredient;
961 
962   /// Indicator if only a single replica per lane is needed.
963   bool IsUniform;
964 
965   /// Indicator if the replicas are also predicated.
966   bool IsPredicated;
967 
968   /// Indicator if the scalar values should also be packed into a vector.
969   bool AlsoPack;
970 
971 public:
972   VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
973       : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
974         IsPredicated(IsPredicated) {
975     // Retain the previous behavior of predicateInstructions(), where an
976     // insert-element of a predicated instruction got hoisted into the
977     // predicated basic block iff it was its only user. This is achieved by
978     // having predicated instructions also pack their values into a vector by
979     // default unless they have a replicated user which uses their scalar value.
980     AlsoPack = IsPredicated && !I->use_empty();
981   }
982 
983   ~VPReplicateRecipe() override = default;
984 
985   /// Method to support type inquiry through isa, cast, and dyn_cast.
986   static inline bool classof(const VPRecipeBase *V) {
987     return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
988   }
989 
990   /// Generate replicas of the desired Ingredient. Replicas will be generated
991   /// for all parts and lanes unless a specific part and lane are specified in
992   /// the \p State.
993   void execute(VPTransformState &State) override;
994 
995   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
996 
997   /// Print the recipe.
998   void print(raw_ostream &O, const Twine &Indent,
999              VPSlotTracker &SlotTracker) const override;
1000 };
1001 
1002 /// A recipe for generating conditional branches on the bits of a mask.
1003 class VPBranchOnMaskRecipe : public VPRecipeBase {
1004 private:
1005   std::unique_ptr<VPUser> User;
1006 
1007 public:
1008   VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
1009     if (BlockInMask) // nullptr means all-one mask.
1010       User.reset(new VPUser({BlockInMask}));
1011   }
1012 
1013   /// Method to support type inquiry through isa, cast, and dyn_cast.
1014   static inline bool classof(const VPRecipeBase *V) {
1015     return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
1016   }
1017 
1018   /// Generate the extraction of the appropriate bit from the block mask and the
1019   /// conditional branch.
1020   void execute(VPTransformState &State) override;
1021 
1022   /// Print the recipe.
1023   void print(raw_ostream &O, const Twine &Indent,
1024              VPSlotTracker &SlotTracker) const override {
1025     O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
1026     if (User)
1027       User->getOperand(0)->print(O, SlotTracker);
1028     else
1029       O << " All-One";
1030     O << "\\l\"";
1031   }
1032 };
1033 
1034 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1035 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1036 /// order to merge values that are set under such a branch and feed their uses.
1037 /// The phi nodes can be scalar or vector depending on the users of the value.
1038 /// This recipe works in concert with VPBranchOnMaskRecipe.
1039 class VPPredInstPHIRecipe : public VPRecipeBase {
1040 private:
1041   Instruction *PredInst;
1042 
1043 public:
1044   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1045   /// nodes after merging back from a Branch-on-Mask.
1046   VPPredInstPHIRecipe(Instruction *PredInst)
1047       : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
1048   ~VPPredInstPHIRecipe() override = default;
1049 
1050   /// Method to support type inquiry through isa, cast, and dyn_cast.
1051   static inline bool classof(const VPRecipeBase *V) {
1052     return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
1053   }
1054 
1055   /// Generates phi nodes for live-outs as needed to retain SSA form.
1056   void execute(VPTransformState &State) override;
1057 
1058   /// Print the recipe.
1059   void print(raw_ostream &O, const Twine &Indent,
1060              VPSlotTracker &SlotTracker) const override;
1061 };
1062 
1063 /// A Recipe for widening load/store operations.
1064 /// The recipe uses the following VPValues:
1065 /// - For load: Address, optional mask
1066 /// - For store: Address, stored value, optional mask
1067 /// TODO: We currently execute only per-part unless a specific instance is
1068 /// provided.
1069 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
1070 private:
1071   Instruction &Instr;
1072   VPUser User;
1073 
1074   void setMask(VPValue *Mask) {
1075     if (!Mask)
1076       return;
1077     User.addOperand(Mask);
1078   }
1079 
1080   bool isMasked() const {
1081     return (isa<LoadInst>(Instr) && User.getNumOperands() == 2) ||
1082            (isa<StoreInst>(Instr) && User.getNumOperands() == 3);
1083   }
1084 
1085 public:
1086   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask)
1087       : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Load), User({Addr}) {
1088     setMask(Mask);
1089   }
1090 
1091   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1092                                  VPValue *StoredValue, VPValue *Mask)
1093       : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Store),
1094         User({Addr, StoredValue}) {
1095     setMask(Mask);
1096   }
1097 
1098   /// Method to support type inquiry through isa, cast, and dyn_cast.
1099   static inline bool classof(const VPRecipeBase *V) {
1100     return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1101   }
1102 
1103   /// Return the address accessed by this recipe.
1104   VPValue *getAddr() const {
1105     return User.getOperand(0); // Address is the 1st, mandatory operand.
1106   }
1107 
1108   /// Return the mask used by this recipe. Note that a full mask is represented
1109   /// by a nullptr.
1110   VPValue *getMask() const {
1111     // Mask is optional and therefore the last operand.
1112     return isMasked() ? User.getOperand(User.getNumOperands() - 1) : nullptr;
1113   }
1114 
1115   /// Return the address accessed by this recipe.
1116   VPValue *getStoredValue() const {
1117     assert(isa<StoreInst>(Instr) &&
1118            "Stored value only available for store instructions");
1119     return User.getOperand(1); // Stored value is the 2nd, mandatory operand.
1120   }
1121 
1122   /// Generate the wide load/store.
1123   void execute(VPTransformState &State) override;
1124 
1125   /// Print the recipe.
1126   void print(raw_ostream &O, const Twine &Indent,
1127              VPSlotTracker &SlotTracker) const override;
1128 };
1129 
1130 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1131 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1132 /// output IR instructions.
1133 class VPBasicBlock : public VPBlockBase {
1134 public:
1135   using RecipeListTy = iplist<VPRecipeBase>;
1136 
1137 private:
1138   /// The VPRecipes held in the order of output instructions to generate.
1139   RecipeListTy Recipes;
1140 
1141 public:
1142   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1143       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1144     if (Recipe)
1145       appendRecipe(Recipe);
1146   }
1147 
1148   ~VPBasicBlock() override { Recipes.clear(); }
1149 
1150   /// Instruction iterators...
1151   using iterator = RecipeListTy::iterator;
1152   using const_iterator = RecipeListTy::const_iterator;
1153   using reverse_iterator = RecipeListTy::reverse_iterator;
1154   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1155 
1156   //===--------------------------------------------------------------------===//
1157   /// Recipe iterator methods
1158   ///
1159   inline iterator begin() { return Recipes.begin(); }
1160   inline const_iterator begin() const { return Recipes.begin(); }
1161   inline iterator end() { return Recipes.end(); }
1162   inline const_iterator end() const { return Recipes.end(); }
1163 
1164   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1165   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1166   inline reverse_iterator rend() { return Recipes.rend(); }
1167   inline const_reverse_iterator rend() const { return Recipes.rend(); }
1168 
1169   inline size_t size() const { return Recipes.size(); }
1170   inline bool empty() const { return Recipes.empty(); }
1171   inline const VPRecipeBase &front() const { return Recipes.front(); }
1172   inline VPRecipeBase &front() { return Recipes.front(); }
1173   inline const VPRecipeBase &back() const { return Recipes.back(); }
1174   inline VPRecipeBase &back() { return Recipes.back(); }
1175 
1176   /// Returns a reference to the list of recipes.
1177   RecipeListTy &getRecipeList() { return Recipes; }
1178 
1179   /// Returns a pointer to a member of the recipe list.
1180   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1181     return &VPBasicBlock::Recipes;
1182   }
1183 
1184   /// Method to support type inquiry through isa, cast, and dyn_cast.
1185   static inline bool classof(const VPBlockBase *V) {
1186     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1187   }
1188 
1189   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
1190     assert(Recipe && "No recipe to append.");
1191     assert(!Recipe->Parent && "Recipe already in VPlan");
1192     Recipe->Parent = this;
1193     Recipes.insert(InsertPt, Recipe);
1194   }
1195 
1196   /// Augment the existing recipes of a VPBasicBlock with an additional
1197   /// \p Recipe as the last recipe.
1198   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1199 
1200   /// The method which generates the output IR instructions that correspond to
1201   /// this VPBasicBlock, thereby "executing" the VPlan.
1202   void execute(struct VPTransformState *State) override;
1203 
1204 private:
1205   /// Create an IR BasicBlock to hold the output instructions generated by this
1206   /// VPBasicBlock, and return it. Update the CFGState accordingly.
1207   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1208 };
1209 
1210 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1211 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1212 /// A VPRegionBlock may indicate that its contents are to be replicated several
1213 /// times. This is designed to support predicated scalarization, in which a
1214 /// scalar if-then code structure needs to be generated VF * UF times. Having
1215 /// this replication indicator helps to keep a single model for multiple
1216 /// candidate VF's. The actual replication takes place only once the desired VF
1217 /// and UF have been determined.
1218 class VPRegionBlock : public VPBlockBase {
1219 private:
1220   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1221   VPBlockBase *Entry;
1222 
1223   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1224   VPBlockBase *Exit;
1225 
1226   /// An indicator whether this region is to generate multiple replicated
1227   /// instances of output IR corresponding to its VPBlockBases.
1228   bool IsReplicator;
1229 
1230 public:
1231   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1232                 const std::string &Name = "", bool IsReplicator = false)
1233       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1234         IsReplicator(IsReplicator) {
1235     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1236     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1237     Entry->setParent(this);
1238     Exit->setParent(this);
1239   }
1240   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1241       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1242         IsReplicator(IsReplicator) {}
1243 
1244   ~VPRegionBlock() override {
1245     if (Entry)
1246       deleteCFG(Entry);
1247   }
1248 
1249   /// Method to support type inquiry through isa, cast, and dyn_cast.
1250   static inline bool classof(const VPBlockBase *V) {
1251     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1252   }
1253 
1254   const VPBlockBase *getEntry() const { return Entry; }
1255   VPBlockBase *getEntry() { return Entry; }
1256 
1257   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1258   /// EntryBlock must have no predecessors.
1259   void setEntry(VPBlockBase *EntryBlock) {
1260     assert(EntryBlock->getPredecessors().empty() &&
1261            "Entry block cannot have predecessors.");
1262     Entry = EntryBlock;
1263     EntryBlock->setParent(this);
1264   }
1265 
1266   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1267   // specific interface of llvm::Function, instead of using
1268   // GraphTraints::getEntryNode. We should add a new template parameter to
1269   // DominatorTreeBase representing the Graph type.
1270   VPBlockBase &front() const { return *Entry; }
1271 
1272   const VPBlockBase *getExit() const { return Exit; }
1273   VPBlockBase *getExit() { return Exit; }
1274 
1275   /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1276   /// ExitBlock must have no successors.
1277   void setExit(VPBlockBase *ExitBlock) {
1278     assert(ExitBlock->getSuccessors().empty() &&
1279            "Exit block cannot have successors.");
1280     Exit = ExitBlock;
1281     ExitBlock->setParent(this);
1282   }
1283 
1284   /// An indicator whether this region is to generate multiple replicated
1285   /// instances of output IR corresponding to its VPBlockBases.
1286   bool isReplicator() const { return IsReplicator; }
1287 
1288   /// The method which generates the output IR instructions that correspond to
1289   /// this VPRegionBlock, thereby "executing" the VPlan.
1290   void execute(struct VPTransformState *State) override;
1291 };
1292 
1293 //===----------------------------------------------------------------------===//
1294 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
1295 //===----------------------------------------------------------------------===//
1296 
1297 // The following set of template specializations implement GraphTraits to treat
1298 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1299 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1300 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1301 // successors/predecessors but not to the blocks inside the region.
1302 
1303 template <> struct GraphTraits<VPBlockBase *> {
1304   using NodeRef = VPBlockBase *;
1305   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1306 
1307   static NodeRef getEntryNode(NodeRef N) { return N; }
1308 
1309   static inline ChildIteratorType child_begin(NodeRef N) {
1310     return N->getSuccessors().begin();
1311   }
1312 
1313   static inline ChildIteratorType child_end(NodeRef N) {
1314     return N->getSuccessors().end();
1315   }
1316 };
1317 
1318 template <> struct GraphTraits<const VPBlockBase *> {
1319   using NodeRef = const VPBlockBase *;
1320   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1321 
1322   static NodeRef getEntryNode(NodeRef N) { return N; }
1323 
1324   static inline ChildIteratorType child_begin(NodeRef N) {
1325     return N->getSuccessors().begin();
1326   }
1327 
1328   static inline ChildIteratorType child_end(NodeRef N) {
1329     return N->getSuccessors().end();
1330   }
1331 };
1332 
1333 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1334 // of successors for the inverse traversal.
1335 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1336   using NodeRef = VPBlockBase *;
1337   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1338 
1339   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1340 
1341   static inline ChildIteratorType child_begin(NodeRef N) {
1342     return N->getPredecessors().begin();
1343   }
1344 
1345   static inline ChildIteratorType child_end(NodeRef N) {
1346     return N->getPredecessors().end();
1347   }
1348 };
1349 
1350 // The following set of template specializations implement GraphTraits to
1351 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1352 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1353 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1354 // there won't be automatic recursion into other VPBlockBases that turn to be
1355 // VPRegionBlocks.
1356 
1357 template <>
1358 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1359   using GraphRef = VPRegionBlock *;
1360   using nodes_iterator = df_iterator<NodeRef>;
1361 
1362   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1363 
1364   static nodes_iterator nodes_begin(GraphRef N) {
1365     return nodes_iterator::begin(N->getEntry());
1366   }
1367 
1368   static nodes_iterator nodes_end(GraphRef N) {
1369     // df_iterator::end() returns an empty iterator so the node used doesn't
1370     // matter.
1371     return nodes_iterator::end(N);
1372   }
1373 };
1374 
1375 template <>
1376 struct GraphTraits<const VPRegionBlock *>
1377     : public GraphTraits<const VPBlockBase *> {
1378   using GraphRef = const VPRegionBlock *;
1379   using nodes_iterator = df_iterator<NodeRef>;
1380 
1381   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1382 
1383   static nodes_iterator nodes_begin(GraphRef N) {
1384     return nodes_iterator::begin(N->getEntry());
1385   }
1386 
1387   static nodes_iterator nodes_end(GraphRef N) {
1388     // df_iterator::end() returns an empty iterator so the node used doesn't
1389     // matter.
1390     return nodes_iterator::end(N);
1391   }
1392 };
1393 
1394 template <>
1395 struct GraphTraits<Inverse<VPRegionBlock *>>
1396     : public GraphTraits<Inverse<VPBlockBase *>> {
1397   using GraphRef = VPRegionBlock *;
1398   using nodes_iterator = df_iterator<NodeRef>;
1399 
1400   static NodeRef getEntryNode(Inverse<GraphRef> N) {
1401     return N.Graph->getExit();
1402   }
1403 
1404   static nodes_iterator nodes_begin(GraphRef N) {
1405     return nodes_iterator::begin(N->getExit());
1406   }
1407 
1408   static nodes_iterator nodes_end(GraphRef N) {
1409     // df_iterator::end() returns an empty iterator so the node used doesn't
1410     // matter.
1411     return nodes_iterator::end(N);
1412   }
1413 };
1414 
1415 class VPSlotTracker;
1416 /// VPlan models a candidate for vectorization, encoding various decisions take
1417 /// to produce efficient output IR, including which branches, basic-blocks and
1418 /// output IR instructions to generate, and their cost. VPlan holds a
1419 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1420 /// VPBlock.
1421 class VPlan {
1422   friend class VPlanPrinter;
1423   friend class VPSlotTracker;
1424 
1425 private:
1426   /// Hold the single entry to the Hierarchical CFG of the VPlan.
1427   VPBlockBase *Entry;
1428 
1429   /// Holds the VFs applicable to this VPlan.
1430   SmallSet<unsigned, 2> VFs;
1431 
1432   /// Holds the name of the VPlan, for printing.
1433   std::string Name;
1434 
1435   /// Holds all the external definitions created for this VPlan.
1436   // TODO: Introduce a specific representation for external definitions in
1437   // VPlan. External definitions must be immutable and hold a pointer to its
1438   // underlying IR that will be used to implement its structural comparison
1439   // (operators '==' and '<').
1440   SmallPtrSet<VPValue *, 16> VPExternalDefs;
1441 
1442   /// Represents the backedge taken count of the original loop, for folding
1443   /// the tail.
1444   VPValue *BackedgeTakenCount = nullptr;
1445 
1446   /// Holds a mapping between Values and their corresponding VPValue inside
1447   /// VPlan.
1448   Value2VPValueTy Value2VPValue;
1449 
1450   /// Holds the VPLoopInfo analysis for this VPlan.
1451   VPLoopInfo VPLInfo;
1452 
1453   /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1454   SmallVector<VPValue *, 4> VPCBVs;
1455 
1456 public:
1457   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
1458     if (Entry)
1459       Entry->setPlan(this);
1460   }
1461 
1462   ~VPlan() {
1463     if (Entry)
1464       VPBlockBase::deleteCFG(Entry);
1465     for (auto &MapEntry : Value2VPValue)
1466       if (MapEntry.second != BackedgeTakenCount)
1467         delete MapEntry.second;
1468     if (BackedgeTakenCount)
1469       delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not.
1470     for (VPValue *Def : VPExternalDefs)
1471       delete Def;
1472     for (VPValue *CBV : VPCBVs)
1473       delete CBV;
1474   }
1475 
1476   /// Generate the IR code for this VPlan.
1477   void execute(struct VPTransformState *State);
1478 
1479   VPBlockBase *getEntry() { return Entry; }
1480   const VPBlockBase *getEntry() const { return Entry; }
1481 
1482   VPBlockBase *setEntry(VPBlockBase *Block) {
1483     Entry = Block;
1484     Block->setPlan(this);
1485     return Entry;
1486   }
1487 
1488   /// The backedge taken count of the original loop.
1489   VPValue *getOrCreateBackedgeTakenCount() {
1490     if (!BackedgeTakenCount)
1491       BackedgeTakenCount = new VPValue();
1492     return BackedgeTakenCount;
1493   }
1494 
1495   void addVF(unsigned VF) { VFs.insert(VF); }
1496 
1497   bool hasVF(unsigned VF) { return VFs.count(VF); }
1498 
1499   const std::string &getName() const { return Name; }
1500 
1501   void setName(const Twine &newName) { Name = newName.str(); }
1502 
1503   /// Add \p VPVal to the pool of external definitions if it's not already
1504   /// in the pool.
1505   void addExternalDef(VPValue *VPVal) {
1506     VPExternalDefs.insert(VPVal);
1507   }
1508 
1509   /// Add \p CBV to the vector of condition bit values.
1510   void addCBV(VPValue *CBV) {
1511     VPCBVs.push_back(CBV);
1512   }
1513 
1514   void addVPValue(Value *V) {
1515     assert(V && "Trying to add a null Value to VPlan");
1516     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1517     Value2VPValue[V] = new VPValue(V);
1518   }
1519 
1520   VPValue *getVPValue(Value *V) {
1521     assert(V && "Trying to get the VPValue of a null Value");
1522     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1523     return Value2VPValue[V];
1524   }
1525 
1526   VPValue *getOrAddVPValue(Value *V) {
1527     assert(V && "Trying to get or add the VPValue of a null Value");
1528     if (!Value2VPValue.count(V))
1529       addVPValue(V);
1530     return getVPValue(V);
1531   }
1532 
1533   /// Return the VPLoopInfo analysis for this VPlan.
1534   VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1535   const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1536 
1537   /// Dump the plan to stderr (for debugging).
1538   void dump() const;
1539 
1540 private:
1541   /// Add to the given dominator tree the header block and every new basic block
1542   /// that was created between it and the latch block, inclusive.
1543   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
1544                                   BasicBlock *LoopPreHeaderBB,
1545                                   BasicBlock *LoopExitBB);
1546 };
1547 
1548 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1549 /// indented and follows the dot format.
1550 class VPlanPrinter {
1551   friend inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan);
1552   friend inline raw_ostream &operator<<(raw_ostream &OS,
1553                                         const struct VPlanIngredient &I);
1554 
1555 private:
1556   raw_ostream &OS;
1557   const VPlan &Plan;
1558   unsigned Depth = 0;
1559   unsigned TabWidth = 2;
1560   std::string Indent;
1561   unsigned BID = 0;
1562   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1563 
1564   VPSlotTracker SlotTracker;
1565 
1566   VPlanPrinter(raw_ostream &O, const VPlan &P)
1567       : OS(O), Plan(P), SlotTracker(&P) {}
1568 
1569   /// Handle indentation.
1570   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1571 
1572   /// Print a given \p Block of the Plan.
1573   void dumpBlock(const VPBlockBase *Block);
1574 
1575   /// Print the information related to the CFG edges going out of a given
1576   /// \p Block, followed by printing the successor blocks themselves.
1577   void dumpEdges(const VPBlockBase *Block);
1578 
1579   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1580   /// its successor blocks.
1581   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1582 
1583   /// Print a given \p Region of the Plan.
1584   void dumpRegion(const VPRegionBlock *Region);
1585 
1586   unsigned getOrCreateBID(const VPBlockBase *Block) {
1587     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1588   }
1589 
1590   const Twine getOrCreateName(const VPBlockBase *Block);
1591 
1592   const Twine getUID(const VPBlockBase *Block);
1593 
1594   /// Print the information related to a CFG edge between two VPBlockBases.
1595   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1596                 const Twine &Label);
1597 
1598   void dump();
1599 
1600   static void printAsIngredient(raw_ostream &O, Value *V);
1601 };
1602 
1603 struct VPlanIngredient {
1604   Value *V;
1605 
1606   VPlanIngredient(Value *V) : V(V) {}
1607 };
1608 
1609 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1610   VPlanPrinter::printAsIngredient(OS, I.V);
1611   return OS;
1612 }
1613 
1614 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
1615   VPlanPrinter Printer(OS, Plan);
1616   Printer.dump();
1617   return OS;
1618 }
1619 
1620 //===----------------------------------------------------------------------===//
1621 // VPlan Utilities
1622 //===----------------------------------------------------------------------===//
1623 
1624 /// Class that provides utilities for VPBlockBases in VPlan.
1625 class VPBlockUtils {
1626 public:
1627   VPBlockUtils() = delete;
1628 
1629   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1630   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1631   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1632   /// has more than one successor, its conditional bit is propagated to \p
1633   /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1634   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1635     assert(NewBlock->getSuccessors().empty() &&
1636            "Can't insert new block with successors.");
1637     // TODO: move successors from BlockPtr to NewBlock when this functionality
1638     // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1639     // already has successors.
1640     BlockPtr->setOneSuccessor(NewBlock);
1641     NewBlock->setPredecessors({BlockPtr});
1642     NewBlock->setParent(BlockPtr->getParent());
1643   }
1644 
1645   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1646   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1647   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1648   /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1649   /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1650   /// must have neither successors nor predecessors.
1651   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1652                                    VPValue *Condition, VPBlockBase *BlockPtr) {
1653     assert(IfTrue->getSuccessors().empty() &&
1654            "Can't insert IfTrue with successors.");
1655     assert(IfFalse->getSuccessors().empty() &&
1656            "Can't insert IfFalse with successors.");
1657     BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
1658     IfTrue->setPredecessors({BlockPtr});
1659     IfFalse->setPredecessors({BlockPtr});
1660     IfTrue->setParent(BlockPtr->getParent());
1661     IfFalse->setParent(BlockPtr->getParent());
1662   }
1663 
1664   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1665   /// the successors of \p From and \p From to the predecessors of \p To. Both
1666   /// VPBlockBases must have the same parent, which can be null. Both
1667   /// VPBlockBases can be already connected to other VPBlockBases.
1668   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1669     assert((From->getParent() == To->getParent()) &&
1670            "Can't connect two block with different parents");
1671     assert(From->getNumSuccessors() < 2 &&
1672            "Blocks can't have more than two successors.");
1673     From->appendSuccessor(To);
1674     To->appendPredecessor(From);
1675   }
1676 
1677   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1678   /// from the successors of \p From and \p From from the predecessors of \p To.
1679   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1680     assert(To && "Successor to disconnect is null.");
1681     From->removeSuccessor(To);
1682     To->removePredecessor(From);
1683   }
1684 
1685   /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1686   static bool isBackEdge(const VPBlockBase *FromBlock,
1687                          const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
1688     assert(FromBlock->getParent() == ToBlock->getParent() &&
1689            FromBlock->getParent() && "Must be in same region");
1690     const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
1691     const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
1692     if (!FromLoop || !ToLoop || FromLoop != ToLoop)
1693       return false;
1694 
1695     // A back-edge is a branch from the loop latch to its header.
1696     return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
1697   }
1698 
1699   /// Returns true if \p Block is a loop latch
1700   static bool blockIsLoopLatch(const VPBlockBase *Block,
1701                                const VPLoopInfo *VPLInfo) {
1702     if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
1703       return ParentVPL->isLoopLatch(Block);
1704 
1705     return false;
1706   }
1707 
1708   /// Count and return the number of succesors of \p PredBlock excluding any
1709   /// backedges.
1710   static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
1711                                       VPLoopInfo *VPLI) {
1712     unsigned Count = 0;
1713     for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
1714       if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
1715         Count++;
1716     }
1717     return Count;
1718   }
1719 };
1720 
1721 class VPInterleavedAccessInfo {
1722 private:
1723   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1724       InterleaveGroupMap;
1725 
1726   /// Type for mapping of instruction based interleave groups to VPInstruction
1727   /// interleave groups
1728   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1729                              InterleaveGroup<VPInstruction> *>;
1730 
1731   /// Recursively \p Region and populate VPlan based interleave groups based on
1732   /// \p IAI.
1733   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1734                    InterleavedAccessInfo &IAI);
1735   /// Recursively traverse \p Block and populate VPlan based interleave groups
1736   /// based on \p IAI.
1737   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1738                   InterleavedAccessInfo &IAI);
1739 
1740 public:
1741   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1742 
1743   ~VPInterleavedAccessInfo() {
1744     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1745     // Avoid releasing a pointer twice.
1746     for (auto &I : InterleaveGroupMap)
1747       DelSet.insert(I.second);
1748     for (auto *Ptr : DelSet)
1749       delete Ptr;
1750   }
1751 
1752   /// Get the interleave group that \p Instr belongs to.
1753   ///
1754   /// \returns nullptr if doesn't have such group.
1755   InterleaveGroup<VPInstruction> *
1756   getInterleaveGroup(VPInstruction *Instr) const {
1757     if (InterleaveGroupMap.count(Instr))
1758       return InterleaveGroupMap.find(Instr)->second;
1759     return nullptr;
1760   }
1761 };
1762 
1763 /// Class that maps (parts of) an existing VPlan to trees of combined
1764 /// VPInstructions.
1765 class VPlanSlp {
1766 private:
1767   enum class OpMode { Failed, Load, Opcode };
1768 
1769   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
1770   /// DenseMap keys.
1771   struct BundleDenseMapInfo {
1772     static SmallVector<VPValue *, 4> getEmptyKey() {
1773       return {reinterpret_cast<VPValue *>(-1)};
1774     }
1775 
1776     static SmallVector<VPValue *, 4> getTombstoneKey() {
1777       return {reinterpret_cast<VPValue *>(-2)};
1778     }
1779 
1780     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
1781       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1782     }
1783 
1784     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
1785                         const SmallVector<VPValue *, 4> &RHS) {
1786       return LHS == RHS;
1787     }
1788   };
1789 
1790   /// Mapping of values in the original VPlan to a combined VPInstruction.
1791   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
1792       BundleToCombined;
1793 
1794   VPInterleavedAccessInfo &IAI;
1795 
1796   /// Basic block to operate on. For now, only instructions in a single BB are
1797   /// considered.
1798   const VPBasicBlock &BB;
1799 
1800   /// Indicates whether we managed to combine all visited instructions or not.
1801   bool CompletelySLP = true;
1802 
1803   /// Width of the widest combined bundle in bits.
1804   unsigned WidestBundleBits = 0;
1805 
1806   using MultiNodeOpTy =
1807       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
1808 
1809   // Input operand bundles for the current multi node. Each multi node operand
1810   // bundle contains values not matching the multi node's opcode. They will
1811   // be reordered in reorderMultiNodeOps, once we completed building a
1812   // multi node.
1813   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
1814 
1815   /// Indicates whether we are building a multi node currently.
1816   bool MultiNodeActive = false;
1817 
1818   /// Check if we can vectorize Operands together.
1819   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
1820 
1821   /// Add combined instruction \p New for the bundle \p Operands.
1822   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
1823 
1824   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
1825   VPInstruction *markFailed();
1826 
1827   /// Reorder operands in the multi node to maximize sequential memory access
1828   /// and commutative operations.
1829   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
1830 
1831   /// Choose the best candidate to use for the lane after \p Last. The set of
1832   /// candidates to choose from are values with an opcode matching \p Last's
1833   /// or loads consecutive to \p Last.
1834   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
1835                                        SmallPtrSetImpl<VPValue *> &Candidates,
1836                                        VPInterleavedAccessInfo &IAI);
1837 
1838   /// Print bundle \p Values to dbgs().
1839   void dumpBundle(ArrayRef<VPValue *> Values);
1840 
1841 public:
1842   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
1843 
1844   ~VPlanSlp() {
1845     for (auto &KV : BundleToCombined)
1846       delete KV.second;
1847   }
1848 
1849   /// Tries to build an SLP tree rooted at \p Operands and returns a
1850   /// VPInstruction combining \p Operands, if they can be combined.
1851   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
1852 
1853   /// Return the width of the widest combined bundle in bits.
1854   unsigned getWidestBundleBits() const { return WidestBundleBits; }
1855 
1856   /// Return true if all visited instruction can be combined.
1857   bool isCompletelySLP() const { return CompletelySLP; }
1858 };
1859 } // end namespace llvm
1860 
1861 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
1862