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     VPWidenCallSC,
613     VPWidenGEPSC,
614     VPWidenIntOrFpInductionSC,
615     VPWidenMemoryInstructionSC,
616     VPWidenPHISC,
617     VPWidenSC,
618   };
619 
620   VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
621   virtual ~VPRecipeBase() = default;
622 
623   /// \return an ID for the concrete type of this object.
624   /// This is used to implement the classof checks. This should not be used
625   /// for any other purpose, as the values may change as LLVM evolves.
626   unsigned getVPRecipeID() const { return SubclassID; }
627 
628   /// \return the VPBasicBlock which this VPRecipe belongs to.
629   VPBasicBlock *getParent() { return Parent; }
630   const VPBasicBlock *getParent() const { return Parent; }
631 
632   /// The method which generates the output IR instructions that correspond to
633   /// this VPRecipe, thereby "executing" the VPlan.
634   virtual void execute(struct VPTransformState &State) = 0;
635 
636   /// Each recipe prints itself.
637   void print(raw_ostream &O, const Twine &Indent);
638   virtual void print(raw_ostream &O, const Twine &Indent,
639                      VPSlotTracker &SlotTracker) const = 0;
640 
641   /// Insert an unlinked recipe into a basic block immediately before
642   /// the specified recipe.
643   void insertBefore(VPRecipeBase *InsertPos);
644 
645   /// Insert an unlinked Recipe into a basic block immediately after
646   /// the specified Recipe.
647   void insertAfter(VPRecipeBase *InsertPos);
648 
649   /// Unlink this recipe from its current VPBasicBlock and insert it into
650   /// the VPBasicBlock that MovePos lives in, right after MovePos.
651   void moveAfter(VPRecipeBase *MovePos);
652 
653   /// This method unlinks 'this' from the containing basic block, but does not
654   /// delete it.
655   void removeFromParent();
656 
657   /// This method unlinks 'this' from the containing basic block and deletes it.
658   ///
659   /// \returns an iterator pointing to the element after the erased one
660   iplist<VPRecipeBase>::iterator eraseFromParent();
661 };
662 
663 /// This is a concrete Recipe that models a single VPlan-level instruction.
664 /// While as any Recipe it may generate a sequence of IR instructions when
665 /// executed, these instructions would always form a single-def expression as
666 /// the VPInstruction is also a single def-use vertex.
667 class VPInstruction : public VPUser, public VPRecipeBase {
668   friend class VPlanSlp;
669 
670 public:
671   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
672   enum {
673     Not = Instruction::OtherOpsEnd + 1,
674     ICmpULE,
675     SLPLoad,
676     SLPStore,
677   };
678 
679 private:
680   typedef unsigned char OpcodeTy;
681   OpcodeTy Opcode;
682 
683   /// Utility method serving execute(): generates a single instance of the
684   /// modeled instruction.
685   void generateInstruction(VPTransformState &State, unsigned Part);
686 
687 protected:
688   Instruction *getUnderlyingInstr() {
689     return cast_or_null<Instruction>(getUnderlyingValue());
690   }
691 
692   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
693 
694 public:
695   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
696       : VPUser(VPValue::VPInstructionSC, Operands),
697         VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
698 
699   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
700       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
701 
702   /// Method to support type inquiry through isa, cast, and dyn_cast.
703   static inline bool classof(const VPValue *V) {
704     return V->getVPValueID() == VPValue::VPInstructionSC;
705   }
706 
707   VPInstruction *clone() const {
708     SmallVector<VPValue *, 2> Operands(operands());
709     return new VPInstruction(Opcode, Operands);
710   }
711 
712   /// Method to support type inquiry through isa, cast, and dyn_cast.
713   static inline bool classof(const VPRecipeBase *R) {
714     return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
715   }
716 
717   unsigned getOpcode() const { return Opcode; }
718 
719   /// Generate the instruction.
720   /// TODO: We currently execute only per-part unless a specific instance is
721   /// provided.
722   void execute(VPTransformState &State) override;
723 
724   /// Print the Recipe.
725   void print(raw_ostream &O, const Twine &Indent,
726              VPSlotTracker &SlotTracker) const override;
727 
728   /// Print the VPInstruction.
729   void print(raw_ostream &O) const;
730   void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
731 
732   /// Return true if this instruction may modify memory.
733   bool mayWriteToMemory() const {
734     // TODO: we can use attributes of the called function to rule out memory
735     //       modifications.
736     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
737            Opcode == Instruction::Invoke || Opcode == SLPStore;
738   }
739 
740   bool hasResult() const {
741     // CallInst may or may not have a result, depending on the called function.
742     // Conservatively return calls have results for now.
743     switch (getOpcode()) {
744     case Instruction::Ret:
745     case Instruction::Br:
746     case Instruction::Store:
747     case Instruction::Switch:
748     case Instruction::IndirectBr:
749     case Instruction::Resume:
750     case Instruction::CatchRet:
751     case Instruction::Unreachable:
752     case Instruction::Fence:
753     case Instruction::AtomicRMW:
754       return false;
755     default:
756       return true;
757     }
758   }
759 };
760 
761 /// VPWidenRecipe is a recipe for producing a copy of vector type its
762 /// ingredient. This recipe covers most of the traditional vectorization cases
763 /// where each ingredient transforms into a vectorized version of itself.
764 class VPWidenRecipe : public VPRecipeBase {
765 private:
766   /// Hold the instruction to be widened.
767   Instruction &Ingredient;
768 
769 public:
770   VPWidenRecipe(Instruction &I) : VPRecipeBase(VPWidenSC), Ingredient(I) {}
771 
772   ~VPWidenRecipe() override = default;
773 
774   /// Method to support type inquiry through isa, cast, and dyn_cast.
775   static inline bool classof(const VPRecipeBase *V) {
776     return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
777   }
778 
779   /// Produce widened copies of all Ingredients.
780   void execute(VPTransformState &State) override;
781 
782   /// Print the recipe.
783   void print(raw_ostream &O, const Twine &Indent,
784              VPSlotTracker &SlotTracker) const override;
785 };
786 
787 /// A recipe for widening Call instructions.
788 class VPWidenCallRecipe : public VPRecipeBase {
789 private:
790   /// Hold the call to be widened.
791   CallInst &Ingredient;
792 
793 public:
794   VPWidenCallRecipe(CallInst &I) : VPRecipeBase(VPWidenCallSC), Ingredient(I) {}
795 
796   ~VPWidenCallRecipe() override = default;
797 
798   /// Method to support type inquiry through isa, cast, and dyn_cast.
799   static inline bool classof(const VPRecipeBase *V) {
800     return V->getVPRecipeID() == VPRecipeBase::VPWidenCallSC;
801   }
802 
803   /// Produce a widened version of the call instruction.
804   void execute(VPTransformState &State) override;
805 
806   /// Print the recipe.
807   void print(raw_ostream &O, const Twine &Indent,
808              VPSlotTracker &SlotTracker) const override;
809 };
810 
811 /// A recipe for handling GEP instructions.
812 class VPWidenGEPRecipe : public VPRecipeBase {
813 private:
814   GetElementPtrInst *GEP;
815   bool IsPtrLoopInvariant;
816   SmallBitVector IsIndexLoopInvariant;
817 
818 public:
819   VPWidenGEPRecipe(GetElementPtrInst *GEP, Loop *OrigLoop)
820       : VPRecipeBase(VPWidenGEPSC), GEP(GEP),
821         IsIndexLoopInvariant(GEP->getNumIndices(), false) {
822     IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
823     for (auto Index : enumerate(GEP->indices()))
824       IsIndexLoopInvariant[Index.index()] =
825           OrigLoop->isLoopInvariant(Index.value().get());
826   }
827   ~VPWidenGEPRecipe() override = default;
828 
829   /// Method to support type inquiry through isa, cast, and dyn_cast.
830   static inline bool classof(const VPRecipeBase *V) {
831     return V->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC;
832   }
833 
834   /// Generate the gep nodes.
835   void execute(VPTransformState &State) override;
836 
837   /// Print the recipe.
838   void print(raw_ostream &O, const Twine &Indent,
839              VPSlotTracker &SlotTracker) const override;
840 };
841 
842 /// A recipe for handling phi nodes of integer and floating-point inductions,
843 /// producing their vector and scalar values.
844 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
845 private:
846   PHINode *IV;
847   TruncInst *Trunc;
848 
849 public:
850   VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
851       : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
852   ~VPWidenIntOrFpInductionRecipe() override = default;
853 
854   /// Method to support type inquiry through isa, cast, and dyn_cast.
855   static inline bool classof(const VPRecipeBase *V) {
856     return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
857   }
858 
859   /// Generate the vectorized and scalarized versions of the phi node as
860   /// needed by their users.
861   void execute(VPTransformState &State) override;
862 
863   /// Print the recipe.
864   void print(raw_ostream &O, const Twine &Indent,
865              VPSlotTracker &SlotTracker) const override;
866 };
867 
868 /// A recipe for handling all phi nodes except for integer and FP inductions.
869 class VPWidenPHIRecipe : public VPRecipeBase {
870 private:
871   PHINode *Phi;
872 
873 public:
874   VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
875   ~VPWidenPHIRecipe() override = default;
876 
877   /// Method to support type inquiry through isa, cast, and dyn_cast.
878   static inline bool classof(const VPRecipeBase *V) {
879     return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
880   }
881 
882   /// Generate the phi/select nodes.
883   void execute(VPTransformState &State) override;
884 
885   /// Print the recipe.
886   void print(raw_ostream &O, const Twine &Indent,
887              VPSlotTracker &SlotTracker) const override;
888 };
889 
890 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
891 /// instructions.
892 class VPBlendRecipe : public VPRecipeBase {
893 private:
894   PHINode *Phi;
895 
896   /// The blend operation is a User of a mask, if not null.
897   std::unique_ptr<VPUser> User;
898 
899 public:
900   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
901       : VPRecipeBase(VPBlendSC), Phi(Phi) {
902     assert((Phi->getNumIncomingValues() == 1 ||
903             Phi->getNumIncomingValues() == Masks.size()) &&
904            "Expected the same number of incoming values and masks");
905     if (!Masks.empty())
906       User.reset(new VPUser(Masks));
907   }
908 
909   /// Method to support type inquiry through isa, cast, and dyn_cast.
910   static inline bool classof(const VPRecipeBase *V) {
911     return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
912   }
913 
914   /// Generate the phi/select nodes.
915   void execute(VPTransformState &State) override;
916 
917   /// Print the recipe.
918   void print(raw_ostream &O, const Twine &Indent,
919              VPSlotTracker &SlotTracker) const override;
920 };
921 
922 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
923 /// or stores into one wide load/store and shuffles.
924 class VPInterleaveRecipe : public VPRecipeBase {
925 private:
926   const InterleaveGroup<Instruction> *IG;
927   VPUser User;
928 
929 public:
930   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr,
931                      VPValue *Mask)
932       : VPRecipeBase(VPInterleaveSC), IG(IG), User({Addr}) {
933     if (Mask)
934       User.addOperand(Mask);
935   }
936   ~VPInterleaveRecipe() override = default;
937 
938   /// Method to support type inquiry through isa, cast, and dyn_cast.
939   static inline bool classof(const VPRecipeBase *V) {
940     return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
941   }
942 
943   /// Return the address accessed by this recipe.
944   VPValue *getAddr() const {
945     return User.getOperand(0); // Address is the 1st, mandatory operand.
946   }
947 
948   /// Return the mask used by this recipe. Note that a full mask is represented
949   /// by a nullptr.
950   VPValue *getMask() const {
951     // Mask is optional and therefore the last, currently 2nd operand.
952     return User.getNumOperands() == 2 ? User.getOperand(1) : nullptr;
953   }
954 
955   /// Generate the wide load or store, and shuffles.
956   void execute(VPTransformState &State) override;
957 
958   /// Print the recipe.
959   void print(raw_ostream &O, const Twine &Indent,
960              VPSlotTracker &SlotTracker) const override;
961 
962   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
963 };
964 
965 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
966 /// copies of the original scalar type, one per lane, instead of producing a
967 /// single copy of widened type for all lanes. If the instruction is known to be
968 /// uniform only one copy, per lane zero, will be generated.
969 class VPReplicateRecipe : public VPRecipeBase {
970 private:
971   /// The instruction being replicated.
972   Instruction *Ingredient;
973 
974   /// Indicator if only a single replica per lane is needed.
975   bool IsUniform;
976 
977   /// Indicator if the replicas are also predicated.
978   bool IsPredicated;
979 
980   /// Indicator if the scalar values should also be packed into a vector.
981   bool AlsoPack;
982 
983 public:
984   VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
985       : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
986         IsPredicated(IsPredicated) {
987     // Retain the previous behavior of predicateInstructions(), where an
988     // insert-element of a predicated instruction got hoisted into the
989     // predicated basic block iff it was its only user. This is achieved by
990     // having predicated instructions also pack their values into a vector by
991     // default unless they have a replicated user which uses their scalar value.
992     AlsoPack = IsPredicated && !I->use_empty();
993   }
994 
995   ~VPReplicateRecipe() override = default;
996 
997   /// Method to support type inquiry through isa, cast, and dyn_cast.
998   static inline bool classof(const VPRecipeBase *V) {
999     return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
1000   }
1001 
1002   /// Generate replicas of the desired Ingredient. Replicas will be generated
1003   /// for all parts and lanes unless a specific part and lane are specified in
1004   /// the \p State.
1005   void execute(VPTransformState &State) override;
1006 
1007   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
1008 
1009   /// Print the recipe.
1010   void print(raw_ostream &O, const Twine &Indent,
1011              VPSlotTracker &SlotTracker) const override;
1012 };
1013 
1014 /// A recipe for generating conditional branches on the bits of a mask.
1015 class VPBranchOnMaskRecipe : public VPRecipeBase {
1016 private:
1017   std::unique_ptr<VPUser> User;
1018 
1019 public:
1020   VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
1021     if (BlockInMask) // nullptr means all-one mask.
1022       User.reset(new VPUser({BlockInMask}));
1023   }
1024 
1025   /// Method to support type inquiry through isa, cast, and dyn_cast.
1026   static inline bool classof(const VPRecipeBase *V) {
1027     return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
1028   }
1029 
1030   /// Generate the extraction of the appropriate bit from the block mask and the
1031   /// conditional branch.
1032   void execute(VPTransformState &State) override;
1033 
1034   /// Print the recipe.
1035   void print(raw_ostream &O, const Twine &Indent,
1036              VPSlotTracker &SlotTracker) const override {
1037     O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
1038     if (User)
1039       User->getOperand(0)->print(O, SlotTracker);
1040     else
1041       O << " All-One";
1042     O << "\\l\"";
1043   }
1044 };
1045 
1046 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1047 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1048 /// order to merge values that are set under such a branch and feed their uses.
1049 /// The phi nodes can be scalar or vector depending on the users of the value.
1050 /// This recipe works in concert with VPBranchOnMaskRecipe.
1051 class VPPredInstPHIRecipe : public VPRecipeBase {
1052 private:
1053   Instruction *PredInst;
1054 
1055 public:
1056   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1057   /// nodes after merging back from a Branch-on-Mask.
1058   VPPredInstPHIRecipe(Instruction *PredInst)
1059       : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
1060   ~VPPredInstPHIRecipe() override = default;
1061 
1062   /// Method to support type inquiry through isa, cast, and dyn_cast.
1063   static inline bool classof(const VPRecipeBase *V) {
1064     return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
1065   }
1066 
1067   /// Generates phi nodes for live-outs as needed to retain SSA form.
1068   void execute(VPTransformState &State) override;
1069 
1070   /// Print the recipe.
1071   void print(raw_ostream &O, const Twine &Indent,
1072              VPSlotTracker &SlotTracker) const override;
1073 };
1074 
1075 /// A Recipe for widening load/store operations.
1076 /// The recipe uses the following VPValues:
1077 /// - For load: Address, optional mask
1078 /// - For store: Address, stored value, optional mask
1079 /// TODO: We currently execute only per-part unless a specific instance is
1080 /// provided.
1081 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
1082 private:
1083   Instruction &Instr;
1084   VPUser User;
1085 
1086   void setMask(VPValue *Mask) {
1087     if (!Mask)
1088       return;
1089     User.addOperand(Mask);
1090   }
1091 
1092   bool isMasked() const {
1093     return (isa<LoadInst>(Instr) && User.getNumOperands() == 2) ||
1094            (isa<StoreInst>(Instr) && User.getNumOperands() == 3);
1095   }
1096 
1097 public:
1098   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask)
1099       : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Load), User({Addr}) {
1100     setMask(Mask);
1101   }
1102 
1103   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1104                                  VPValue *StoredValue, VPValue *Mask)
1105       : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Store),
1106         User({Addr, StoredValue}) {
1107     setMask(Mask);
1108   }
1109 
1110   /// Method to support type inquiry through isa, cast, and dyn_cast.
1111   static inline bool classof(const VPRecipeBase *V) {
1112     return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1113   }
1114 
1115   /// Return the address accessed by this recipe.
1116   VPValue *getAddr() const {
1117     return User.getOperand(0); // Address is the 1st, mandatory operand.
1118   }
1119 
1120   /// Return the mask used by this recipe. Note that a full mask is represented
1121   /// by a nullptr.
1122   VPValue *getMask() const {
1123     // Mask is optional and therefore the last operand.
1124     return isMasked() ? User.getOperand(User.getNumOperands() - 1) : nullptr;
1125   }
1126 
1127   /// Return the address accessed by this recipe.
1128   VPValue *getStoredValue() const {
1129     assert(isa<StoreInst>(Instr) &&
1130            "Stored value only available for store instructions");
1131     return User.getOperand(1); // Stored value is the 2nd, mandatory operand.
1132   }
1133 
1134   /// Generate the wide load/store.
1135   void execute(VPTransformState &State) override;
1136 
1137   /// Print the recipe.
1138   void print(raw_ostream &O, const Twine &Indent,
1139              VPSlotTracker &SlotTracker) const override;
1140 };
1141 
1142 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1143 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1144 /// output IR instructions.
1145 class VPBasicBlock : public VPBlockBase {
1146 public:
1147   using RecipeListTy = iplist<VPRecipeBase>;
1148 
1149 private:
1150   /// The VPRecipes held in the order of output instructions to generate.
1151   RecipeListTy Recipes;
1152 
1153 public:
1154   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1155       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1156     if (Recipe)
1157       appendRecipe(Recipe);
1158   }
1159 
1160   ~VPBasicBlock() override { Recipes.clear(); }
1161 
1162   /// Instruction iterators...
1163   using iterator = RecipeListTy::iterator;
1164   using const_iterator = RecipeListTy::const_iterator;
1165   using reverse_iterator = RecipeListTy::reverse_iterator;
1166   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1167 
1168   //===--------------------------------------------------------------------===//
1169   /// Recipe iterator methods
1170   ///
1171   inline iterator begin() { return Recipes.begin(); }
1172   inline const_iterator begin() const { return Recipes.begin(); }
1173   inline iterator end() { return Recipes.end(); }
1174   inline const_iterator end() const { return Recipes.end(); }
1175 
1176   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1177   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1178   inline reverse_iterator rend() { return Recipes.rend(); }
1179   inline const_reverse_iterator rend() const { return Recipes.rend(); }
1180 
1181   inline size_t size() const { return Recipes.size(); }
1182   inline bool empty() const { return Recipes.empty(); }
1183   inline const VPRecipeBase &front() const { return Recipes.front(); }
1184   inline VPRecipeBase &front() { return Recipes.front(); }
1185   inline const VPRecipeBase &back() const { return Recipes.back(); }
1186   inline VPRecipeBase &back() { return Recipes.back(); }
1187 
1188   /// Returns a reference to the list of recipes.
1189   RecipeListTy &getRecipeList() { return Recipes; }
1190 
1191   /// Returns a pointer to a member of the recipe list.
1192   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1193     return &VPBasicBlock::Recipes;
1194   }
1195 
1196   /// Method to support type inquiry through isa, cast, and dyn_cast.
1197   static inline bool classof(const VPBlockBase *V) {
1198     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1199   }
1200 
1201   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
1202     assert(Recipe && "No recipe to append.");
1203     assert(!Recipe->Parent && "Recipe already in VPlan");
1204     Recipe->Parent = this;
1205     Recipes.insert(InsertPt, Recipe);
1206   }
1207 
1208   /// Augment the existing recipes of a VPBasicBlock with an additional
1209   /// \p Recipe as the last recipe.
1210   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1211 
1212   /// The method which generates the output IR instructions that correspond to
1213   /// this VPBasicBlock, thereby "executing" the VPlan.
1214   void execute(struct VPTransformState *State) override;
1215 
1216 private:
1217   /// Create an IR BasicBlock to hold the output instructions generated by this
1218   /// VPBasicBlock, and return it. Update the CFGState accordingly.
1219   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1220 };
1221 
1222 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1223 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1224 /// A VPRegionBlock may indicate that its contents are to be replicated several
1225 /// times. This is designed to support predicated scalarization, in which a
1226 /// scalar if-then code structure needs to be generated VF * UF times. Having
1227 /// this replication indicator helps to keep a single model for multiple
1228 /// candidate VF's. The actual replication takes place only once the desired VF
1229 /// and UF have been determined.
1230 class VPRegionBlock : public VPBlockBase {
1231 private:
1232   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1233   VPBlockBase *Entry;
1234 
1235   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1236   VPBlockBase *Exit;
1237 
1238   /// An indicator whether this region is to generate multiple replicated
1239   /// instances of output IR corresponding to its VPBlockBases.
1240   bool IsReplicator;
1241 
1242 public:
1243   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1244                 const std::string &Name = "", bool IsReplicator = false)
1245       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1246         IsReplicator(IsReplicator) {
1247     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1248     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1249     Entry->setParent(this);
1250     Exit->setParent(this);
1251   }
1252   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1253       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1254         IsReplicator(IsReplicator) {}
1255 
1256   ~VPRegionBlock() override {
1257     if (Entry)
1258       deleteCFG(Entry);
1259   }
1260 
1261   /// Method to support type inquiry through isa, cast, and dyn_cast.
1262   static inline bool classof(const VPBlockBase *V) {
1263     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1264   }
1265 
1266   const VPBlockBase *getEntry() const { return Entry; }
1267   VPBlockBase *getEntry() { return Entry; }
1268 
1269   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1270   /// EntryBlock must have no predecessors.
1271   void setEntry(VPBlockBase *EntryBlock) {
1272     assert(EntryBlock->getPredecessors().empty() &&
1273            "Entry block cannot have predecessors.");
1274     Entry = EntryBlock;
1275     EntryBlock->setParent(this);
1276   }
1277 
1278   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1279   // specific interface of llvm::Function, instead of using
1280   // GraphTraints::getEntryNode. We should add a new template parameter to
1281   // DominatorTreeBase representing the Graph type.
1282   VPBlockBase &front() const { return *Entry; }
1283 
1284   const VPBlockBase *getExit() const { return Exit; }
1285   VPBlockBase *getExit() { return Exit; }
1286 
1287   /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1288   /// ExitBlock must have no successors.
1289   void setExit(VPBlockBase *ExitBlock) {
1290     assert(ExitBlock->getSuccessors().empty() &&
1291            "Exit block cannot have successors.");
1292     Exit = ExitBlock;
1293     ExitBlock->setParent(this);
1294   }
1295 
1296   /// An indicator whether this region is to generate multiple replicated
1297   /// instances of output IR corresponding to its VPBlockBases.
1298   bool isReplicator() const { return IsReplicator; }
1299 
1300   /// The method which generates the output IR instructions that correspond to
1301   /// this VPRegionBlock, thereby "executing" the VPlan.
1302   void execute(struct VPTransformState *State) override;
1303 };
1304 
1305 //===----------------------------------------------------------------------===//
1306 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
1307 //===----------------------------------------------------------------------===//
1308 
1309 // The following set of template specializations implement GraphTraits to treat
1310 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1311 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1312 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1313 // successors/predecessors but not to the blocks inside the region.
1314 
1315 template <> struct GraphTraits<VPBlockBase *> {
1316   using NodeRef = VPBlockBase *;
1317   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1318 
1319   static NodeRef getEntryNode(NodeRef N) { return N; }
1320 
1321   static inline ChildIteratorType child_begin(NodeRef N) {
1322     return N->getSuccessors().begin();
1323   }
1324 
1325   static inline ChildIteratorType child_end(NodeRef N) {
1326     return N->getSuccessors().end();
1327   }
1328 };
1329 
1330 template <> struct GraphTraits<const VPBlockBase *> {
1331   using NodeRef = const VPBlockBase *;
1332   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1333 
1334   static NodeRef getEntryNode(NodeRef N) { return N; }
1335 
1336   static inline ChildIteratorType child_begin(NodeRef N) {
1337     return N->getSuccessors().begin();
1338   }
1339 
1340   static inline ChildIteratorType child_end(NodeRef N) {
1341     return N->getSuccessors().end();
1342   }
1343 };
1344 
1345 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1346 // of successors for the inverse traversal.
1347 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1348   using NodeRef = VPBlockBase *;
1349   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1350 
1351   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1352 
1353   static inline ChildIteratorType child_begin(NodeRef N) {
1354     return N->getPredecessors().begin();
1355   }
1356 
1357   static inline ChildIteratorType child_end(NodeRef N) {
1358     return N->getPredecessors().end();
1359   }
1360 };
1361 
1362 // The following set of template specializations implement GraphTraits to
1363 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1364 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1365 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1366 // there won't be automatic recursion into other VPBlockBases that turn to be
1367 // VPRegionBlocks.
1368 
1369 template <>
1370 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1371   using GraphRef = VPRegionBlock *;
1372   using nodes_iterator = df_iterator<NodeRef>;
1373 
1374   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1375 
1376   static nodes_iterator nodes_begin(GraphRef N) {
1377     return nodes_iterator::begin(N->getEntry());
1378   }
1379 
1380   static nodes_iterator nodes_end(GraphRef N) {
1381     // df_iterator::end() returns an empty iterator so the node used doesn't
1382     // matter.
1383     return nodes_iterator::end(N);
1384   }
1385 };
1386 
1387 template <>
1388 struct GraphTraits<const VPRegionBlock *>
1389     : public GraphTraits<const VPBlockBase *> {
1390   using GraphRef = const VPRegionBlock *;
1391   using nodes_iterator = df_iterator<NodeRef>;
1392 
1393   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1394 
1395   static nodes_iterator nodes_begin(GraphRef N) {
1396     return nodes_iterator::begin(N->getEntry());
1397   }
1398 
1399   static nodes_iterator nodes_end(GraphRef N) {
1400     // df_iterator::end() returns an empty iterator so the node used doesn't
1401     // matter.
1402     return nodes_iterator::end(N);
1403   }
1404 };
1405 
1406 template <>
1407 struct GraphTraits<Inverse<VPRegionBlock *>>
1408     : public GraphTraits<Inverse<VPBlockBase *>> {
1409   using GraphRef = VPRegionBlock *;
1410   using nodes_iterator = df_iterator<NodeRef>;
1411 
1412   static NodeRef getEntryNode(Inverse<GraphRef> N) {
1413     return N.Graph->getExit();
1414   }
1415 
1416   static nodes_iterator nodes_begin(GraphRef N) {
1417     return nodes_iterator::begin(N->getExit());
1418   }
1419 
1420   static nodes_iterator nodes_end(GraphRef N) {
1421     // df_iterator::end() returns an empty iterator so the node used doesn't
1422     // matter.
1423     return nodes_iterator::end(N);
1424   }
1425 };
1426 
1427 class VPSlotTracker;
1428 /// VPlan models a candidate for vectorization, encoding various decisions take
1429 /// to produce efficient output IR, including which branches, basic-blocks and
1430 /// output IR instructions to generate, and their cost. VPlan holds a
1431 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1432 /// VPBlock.
1433 class VPlan {
1434   friend class VPlanPrinter;
1435   friend class VPSlotTracker;
1436 
1437 private:
1438   /// Hold the single entry to the Hierarchical CFG of the VPlan.
1439   VPBlockBase *Entry;
1440 
1441   /// Holds the VFs applicable to this VPlan.
1442   SmallSet<unsigned, 2> VFs;
1443 
1444   /// Holds the name of the VPlan, for printing.
1445   std::string Name;
1446 
1447   /// Holds all the external definitions created for this VPlan.
1448   // TODO: Introduce a specific representation for external definitions in
1449   // VPlan. External definitions must be immutable and hold a pointer to its
1450   // underlying IR that will be used to implement its structural comparison
1451   // (operators '==' and '<').
1452   SmallPtrSet<VPValue *, 16> VPExternalDefs;
1453 
1454   /// Represents the backedge taken count of the original loop, for folding
1455   /// the tail.
1456   VPValue *BackedgeTakenCount = nullptr;
1457 
1458   /// Holds a mapping between Values and their corresponding VPValue inside
1459   /// VPlan.
1460   Value2VPValueTy Value2VPValue;
1461 
1462   /// Holds the VPLoopInfo analysis for this VPlan.
1463   VPLoopInfo VPLInfo;
1464 
1465   /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1466   SmallVector<VPValue *, 4> VPCBVs;
1467 
1468 public:
1469   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
1470     if (Entry)
1471       Entry->setPlan(this);
1472   }
1473 
1474   ~VPlan() {
1475     if (Entry)
1476       VPBlockBase::deleteCFG(Entry);
1477     for (auto &MapEntry : Value2VPValue)
1478       if (MapEntry.second != BackedgeTakenCount)
1479         delete MapEntry.second;
1480     if (BackedgeTakenCount)
1481       delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not.
1482     for (VPValue *Def : VPExternalDefs)
1483       delete Def;
1484     for (VPValue *CBV : VPCBVs)
1485       delete CBV;
1486   }
1487 
1488   /// Generate the IR code for this VPlan.
1489   void execute(struct VPTransformState *State);
1490 
1491   VPBlockBase *getEntry() { return Entry; }
1492   const VPBlockBase *getEntry() const { return Entry; }
1493 
1494   VPBlockBase *setEntry(VPBlockBase *Block) {
1495     Entry = Block;
1496     Block->setPlan(this);
1497     return Entry;
1498   }
1499 
1500   /// The backedge taken count of the original loop.
1501   VPValue *getOrCreateBackedgeTakenCount() {
1502     if (!BackedgeTakenCount)
1503       BackedgeTakenCount = new VPValue();
1504     return BackedgeTakenCount;
1505   }
1506 
1507   void addVF(unsigned VF) { VFs.insert(VF); }
1508 
1509   bool hasVF(unsigned VF) { return VFs.count(VF); }
1510 
1511   const std::string &getName() const { return Name; }
1512 
1513   void setName(const Twine &newName) { Name = newName.str(); }
1514 
1515   /// Add \p VPVal to the pool of external definitions if it's not already
1516   /// in the pool.
1517   void addExternalDef(VPValue *VPVal) {
1518     VPExternalDefs.insert(VPVal);
1519   }
1520 
1521   /// Add \p CBV to the vector of condition bit values.
1522   void addCBV(VPValue *CBV) {
1523     VPCBVs.push_back(CBV);
1524   }
1525 
1526   void addVPValue(Value *V) {
1527     assert(V && "Trying to add a null Value to VPlan");
1528     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1529     Value2VPValue[V] = new VPValue(V);
1530   }
1531 
1532   VPValue *getVPValue(Value *V) {
1533     assert(V && "Trying to get the VPValue of a null Value");
1534     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1535     return Value2VPValue[V];
1536   }
1537 
1538   VPValue *getOrAddVPValue(Value *V) {
1539     assert(V && "Trying to get or add the VPValue of a null Value");
1540     if (!Value2VPValue.count(V))
1541       addVPValue(V);
1542     return getVPValue(V);
1543   }
1544 
1545   /// Return the VPLoopInfo analysis for this VPlan.
1546   VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1547   const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1548 
1549   /// Dump the plan to stderr (for debugging).
1550   void dump() const;
1551 
1552 private:
1553   /// Add to the given dominator tree the header block and every new basic block
1554   /// that was created between it and the latch block, inclusive.
1555   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
1556                                   BasicBlock *LoopPreHeaderBB,
1557                                   BasicBlock *LoopExitBB);
1558 };
1559 
1560 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1561 /// indented and follows the dot format.
1562 class VPlanPrinter {
1563   friend inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan);
1564   friend inline raw_ostream &operator<<(raw_ostream &OS,
1565                                         const struct VPlanIngredient &I);
1566 
1567 private:
1568   raw_ostream &OS;
1569   const VPlan &Plan;
1570   unsigned Depth = 0;
1571   unsigned TabWidth = 2;
1572   std::string Indent;
1573   unsigned BID = 0;
1574   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1575 
1576   VPSlotTracker SlotTracker;
1577 
1578   VPlanPrinter(raw_ostream &O, const VPlan &P)
1579       : OS(O), Plan(P), SlotTracker(&P) {}
1580 
1581   /// Handle indentation.
1582   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1583 
1584   /// Print a given \p Block of the Plan.
1585   void dumpBlock(const VPBlockBase *Block);
1586 
1587   /// Print the information related to the CFG edges going out of a given
1588   /// \p Block, followed by printing the successor blocks themselves.
1589   void dumpEdges(const VPBlockBase *Block);
1590 
1591   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1592   /// its successor blocks.
1593   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1594 
1595   /// Print a given \p Region of the Plan.
1596   void dumpRegion(const VPRegionBlock *Region);
1597 
1598   unsigned getOrCreateBID(const VPBlockBase *Block) {
1599     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1600   }
1601 
1602   const Twine getOrCreateName(const VPBlockBase *Block);
1603 
1604   const Twine getUID(const VPBlockBase *Block);
1605 
1606   /// Print the information related to a CFG edge between two VPBlockBases.
1607   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1608                 const Twine &Label);
1609 
1610   void dump();
1611 
1612   static void printAsIngredient(raw_ostream &O, Value *V);
1613 };
1614 
1615 struct VPlanIngredient {
1616   Value *V;
1617 
1618   VPlanIngredient(Value *V) : V(V) {}
1619 };
1620 
1621 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1622   VPlanPrinter::printAsIngredient(OS, I.V);
1623   return OS;
1624 }
1625 
1626 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
1627   VPlanPrinter Printer(OS, Plan);
1628   Printer.dump();
1629   return OS;
1630 }
1631 
1632 //===----------------------------------------------------------------------===//
1633 // VPlan Utilities
1634 //===----------------------------------------------------------------------===//
1635 
1636 /// Class that provides utilities for VPBlockBases in VPlan.
1637 class VPBlockUtils {
1638 public:
1639   VPBlockUtils() = delete;
1640 
1641   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1642   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1643   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1644   /// has more than one successor, its conditional bit is propagated to \p
1645   /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1646   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1647     assert(NewBlock->getSuccessors().empty() &&
1648            "Can't insert new block with successors.");
1649     // TODO: move successors from BlockPtr to NewBlock when this functionality
1650     // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1651     // already has successors.
1652     BlockPtr->setOneSuccessor(NewBlock);
1653     NewBlock->setPredecessors({BlockPtr});
1654     NewBlock->setParent(BlockPtr->getParent());
1655   }
1656 
1657   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1658   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1659   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1660   /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1661   /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1662   /// must have neither successors nor predecessors.
1663   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1664                                    VPValue *Condition, VPBlockBase *BlockPtr) {
1665     assert(IfTrue->getSuccessors().empty() &&
1666            "Can't insert IfTrue with successors.");
1667     assert(IfFalse->getSuccessors().empty() &&
1668            "Can't insert IfFalse with successors.");
1669     BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
1670     IfTrue->setPredecessors({BlockPtr});
1671     IfFalse->setPredecessors({BlockPtr});
1672     IfTrue->setParent(BlockPtr->getParent());
1673     IfFalse->setParent(BlockPtr->getParent());
1674   }
1675 
1676   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1677   /// the successors of \p From and \p From to the predecessors of \p To. Both
1678   /// VPBlockBases must have the same parent, which can be null. Both
1679   /// VPBlockBases can be already connected to other VPBlockBases.
1680   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1681     assert((From->getParent() == To->getParent()) &&
1682            "Can't connect two block with different parents");
1683     assert(From->getNumSuccessors() < 2 &&
1684            "Blocks can't have more than two successors.");
1685     From->appendSuccessor(To);
1686     To->appendPredecessor(From);
1687   }
1688 
1689   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1690   /// from the successors of \p From and \p From from the predecessors of \p To.
1691   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1692     assert(To && "Successor to disconnect is null.");
1693     From->removeSuccessor(To);
1694     To->removePredecessor(From);
1695   }
1696 
1697   /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1698   static bool isBackEdge(const VPBlockBase *FromBlock,
1699                          const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
1700     assert(FromBlock->getParent() == ToBlock->getParent() &&
1701            FromBlock->getParent() && "Must be in same region");
1702     const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
1703     const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
1704     if (!FromLoop || !ToLoop || FromLoop != ToLoop)
1705       return false;
1706 
1707     // A back-edge is a branch from the loop latch to its header.
1708     return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
1709   }
1710 
1711   /// Returns true if \p Block is a loop latch
1712   static bool blockIsLoopLatch(const VPBlockBase *Block,
1713                                const VPLoopInfo *VPLInfo) {
1714     if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
1715       return ParentVPL->isLoopLatch(Block);
1716 
1717     return false;
1718   }
1719 
1720   /// Count and return the number of succesors of \p PredBlock excluding any
1721   /// backedges.
1722   static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
1723                                       VPLoopInfo *VPLI) {
1724     unsigned Count = 0;
1725     for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
1726       if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
1727         Count++;
1728     }
1729     return Count;
1730   }
1731 };
1732 
1733 class VPInterleavedAccessInfo {
1734 private:
1735   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1736       InterleaveGroupMap;
1737 
1738   /// Type for mapping of instruction based interleave groups to VPInstruction
1739   /// interleave groups
1740   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1741                              InterleaveGroup<VPInstruction> *>;
1742 
1743   /// Recursively \p Region and populate VPlan based interleave groups based on
1744   /// \p IAI.
1745   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1746                    InterleavedAccessInfo &IAI);
1747   /// Recursively traverse \p Block and populate VPlan based interleave groups
1748   /// based on \p IAI.
1749   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1750                   InterleavedAccessInfo &IAI);
1751 
1752 public:
1753   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1754 
1755   ~VPInterleavedAccessInfo() {
1756     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1757     // Avoid releasing a pointer twice.
1758     for (auto &I : InterleaveGroupMap)
1759       DelSet.insert(I.second);
1760     for (auto *Ptr : DelSet)
1761       delete Ptr;
1762   }
1763 
1764   /// Get the interleave group that \p Instr belongs to.
1765   ///
1766   /// \returns nullptr if doesn't have such group.
1767   InterleaveGroup<VPInstruction> *
1768   getInterleaveGroup(VPInstruction *Instr) const {
1769     if (InterleaveGroupMap.count(Instr))
1770       return InterleaveGroupMap.find(Instr)->second;
1771     return nullptr;
1772   }
1773 };
1774 
1775 /// Class that maps (parts of) an existing VPlan to trees of combined
1776 /// VPInstructions.
1777 class VPlanSlp {
1778 private:
1779   enum class OpMode { Failed, Load, Opcode };
1780 
1781   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
1782   /// DenseMap keys.
1783   struct BundleDenseMapInfo {
1784     static SmallVector<VPValue *, 4> getEmptyKey() {
1785       return {reinterpret_cast<VPValue *>(-1)};
1786     }
1787 
1788     static SmallVector<VPValue *, 4> getTombstoneKey() {
1789       return {reinterpret_cast<VPValue *>(-2)};
1790     }
1791 
1792     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
1793       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1794     }
1795 
1796     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
1797                         const SmallVector<VPValue *, 4> &RHS) {
1798       return LHS == RHS;
1799     }
1800   };
1801 
1802   /// Mapping of values in the original VPlan to a combined VPInstruction.
1803   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
1804       BundleToCombined;
1805 
1806   VPInterleavedAccessInfo &IAI;
1807 
1808   /// Basic block to operate on. For now, only instructions in a single BB are
1809   /// considered.
1810   const VPBasicBlock &BB;
1811 
1812   /// Indicates whether we managed to combine all visited instructions or not.
1813   bool CompletelySLP = true;
1814 
1815   /// Width of the widest combined bundle in bits.
1816   unsigned WidestBundleBits = 0;
1817 
1818   using MultiNodeOpTy =
1819       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
1820 
1821   // Input operand bundles for the current multi node. Each multi node operand
1822   // bundle contains values not matching the multi node's opcode. They will
1823   // be reordered in reorderMultiNodeOps, once we completed building a
1824   // multi node.
1825   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
1826 
1827   /// Indicates whether we are building a multi node currently.
1828   bool MultiNodeActive = false;
1829 
1830   /// Check if we can vectorize Operands together.
1831   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
1832 
1833   /// Add combined instruction \p New for the bundle \p Operands.
1834   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
1835 
1836   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
1837   VPInstruction *markFailed();
1838 
1839   /// Reorder operands in the multi node to maximize sequential memory access
1840   /// and commutative operations.
1841   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
1842 
1843   /// Choose the best candidate to use for the lane after \p Last. The set of
1844   /// candidates to choose from are values with an opcode matching \p Last's
1845   /// or loads consecutive to \p Last.
1846   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
1847                                        SmallPtrSetImpl<VPValue *> &Candidates,
1848                                        VPInterleavedAccessInfo &IAI);
1849 
1850   /// Print bundle \p Values to dbgs().
1851   void dumpBundle(ArrayRef<VPValue *> Values);
1852 
1853 public:
1854   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
1855 
1856   ~VPlanSlp() {
1857     for (auto &KV : BundleToCombined)
1858       delete KV.second;
1859   }
1860 
1861   /// Tries to build an SLP tree rooted at \p Operands and returns a
1862   /// VPInstruction combining \p Operands, if they can be combined.
1863   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
1864 
1865   /// Return the width of the widest combined bundle in bits.
1866   unsigned getWidestBundleBits() const { return WidestBundleBits; }
1867 
1868   /// Return true if all visited instruction can be combined.
1869   bool isCompletelySLP() const { return CompletelySLP; }
1870 };
1871 } // end namespace llvm
1872 
1873 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
1874