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