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 "VPlanValue.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/GraphTraits.h"
32 #include "llvm/ADT/MapVector.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/SmallBitVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/ADT/ilist.h"
39 #include "llvm/ADT/ilist_node.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/FMF.h"
44 #include "llvm/Transforms/Utils/LoopVersioning.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstddef>
48 #include <string>
49 
50 namespace llvm {
51 
52 class BasicBlock;
53 class DominatorTree;
54 class InductionDescriptor;
55 class InnerLoopVectorizer;
56 class IRBuilderBase;
57 class LoopInfo;
58 class raw_ostream;
59 class RecurrenceDescriptor;
60 class Value;
61 class VPBasicBlock;
62 class VPRegionBlock;
63 class VPlan;
64 class VPReplicateRecipe;
65 class VPlanSlp;
66 
67 /// Returns a calculation for the total number of elements for a given \p VF.
68 /// For fixed width vectors this value is a constant, whereas for scalable
69 /// vectors it is an expression determined at runtime.
70 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF);
71 
72 /// Return a value for Step multiplied by VF.
73 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
74                        int64_t Step);
75 
76 /// A range of powers-of-2 vectorization factors with fixed start and
77 /// adjustable end. The range includes start and excludes end, e.g.,:
78 /// [1, 9) = {1, 2, 4, 8}
79 struct VFRange {
80   // A power of 2.
81   const ElementCount Start;
82 
83   // Need not be a power of 2. If End <= Start range is empty.
84   ElementCount End;
85 
86   bool isEmpty() const {
87     return End.getKnownMinValue() <= Start.getKnownMinValue();
88   }
89 
90   VFRange(const ElementCount &Start, const ElementCount &End)
91       : Start(Start), End(End) {
92     assert(Start.isScalable() == End.isScalable() &&
93            "Both Start and End should have the same scalable flag");
94     assert(isPowerOf2_32(Start.getKnownMinValue()) &&
95            "Expected Start to be a power of 2");
96   }
97 };
98 
99 using VPlanPtr = std::unique_ptr<VPlan>;
100 
101 /// In what follows, the term "input IR" refers to code that is fed into the
102 /// vectorizer whereas the term "output IR" refers to code that is generated by
103 /// the vectorizer.
104 
105 /// VPLane provides a way to access lanes in both fixed width and scalable
106 /// vectors, where for the latter the lane index sometimes needs calculating
107 /// as a runtime expression.
108 class VPLane {
109 public:
110   /// Kind describes how to interpret Lane.
111   enum class Kind : uint8_t {
112     /// For First, Lane is the index into the first N elements of a
113     /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>.
114     First,
115     /// For ScalableLast, Lane is the offset from the start of the last
116     /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For
117     /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of
118     /// 1 corresponds to `((vscale - 1) * N) + 1`, etc.
119     ScalableLast
120   };
121 
122 private:
123   /// in [0..VF)
124   unsigned Lane;
125 
126   /// Indicates how the Lane should be interpreted, as described above.
127   Kind LaneKind;
128 
129 public:
130   VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {}
131 
132   static VPLane getFirstLane() { return VPLane(0, VPLane::Kind::First); }
133 
134   static VPLane getLastLaneForVF(const ElementCount &VF) {
135     unsigned LaneOffset = VF.getKnownMinValue() - 1;
136     Kind LaneKind;
137     if (VF.isScalable())
138       // In this case 'LaneOffset' refers to the offset from the start of the
139       // last subvector with VF.getKnownMinValue() elements.
140       LaneKind = VPLane::Kind::ScalableLast;
141     else
142       LaneKind = VPLane::Kind::First;
143     return VPLane(LaneOffset, LaneKind);
144   }
145 
146   /// Returns a compile-time known value for the lane index and asserts if the
147   /// lane can only be calculated at runtime.
148   unsigned getKnownLane() const {
149     assert(LaneKind == Kind::First);
150     return Lane;
151   }
152 
153   /// Returns an expression describing the lane index that can be used at
154   /// runtime.
155   Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const;
156 
157   /// Returns the Kind of lane offset.
158   Kind getKind() const { return LaneKind; }
159 
160   /// Returns true if this is the first lane of the whole vector.
161   bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; }
162 
163   /// Maps the lane to a cache index based on \p VF.
164   unsigned mapToCacheIndex(const ElementCount &VF) const {
165     switch (LaneKind) {
166     case VPLane::Kind::ScalableLast:
167       assert(VF.isScalable() && Lane < VF.getKnownMinValue());
168       return VF.getKnownMinValue() + Lane;
169     default:
170       assert(Lane < VF.getKnownMinValue());
171       return Lane;
172     }
173   }
174 
175   /// Returns the maxmimum number of lanes that we are able to consider
176   /// caching for \p VF.
177   static unsigned getNumCachedLanes(const ElementCount &VF) {
178     return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1);
179   }
180 };
181 
182 /// VPIteration represents a single point in the iteration space of the output
183 /// (vectorized and/or unrolled) IR loop.
184 struct VPIteration {
185   /// in [0..UF)
186   unsigned Part;
187 
188   VPLane Lane;
189 
190   VPIteration(unsigned Part, unsigned Lane,
191               VPLane::Kind Kind = VPLane::Kind::First)
192       : Part(Part), Lane(Lane, Kind) {}
193 
194   VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {}
195 
196   bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); }
197 };
198 
199 /// VPTransformState holds information passed down when "executing" a VPlan,
200 /// needed for generating the output IR.
201 struct VPTransformState {
202   VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
203                    DominatorTree *DT, IRBuilderBase &Builder,
204                    InnerLoopVectorizer *ILV, VPlan *Plan)
205       : VF(VF), UF(UF), LI(LI), DT(DT), Builder(Builder), ILV(ILV), Plan(Plan),
206         LVer(nullptr) {}
207 
208   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
209   ElementCount VF;
210   unsigned UF;
211 
212   /// Hold the indices to generate specific scalar instructions. Null indicates
213   /// that all instances are to be generated, using either scalar or vector
214   /// instructions.
215   Optional<VPIteration> Instance;
216 
217   struct DataState {
218     /// A type for vectorized values in the new loop. Each value from the
219     /// original loop, when vectorized, is represented by UF vector values in
220     /// the new unrolled loop, where UF is the unroll factor.
221     typedef SmallVector<Value *, 2> PerPartValuesTy;
222 
223     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
224 
225     using ScalarsPerPartValuesTy = SmallVector<SmallVector<Value *, 4>, 2>;
226     DenseMap<VPValue *, ScalarsPerPartValuesTy> PerPartScalars;
227   } Data;
228 
229   /// Get the generated Value for a given VPValue and a given Part. Note that
230   /// as some Defs are still created by ILV and managed in its ValueMap, this
231   /// method will delegate the call to ILV in such cases in order to provide
232   /// callers a consistent API.
233   /// \see set.
234   Value *get(VPValue *Def, unsigned Part);
235 
236   /// Get the generated Value for a given VPValue and given Part and Lane.
237   Value *get(VPValue *Def, const VPIteration &Instance);
238 
239   bool hasVectorValue(VPValue *Def, unsigned Part) {
240     auto I = Data.PerPartOutput.find(Def);
241     return I != Data.PerPartOutput.end() && Part < I->second.size() &&
242            I->second[Part];
243   }
244 
245   bool hasAnyVectorValue(VPValue *Def) const {
246     return Data.PerPartOutput.find(Def) != Data.PerPartOutput.end();
247   }
248 
249   bool hasScalarValue(VPValue *Def, VPIteration Instance) {
250     auto I = Data.PerPartScalars.find(Def);
251     if (I == Data.PerPartScalars.end())
252       return false;
253     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
254     return Instance.Part < I->second.size() &&
255            CacheIdx < I->second[Instance.Part].size() &&
256            I->second[Instance.Part][CacheIdx];
257   }
258 
259   /// Set the generated Value for a given VPValue and a given Part.
260   void set(VPValue *Def, Value *V, unsigned Part) {
261     if (!Data.PerPartOutput.count(Def)) {
262       DataState::PerPartValuesTy Entry(UF);
263       Data.PerPartOutput[Def] = Entry;
264     }
265     Data.PerPartOutput[Def][Part] = V;
266   }
267   /// Reset an existing vector value for \p Def and a given \p Part.
268   void reset(VPValue *Def, Value *V, unsigned Part) {
269     auto Iter = Data.PerPartOutput.find(Def);
270     assert(Iter != Data.PerPartOutput.end() &&
271            "need to overwrite existing value");
272     Iter->second[Part] = V;
273   }
274 
275   /// Set the generated scalar \p V for \p Def and the given \p Instance.
276   void set(VPValue *Def, Value *V, const VPIteration &Instance) {
277     auto Iter = Data.PerPartScalars.insert({Def, {}});
278     auto &PerPartVec = Iter.first->second;
279     while (PerPartVec.size() <= Instance.Part)
280       PerPartVec.emplace_back();
281     auto &Scalars = PerPartVec[Instance.Part];
282     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
283     while (Scalars.size() <= CacheIdx)
284       Scalars.push_back(nullptr);
285     assert(!Scalars[CacheIdx] && "should overwrite existing value");
286     Scalars[CacheIdx] = V;
287   }
288 
289   /// Reset an existing scalar value for \p Def and a given \p Instance.
290   void reset(VPValue *Def, Value *V, const VPIteration &Instance) {
291     auto Iter = Data.PerPartScalars.find(Def);
292     assert(Iter != Data.PerPartScalars.end() &&
293            "need to overwrite existing value");
294     assert(Instance.Part < Iter->second.size() &&
295            "need to overwrite existing value");
296     unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
297     assert(CacheIdx < Iter->second[Instance.Part].size() &&
298            "need to overwrite existing value");
299     Iter->second[Instance.Part][CacheIdx] = V;
300   }
301 
302   /// Add additional metadata to \p To that was not present on \p Orig.
303   ///
304   /// Currently this is used to add the noalias annotations based on the
305   /// inserted memchecks.  Use this for instructions that are *cloned* into the
306   /// vector loop.
307   void addNewMetadata(Instruction *To, const Instruction *Orig);
308 
309   /// Add metadata from one instruction to another.
310   ///
311   /// This includes both the original MDs from \p From and additional ones (\see
312   /// addNewMetadata).  Use this for *newly created* instructions in the vector
313   /// loop.
314   void addMetadata(Instruction *To, Instruction *From);
315 
316   /// Similar to the previous function but it adds the metadata to a
317   /// vector of instructions.
318   void addMetadata(ArrayRef<Value *> To, Instruction *From);
319 
320   /// Set the debug location in the builder using the debug location in \p V.
321   void setDebugLocFromInst(const Value *V);
322 
323   /// Hold state information used when constructing the CFG of the output IR,
324   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
325   struct CFGState {
326     /// The previous VPBasicBlock visited. Initially set to null.
327     VPBasicBlock *PrevVPBB = nullptr;
328 
329     /// The previous IR BasicBlock created or used. Initially set to the new
330     /// header BasicBlock.
331     BasicBlock *PrevBB = nullptr;
332 
333     /// The last IR BasicBlock in the output IR. Set to the exit block of the
334     /// vector loop.
335     BasicBlock *ExitBB = nullptr;
336 
337     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
338     /// of replication, maps the BasicBlock of the last replica created.
339     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
340 
341     CFGState() = default;
342 
343     /// Returns the BasicBlock* mapped to the pre-header of the loop region
344     /// containing \p R.
345     BasicBlock *getPreheaderBBFor(VPRecipeBase *R);
346   } CFG;
347 
348   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
349   LoopInfo *LI;
350 
351   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
352   DominatorTree *DT;
353 
354   /// Hold a reference to the IRBuilder used to generate output IR code.
355   IRBuilderBase &Builder;
356 
357   VPValue2ValueTy VPValue2Value;
358 
359   /// Hold the canonical scalar IV of the vector loop (start=0, step=VF*UF).
360   Value *CanonicalIV = nullptr;
361 
362   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
363   InnerLoopVectorizer *ILV;
364 
365   /// Pointer to the VPlan code is generated for.
366   VPlan *Plan;
367 
368   /// Holds recipes that may generate a poison value that is used after
369   /// vectorization, even when their operands are not poison.
370   SmallPtrSet<VPRecipeBase *, 16> MayGeneratePoisonRecipes;
371 
372   /// The loop object for the current parent region, or nullptr.
373   Loop *CurrentVectorLoop = nullptr;
374 
375   /// LoopVersioning.  It's only set up (non-null) if memchecks were
376   /// used.
377   ///
378   /// This is currently only used to add no-alias metadata based on the
379   /// memchecks.  The actually versioning is performed manually.
380   std::unique_ptr<LoopVersioning> LVer;
381 };
382 
383 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
384 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
385 class VPBlockBase {
386   friend class VPBlockUtils;
387 
388   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
389 
390   /// An optional name for the block.
391   std::string Name;
392 
393   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
394   /// it is a topmost VPBlockBase.
395   VPRegionBlock *Parent = nullptr;
396 
397   /// List of predecessor blocks.
398   SmallVector<VPBlockBase *, 1> Predecessors;
399 
400   /// List of successor blocks.
401   SmallVector<VPBlockBase *, 1> Successors;
402 
403   /// VPlan containing the block. Can only be set on the entry block of the
404   /// plan.
405   VPlan *Plan = nullptr;
406 
407   /// Add \p Successor as the last successor to this block.
408   void appendSuccessor(VPBlockBase *Successor) {
409     assert(Successor && "Cannot add nullptr successor!");
410     Successors.push_back(Successor);
411   }
412 
413   /// Add \p Predecessor as the last predecessor to this block.
414   void appendPredecessor(VPBlockBase *Predecessor) {
415     assert(Predecessor && "Cannot add nullptr predecessor!");
416     Predecessors.push_back(Predecessor);
417   }
418 
419   /// Remove \p Predecessor from the predecessors of this block.
420   void removePredecessor(VPBlockBase *Predecessor) {
421     auto Pos = find(Predecessors, Predecessor);
422     assert(Pos && "Predecessor does not exist");
423     Predecessors.erase(Pos);
424   }
425 
426   /// Remove \p Successor from the successors of this block.
427   void removeSuccessor(VPBlockBase *Successor) {
428     auto Pos = find(Successors, Successor);
429     assert(Pos && "Successor does not exist");
430     Successors.erase(Pos);
431   }
432 
433 protected:
434   VPBlockBase(const unsigned char SC, const std::string &N)
435       : SubclassID(SC), Name(N) {}
436 
437 public:
438   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
439   /// that are actually instantiated. Values of this enumeration are kept in the
440   /// SubclassID field of the VPBlockBase objects. They are used for concrete
441   /// type identification.
442   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
443 
444   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
445 
446   virtual ~VPBlockBase() = default;
447 
448   const std::string &getName() const { return Name; }
449 
450   void setName(const Twine &newName) { Name = newName.str(); }
451 
452   /// \return an ID for the concrete type of this object.
453   /// This is used to implement the classof checks. This should not be used
454   /// for any other purpose, as the values may change as LLVM evolves.
455   unsigned getVPBlockID() const { return SubclassID; }
456 
457   VPRegionBlock *getParent() { return Parent; }
458   const VPRegionBlock *getParent() const { return Parent; }
459 
460   /// \return A pointer to the plan containing the current block.
461   VPlan *getPlan();
462   const VPlan *getPlan() const;
463 
464   /// Sets the pointer of the plan containing the block. The block must be the
465   /// entry block into the VPlan.
466   void setPlan(VPlan *ParentPlan);
467 
468   void setParent(VPRegionBlock *P) { Parent = P; }
469 
470   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
471   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
472   /// VPBlockBase is a VPBasicBlock, it is returned.
473   const VPBasicBlock *getEntryBasicBlock() const;
474   VPBasicBlock *getEntryBasicBlock();
475 
476   /// \return the VPBasicBlock that is the exiting this VPBlockBase,
477   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
478   /// VPBlockBase is a VPBasicBlock, it is returned.
479   const VPBasicBlock *getExitingBasicBlock() const;
480   VPBasicBlock *getExitingBasicBlock();
481 
482   const VPBlocksTy &getSuccessors() const { return Successors; }
483   VPBlocksTy &getSuccessors() { return Successors; }
484 
485   iterator_range<VPBlockBase **> successors() { return Successors; }
486 
487   const VPBlocksTy &getPredecessors() const { return Predecessors; }
488   VPBlocksTy &getPredecessors() { return Predecessors; }
489 
490   /// \return the successor of this VPBlockBase if it has a single successor.
491   /// Otherwise return a null pointer.
492   VPBlockBase *getSingleSuccessor() const {
493     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
494   }
495 
496   /// \return the predecessor of this VPBlockBase if it has a single
497   /// predecessor. Otherwise return a null pointer.
498   VPBlockBase *getSinglePredecessor() const {
499     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
500   }
501 
502   size_t getNumSuccessors() const { return Successors.size(); }
503   size_t getNumPredecessors() const { return Predecessors.size(); }
504 
505   /// An Enclosing Block of a block B is any block containing B, including B
506   /// itself. \return the closest enclosing block starting from "this", which
507   /// has successors. \return the root enclosing block if all enclosing blocks
508   /// have no successors.
509   VPBlockBase *getEnclosingBlockWithSuccessors();
510 
511   /// \return the closest enclosing block starting from "this", which has
512   /// predecessors. \return the root enclosing block if all enclosing blocks
513   /// have no predecessors.
514   VPBlockBase *getEnclosingBlockWithPredecessors();
515 
516   /// \return the successors either attached directly to this VPBlockBase or, if
517   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
518   /// successors of its own, search recursively for the first enclosing
519   /// VPRegionBlock that has successors and return them. If no such
520   /// VPRegionBlock exists, return the (empty) successors of the topmost
521   /// VPBlockBase reached.
522   const VPBlocksTy &getHierarchicalSuccessors() {
523     return getEnclosingBlockWithSuccessors()->getSuccessors();
524   }
525 
526   /// \return the hierarchical successor of this VPBlockBase if it has a single
527   /// hierarchical successor. Otherwise return a null pointer.
528   VPBlockBase *getSingleHierarchicalSuccessor() {
529     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
530   }
531 
532   /// \return the predecessors either attached directly to this VPBlockBase or,
533   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
534   /// predecessors of its own, search recursively for the first enclosing
535   /// VPRegionBlock that has predecessors and return them. If no such
536   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
537   /// VPBlockBase reached.
538   const VPBlocksTy &getHierarchicalPredecessors() {
539     return getEnclosingBlockWithPredecessors()->getPredecessors();
540   }
541 
542   /// \return the hierarchical predecessor of this VPBlockBase if it has a
543   /// single hierarchical predecessor. Otherwise return a null pointer.
544   VPBlockBase *getSingleHierarchicalPredecessor() {
545     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
546   }
547 
548   /// Set a given VPBlockBase \p Successor as the single successor of this
549   /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
550   /// This VPBlockBase must have no successors.
551   void setOneSuccessor(VPBlockBase *Successor) {
552     assert(Successors.empty() && "Setting one successor when others exist.");
553     appendSuccessor(Successor);
554   }
555 
556   /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
557   /// successors of this VPBlockBase. This VPBlockBase is not added as
558   /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
559   /// successors.
560   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
561     assert(Successors.empty() && "Setting two successors when others exist.");
562     appendSuccessor(IfTrue);
563     appendSuccessor(IfFalse);
564   }
565 
566   /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
567   /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
568   /// as successor of any VPBasicBlock in \p NewPreds.
569   void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
570     assert(Predecessors.empty() && "Block predecessors already set.");
571     for (auto *Pred : NewPreds)
572       appendPredecessor(Pred);
573   }
574 
575   /// Remove all the predecessor of this block.
576   void clearPredecessors() { Predecessors.clear(); }
577 
578   /// Remove all the successors of this block.
579   void clearSuccessors() { Successors.clear(); }
580 
581   /// The method which generates the output IR that correspond to this
582   /// VPBlockBase, thereby "executing" the VPlan.
583   virtual void execute(struct VPTransformState *State) = 0;
584 
585   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
586   static void deleteCFG(VPBlockBase *Entry);
587 
588   /// Return true if it is legal to hoist instructions into this block.
589   bool isLegalToHoistInto() {
590     // There are currently no constraints that prevent an instruction to be
591     // hoisted into a VPBlockBase.
592     return true;
593   }
594 
595   /// Replace all operands of VPUsers in the block with \p NewValue and also
596   /// replaces all uses of VPValues defined in the block with NewValue.
597   virtual void dropAllReferences(VPValue *NewValue) = 0;
598 
599 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
600   void printAsOperand(raw_ostream &OS, bool PrintType) const {
601     OS << getName();
602   }
603 
604   /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
605   /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
606   /// consequtive numbers.
607   ///
608   /// Note that the numbering is applied to the whole VPlan, so printing
609   /// individual blocks is consistent with the whole VPlan printing.
610   virtual void print(raw_ostream &O, const Twine &Indent,
611                      VPSlotTracker &SlotTracker) const = 0;
612 
613   /// Print plain-text dump of this VPlan to \p O.
614   void print(raw_ostream &O) const {
615     VPSlotTracker SlotTracker(getPlan());
616     print(O, "", SlotTracker);
617   }
618 
619   /// Print the successors of this block to \p O, prefixing all lines with \p
620   /// Indent.
621   void printSuccessors(raw_ostream &O, const Twine &Indent) const;
622 
623   /// Dump this VPBlockBase to dbgs().
624   LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
625 #endif
626 };
627 
628 /// A value that is used outside the VPlan. The operand of the user needs to be
629 /// added to the associated LCSSA phi node.
630 class VPLiveOut : public VPUser {
631   PHINode *Phi;
632 
633 public:
634   VPLiveOut(PHINode *Phi, VPValue *Op)
635       : VPUser({Op}, VPUser::VPUserID::LiveOut), Phi(Phi) {}
636 
637   /// Fixup the wrapped LCSSA phi node in the unique exit block.  This simply
638   /// means we need to add the appropriate incoming value from the middle
639   /// block as exiting edges from the scalar epilogue loop (if present) are
640   /// already in place, and we exit the vector loop exclusively to the middle
641   /// block.
642   void fixPhi(VPlan &Plan, VPTransformState &State);
643 
644   /// Returns true if the VPLiveOut uses scalars of operand \p Op.
645   bool usesScalars(const VPValue *Op) const override {
646     assert(is_contained(operands(), Op) &&
647            "Op must be an operand of the recipe");
648     return true;
649   }
650 
651   PHINode *getPhi() const { return Phi; }
652 };
653 
654 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
655 /// instructions. VPRecipeBase owns the the VPValues it defines through VPDef
656 /// and is responsible for deleting its defined values. Single-value
657 /// VPRecipeBases that also inherit from VPValue must make sure to inherit from
658 /// VPRecipeBase before VPValue.
659 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>,
660                      public VPDef,
661                      public VPUser {
662   friend VPBasicBlock;
663   friend class VPBlockUtils;
664 
665   /// Each VPRecipe belongs to a single VPBasicBlock.
666   VPBasicBlock *Parent = nullptr;
667 
668 public:
669   VPRecipeBase(const unsigned char SC, ArrayRef<VPValue *> Operands)
670       : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {}
671 
672   template <typename IterT>
673   VPRecipeBase(const unsigned char SC, iterator_range<IterT> Operands)
674       : VPDef(SC), VPUser(Operands, VPUser::VPUserID::Recipe) {}
675   virtual ~VPRecipeBase() = default;
676 
677   /// \return the VPBasicBlock which this VPRecipe belongs to.
678   VPBasicBlock *getParent() { return Parent; }
679   const VPBasicBlock *getParent() const { return Parent; }
680 
681   /// The method which generates the output IR instructions that correspond to
682   /// this VPRecipe, thereby "executing" the VPlan.
683   virtual void execute(struct VPTransformState &State) = 0;
684 
685   /// Insert an unlinked recipe into a basic block immediately before
686   /// the specified recipe.
687   void insertBefore(VPRecipeBase *InsertPos);
688   /// Insert an unlinked recipe into \p BB immediately before the insertion
689   /// point \p IP;
690   void insertBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator IP);
691 
692   /// Insert an unlinked Recipe into a basic block immediately after
693   /// the specified Recipe.
694   void insertAfter(VPRecipeBase *InsertPos);
695 
696   /// Unlink this recipe from its current VPBasicBlock and insert it into
697   /// the VPBasicBlock that MovePos lives in, right after MovePos.
698   void moveAfter(VPRecipeBase *MovePos);
699 
700   /// Unlink this recipe and insert into BB before I.
701   ///
702   /// \pre I is a valid iterator into BB.
703   void moveBefore(VPBasicBlock &BB, iplist<VPRecipeBase>::iterator I);
704 
705   /// This method unlinks 'this' from the containing basic block, but does not
706   /// delete it.
707   void removeFromParent();
708 
709   /// This method unlinks 'this' from the containing basic block and deletes it.
710   ///
711   /// \returns an iterator pointing to the element after the erased one
712   iplist<VPRecipeBase>::iterator eraseFromParent();
713 
714   /// Returns the underlying instruction, if the recipe is a VPValue or nullptr
715   /// otherwise.
716   Instruction *getUnderlyingInstr() {
717     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue());
718   }
719   const Instruction *getUnderlyingInstr() const {
720     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue());
721   }
722 
723   /// Method to support type inquiry through isa, cast, and dyn_cast.
724   static inline bool classof(const VPDef *D) {
725     // All VPDefs are also VPRecipeBases.
726     return true;
727   }
728 
729   static inline bool classof(const VPUser *U) {
730     return U->getVPUserID() == VPUser::VPUserID::Recipe;
731   }
732 
733   /// Returns true if the recipe may have side-effects.
734   bool mayHaveSideEffects() const;
735 
736   /// Returns true for PHI-like recipes.
737   bool isPhi() const {
738     return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC;
739   }
740 
741   /// Returns true if the recipe may read from memory.
742   bool mayReadFromMemory() const;
743 
744   /// Returns true if the recipe may write to memory.
745   bool mayWriteToMemory() const;
746 
747   /// Returns true if the recipe may read from or write to memory.
748   bool mayReadOrWriteMemory() const {
749     return mayReadFromMemory() || mayWriteToMemory();
750   }
751 };
752 
753 inline bool VPUser::classof(const VPDef *Def) {
754   return Def->getVPDefID() == VPRecipeBase::VPInstructionSC ||
755          Def->getVPDefID() == VPRecipeBase::VPWidenSC ||
756          Def->getVPDefID() == VPRecipeBase::VPWidenCallSC ||
757          Def->getVPDefID() == VPRecipeBase::VPWidenSelectSC ||
758          Def->getVPDefID() == VPRecipeBase::VPWidenGEPSC ||
759          Def->getVPDefID() == VPRecipeBase::VPBlendSC ||
760          Def->getVPDefID() == VPRecipeBase::VPInterleaveSC ||
761          Def->getVPDefID() == VPRecipeBase::VPReplicateSC ||
762          Def->getVPDefID() == VPRecipeBase::VPReductionSC ||
763          Def->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC ||
764          Def->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
765 }
766 
767 /// This is a concrete Recipe that models a single VPlan-level instruction.
768 /// While as any Recipe it may generate a sequence of IR instructions when
769 /// executed, these instructions would always form a single-def expression as
770 /// the VPInstruction is also a single def-use vertex.
771 class VPInstruction : public VPRecipeBase, public VPValue {
772   friend class VPlanSlp;
773 
774 public:
775   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
776   enum {
777     FirstOrderRecurrenceSplice =
778         Instruction::OtherOpsEnd + 1, // Combines the incoming and previous
779                                       // values of a first-order recurrence.
780     Not,
781     ICmpULE,
782     SLPLoad,
783     SLPStore,
784     ActiveLaneMask,
785     CanonicalIVIncrement,
786     CanonicalIVIncrementNUW,
787     BranchOnCount,
788     BranchOnCond
789   };
790 
791 private:
792   typedef unsigned char OpcodeTy;
793   OpcodeTy Opcode;
794   FastMathFlags FMF;
795   DebugLoc DL;
796 
797   /// An optional name that can be used for the generated IR instruction.
798   const std::string Name;
799 
800   /// Utility method serving execute(): generates a single instance of the
801   /// modeled instruction.
802   void generateInstruction(VPTransformState &State, unsigned Part);
803 
804 protected:
805   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
806 
807 public:
808   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands, DebugLoc DL,
809                 const Twine &Name = "")
810       : VPRecipeBase(VPRecipeBase::VPInstructionSC, Operands),
811         VPValue(VPValue::VPVInstructionSC, nullptr, this), Opcode(Opcode),
812         DL(DL), Name(Name.str()) {}
813 
814   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
815                 DebugLoc DL = {}, const Twine &Name = "")
816       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands), DL, Name) {}
817 
818   /// Method to support type inquiry through isa, cast, and dyn_cast.
819   static inline bool classof(const VPValue *V) {
820     return V->getVPValueID() == VPValue::VPVInstructionSC;
821   }
822 
823   VPInstruction *clone() const {
824     SmallVector<VPValue *, 2> Operands(operands());
825     return new VPInstruction(Opcode, Operands, DL, Name);
826   }
827 
828   /// Method to support type inquiry through isa, cast, and dyn_cast.
829   static inline bool classof(const VPDef *R) {
830     return R->getVPDefID() == VPRecipeBase::VPInstructionSC;
831   }
832 
833   /// Extra classof implementations to allow directly casting from VPUser ->
834   /// VPInstruction.
835   static inline bool classof(const VPUser *U) {
836     auto *R = dyn_cast<VPRecipeBase>(U);
837     return R && R->getVPDefID() == VPRecipeBase::VPInstructionSC;
838   }
839   static inline bool classof(const VPRecipeBase *R) {
840     return R->getVPDefID() == VPRecipeBase::VPInstructionSC;
841   }
842 
843   unsigned getOpcode() const { return Opcode; }
844 
845   /// Generate the instruction.
846   /// TODO: We currently execute only per-part unless a specific instance is
847   /// provided.
848   void execute(VPTransformState &State) override;
849 
850 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
851   /// Print the VPInstruction to \p O.
852   void print(raw_ostream &O, const Twine &Indent,
853              VPSlotTracker &SlotTracker) const override;
854 
855   /// Print the VPInstruction to dbgs() (for debugging).
856   LLVM_DUMP_METHOD void dump() const;
857 #endif
858 
859   /// Return true if this instruction may modify memory.
860   bool mayWriteToMemory() const {
861     // TODO: we can use attributes of the called function to rule out memory
862     //       modifications.
863     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
864            Opcode == Instruction::Invoke || Opcode == SLPStore;
865   }
866 
867   bool hasResult() const {
868     // CallInst may or may not have a result, depending on the called function.
869     // Conservatively return calls have results for now.
870     switch (getOpcode()) {
871     case Instruction::Ret:
872     case Instruction::Br:
873     case Instruction::Store:
874     case Instruction::Switch:
875     case Instruction::IndirectBr:
876     case Instruction::Resume:
877     case Instruction::CatchRet:
878     case Instruction::Unreachable:
879     case Instruction::Fence:
880     case Instruction::AtomicRMW:
881     case VPInstruction::BranchOnCond:
882     case VPInstruction::BranchOnCount:
883       return false;
884     default:
885       return true;
886     }
887   }
888 
889   /// Set the fast-math flags.
890   void setFastMathFlags(FastMathFlags FMFNew);
891 
892   /// Returns true if the recipe only uses the first lane of operand \p Op.
893   bool onlyFirstLaneUsed(const VPValue *Op) const override {
894     assert(is_contained(operands(), Op) &&
895            "Op must be an operand of the recipe");
896     if (getOperand(0) != Op)
897       return false;
898     switch (getOpcode()) {
899     default:
900       return false;
901     case VPInstruction::ActiveLaneMask:
902     case VPInstruction::CanonicalIVIncrement:
903     case VPInstruction::CanonicalIVIncrementNUW:
904     case VPInstruction::BranchOnCount:
905       return true;
906     };
907     llvm_unreachable("switch should return");
908   }
909 };
910 
911 /// VPWidenRecipe is a recipe for producing a copy of vector type its
912 /// ingredient. This recipe covers most of the traditional vectorization cases
913 /// where each ingredient transforms into a vectorized version of itself.
914 class VPWidenRecipe : public VPRecipeBase, public VPValue {
915 public:
916   template <typename IterT>
917   VPWidenRecipe(Instruction &I, iterator_range<IterT> Operands)
918       : VPRecipeBase(VPRecipeBase::VPWidenSC, Operands),
919         VPValue(VPValue::VPVWidenSC, &I, this) {}
920 
921   ~VPWidenRecipe() override = default;
922 
923   /// Method to support type inquiry through isa, cast, and dyn_cast.
924   static inline bool classof(const VPDef *D) {
925     return D->getVPDefID() == VPRecipeBase::VPWidenSC;
926   }
927   static inline bool classof(const VPValue *V) {
928     return V->getVPValueID() == VPValue::VPVWidenSC;
929   }
930 
931   /// Produce widened copies of all Ingredients.
932   void execute(VPTransformState &State) override;
933 
934 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
935   /// Print the recipe.
936   void print(raw_ostream &O, const Twine &Indent,
937              VPSlotTracker &SlotTracker) const override;
938 #endif
939 };
940 
941 /// A recipe for widening Call instructions.
942 class VPWidenCallRecipe : public VPRecipeBase, public VPValue {
943 
944 public:
945   template <typename IterT>
946   VPWidenCallRecipe(CallInst &I, iterator_range<IterT> CallArguments)
947       : VPRecipeBase(VPRecipeBase::VPWidenCallSC, CallArguments),
948         VPValue(VPValue::VPVWidenCallSC, &I, this) {}
949 
950   ~VPWidenCallRecipe() override = default;
951 
952   /// Method to support type inquiry through isa, cast, and dyn_cast.
953   static inline bool classof(const VPDef *D) {
954     return D->getVPDefID() == VPRecipeBase::VPWidenCallSC;
955   }
956 
957   /// Produce a widened version of the call instruction.
958   void execute(VPTransformState &State) override;
959 
960 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
961   /// Print the recipe.
962   void print(raw_ostream &O, const Twine &Indent,
963              VPSlotTracker &SlotTracker) const override;
964 #endif
965 };
966 
967 /// A recipe for widening select instructions.
968 class VPWidenSelectRecipe : public VPRecipeBase, public VPValue {
969 
970   /// Is the condition of the select loop invariant?
971   bool InvariantCond;
972 
973 public:
974   template <typename IterT>
975   VPWidenSelectRecipe(SelectInst &I, iterator_range<IterT> Operands,
976                       bool InvariantCond)
977       : VPRecipeBase(VPRecipeBase::VPWidenSelectSC, Operands),
978         VPValue(VPValue::VPVWidenSelectSC, &I, this),
979         InvariantCond(InvariantCond) {}
980 
981   ~VPWidenSelectRecipe() override = default;
982 
983   /// Method to support type inquiry through isa, cast, and dyn_cast.
984   static inline bool classof(const VPDef *D) {
985     return D->getVPDefID() == VPRecipeBase::VPWidenSelectSC;
986   }
987 
988   /// Produce a widened version of the select instruction.
989   void execute(VPTransformState &State) override;
990 
991 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
992   /// Print the recipe.
993   void print(raw_ostream &O, const Twine &Indent,
994              VPSlotTracker &SlotTracker) const override;
995 #endif
996 };
997 
998 /// A recipe for handling GEP instructions.
999 class VPWidenGEPRecipe : public VPRecipeBase, public VPValue {
1000   bool IsPtrLoopInvariant;
1001   SmallBitVector IsIndexLoopInvariant;
1002 
1003 public:
1004   template <typename IterT>
1005   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands)
1006       : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands),
1007         VPValue(VPWidenGEPSC, GEP, this),
1008         IsIndexLoopInvariant(GEP->getNumIndices(), false) {}
1009 
1010   template <typename IterT>
1011   VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range<IterT> Operands,
1012                    Loop *OrigLoop)
1013       : VPRecipeBase(VPRecipeBase::VPWidenGEPSC, Operands),
1014         VPValue(VPValue::VPVWidenGEPSC, GEP, this),
1015         IsIndexLoopInvariant(GEP->getNumIndices(), false) {
1016     IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
1017     for (auto Index : enumerate(GEP->indices()))
1018       IsIndexLoopInvariant[Index.index()] =
1019           OrigLoop->isLoopInvariant(Index.value().get());
1020   }
1021   ~VPWidenGEPRecipe() override = default;
1022 
1023   /// Method to support type inquiry through isa, cast, and dyn_cast.
1024   static inline bool classof(const VPDef *D) {
1025     return D->getVPDefID() == VPRecipeBase::VPWidenGEPSC;
1026   }
1027 
1028   /// Generate the gep nodes.
1029   void execute(VPTransformState &State) override;
1030 
1031 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1032   /// Print the recipe.
1033   void print(raw_ostream &O, const Twine &Indent,
1034              VPSlotTracker &SlotTracker) const override;
1035 #endif
1036 };
1037 
1038 /// A recipe for handling phi nodes of integer and floating-point inductions,
1039 /// producing their vector values.
1040 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase, public VPValue {
1041   PHINode *IV;
1042   const InductionDescriptor &IndDesc;
1043   bool NeedsVectorIV;
1044 
1045 public:
1046   VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step,
1047                                 const InductionDescriptor &IndDesc,
1048                                 bool NeedsVectorIV)
1049       : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}),
1050         VPValue(IV, this), IV(IV), IndDesc(IndDesc),
1051         NeedsVectorIV(NeedsVectorIV) {}
1052 
1053   VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step,
1054                                 const InductionDescriptor &IndDesc,
1055                                 TruncInst *Trunc, bool NeedsVectorIV)
1056       : VPRecipeBase(VPWidenIntOrFpInductionSC, {Start, Step}),
1057         VPValue(Trunc, this), IV(IV), IndDesc(IndDesc),
1058         NeedsVectorIV(NeedsVectorIV) {}
1059 
1060   ~VPWidenIntOrFpInductionRecipe() override = default;
1061 
1062   /// Method to support type inquiry through isa, cast, and dyn_cast.
1063   static inline bool classof(const VPDef *D) {
1064     return D->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
1065   }
1066 
1067   /// Generate the vectorized and scalarized versions of the phi node as
1068   /// needed by their users.
1069   void execute(VPTransformState &State) override;
1070 
1071 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1072   /// Print the recipe.
1073   void print(raw_ostream &O, const Twine &Indent,
1074              VPSlotTracker &SlotTracker) const override;
1075 #endif
1076 
1077   /// Returns the start value of the induction.
1078   VPValue *getStartValue() { return getOperand(0); }
1079   const VPValue *getStartValue() const { return getOperand(0); }
1080 
1081   /// Returns the step value of the induction.
1082   VPValue *getStepValue() { return getOperand(1); }
1083   const VPValue *getStepValue() const { return getOperand(1); }
1084 
1085   /// Returns the first defined value as TruncInst, if it is one or nullptr
1086   /// otherwise.
1087   TruncInst *getTruncInst() {
1088     return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue());
1089   }
1090   const TruncInst *getTruncInst() const {
1091     return dyn_cast_or_null<TruncInst>(getVPValue(0)->getUnderlyingValue());
1092   }
1093 
1094   PHINode *getPHINode() { return IV; }
1095 
1096   /// Returns the induction descriptor for the recipe.
1097   const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
1098 
1099   /// Returns true if the induction is canonical, i.e. starting at 0 and
1100   /// incremented by UF * VF (= the original IV is incremented by 1).
1101   bool isCanonical() const;
1102 
1103   /// Returns the scalar type of the induction.
1104   const Type *getScalarType() const {
1105     const TruncInst *TruncI = getTruncInst();
1106     return TruncI ? TruncI->getType() : IV->getType();
1107   }
1108 
1109   /// Returns true if a vector phi needs to be created for the induction.
1110   bool needsVectorIV() const { return NeedsVectorIV; }
1111 };
1112 
1113 /// A pure virtual base class for all recipes modeling header phis, including
1114 /// phis for first order recurrences, pointer inductions and reductions. The
1115 /// start value is the first operand of the recipe and the incoming value from
1116 /// the backedge is the second operand.
1117 class VPHeaderPHIRecipe : public VPRecipeBase, public VPValue {
1118 protected:
1119   VPHeaderPHIRecipe(unsigned char VPVID, unsigned char VPDefID, PHINode *Phi,
1120                     VPValue *Start = nullptr)
1121       : VPRecipeBase(VPDefID, {}), VPValue(VPVID, Phi, this) {
1122     if (Start)
1123       addOperand(Start);
1124   }
1125 
1126 public:
1127   ~VPHeaderPHIRecipe() override = default;
1128 
1129   /// Method to support type inquiry through isa, cast, and dyn_cast.
1130   static inline bool classof(const VPRecipeBase *B) {
1131     return B->getVPDefID() == VPRecipeBase::VPCanonicalIVPHISC ||
1132            B->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC ||
1133            B->getVPDefID() == VPRecipeBase::VPReductionPHISC ||
1134            B->getVPDefID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
1135            B->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1136   }
1137   static inline bool classof(const VPValue *V) {
1138     return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC ||
1139            V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC ||
1140            V->getVPValueID() == VPValue::VPVReductionPHISC ||
1141            V->getVPValueID() == VPValue::VPVWidenIntOrFpInductionSC ||
1142            V->getVPValueID() == VPValue::VPVWidenPHISC;
1143   }
1144 
1145   /// Generate the phi nodes.
1146   void execute(VPTransformState &State) override = 0;
1147 
1148 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1149   /// Print the recipe.
1150   void print(raw_ostream &O, const Twine &Indent,
1151              VPSlotTracker &SlotTracker) const override = 0;
1152 #endif
1153 
1154   /// Returns the start value of the phi, if one is set.
1155   VPValue *getStartValue() {
1156     return getNumOperands() == 0 ? nullptr : getOperand(0);
1157   }
1158   VPValue *getStartValue() const {
1159     return getNumOperands() == 0 ? nullptr : getOperand(0);
1160   }
1161 
1162   /// Returns the incoming value from the loop backedge.
1163   VPValue *getBackedgeValue() {
1164     return getOperand(1);
1165   }
1166 
1167   /// Returns the backedge value as a recipe. The backedge value is guaranteed
1168   /// to be a recipe.
1169   VPRecipeBase *getBackedgeRecipe() {
1170     return cast<VPRecipeBase>(getBackedgeValue()->getDef());
1171   }
1172 };
1173 
1174 class VPWidenPointerInductionRecipe : public VPHeaderPHIRecipe {
1175   const InductionDescriptor &IndDesc;
1176 
1177   /// SCEV used to expand step.
1178   /// FIXME: move expansion of step to the pre-header, once it is modeled
1179   /// explicitly.
1180   ScalarEvolution &SE;
1181 
1182 public:
1183   /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
1184   /// Start.
1185   VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start,
1186                                 const InductionDescriptor &IndDesc,
1187                                 ScalarEvolution &SE)
1188       : VPHeaderPHIRecipe(VPVWidenPointerInductionSC, VPWidenPointerInductionSC,
1189                           Phi),
1190         IndDesc(IndDesc), SE(SE) {
1191     addOperand(Start);
1192   }
1193 
1194   ~VPWidenPointerInductionRecipe() override = default;
1195 
1196   /// Method to support type inquiry through isa, cast, and dyn_cast.
1197   static inline bool classof(const VPRecipeBase *B) {
1198     return B->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC;
1199   }
1200   static inline bool classof(const VPHeaderPHIRecipe *R) {
1201     return R->getVPDefID() == VPRecipeBase::VPWidenPointerInductionSC;
1202   }
1203   static inline bool classof(const VPValue *V) {
1204     return V->getVPValueID() == VPValue::VPVWidenPointerInductionSC;
1205   }
1206 
1207   /// Generate vector values for the pointer induction.
1208   void execute(VPTransformState &State) override;
1209 
1210   /// Returns true if only scalar values will be generated.
1211   bool onlyScalarsGenerated(ElementCount VF);
1212 
1213 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1214   /// Print the recipe.
1215   void print(raw_ostream &O, const Twine &Indent,
1216              VPSlotTracker &SlotTracker) const override;
1217 #endif
1218 };
1219 
1220 /// A recipe for handling header phis that are widened in the vector loop.
1221 /// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are
1222 /// managed in the recipe directly.
1223 class VPWidenPHIRecipe : public VPHeaderPHIRecipe {
1224   /// List of incoming blocks. Only used in the VPlan native path.
1225   SmallVector<VPBasicBlock *, 2> IncomingBlocks;
1226 
1227 public:
1228   /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start.
1229   VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr)
1230       : VPHeaderPHIRecipe(VPVWidenPHISC, VPWidenPHISC, Phi) {
1231     if (Start)
1232       addOperand(Start);
1233   }
1234 
1235   ~VPWidenPHIRecipe() override = default;
1236 
1237   /// Method to support type inquiry through isa, cast, and dyn_cast.
1238   static inline bool classof(const VPRecipeBase *B) {
1239     return B->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1240   }
1241   static inline bool classof(const VPHeaderPHIRecipe *R) {
1242     return R->getVPDefID() == VPRecipeBase::VPWidenPHISC;
1243   }
1244   static inline bool classof(const VPValue *V) {
1245     return V->getVPValueID() == VPValue::VPVWidenPHISC;
1246   }
1247 
1248   /// Generate the phi/select nodes.
1249   void execute(VPTransformState &State) override;
1250 
1251 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1252   /// Print the recipe.
1253   void print(raw_ostream &O, const Twine &Indent,
1254              VPSlotTracker &SlotTracker) const override;
1255 #endif
1256 
1257   /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi.
1258   void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) {
1259     addOperand(IncomingV);
1260     IncomingBlocks.push_back(IncomingBlock);
1261   }
1262 
1263   /// Returns the \p I th incoming VPBasicBlock.
1264   VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; }
1265 
1266   /// Returns the \p I th incoming VPValue.
1267   VPValue *getIncomingValue(unsigned I) { return getOperand(I); }
1268 };
1269 
1270 /// A recipe for handling first-order recurrence phis. The start value is the
1271 /// first operand of the recipe and the incoming value from the backedge is the
1272 /// second operand.
1273 struct VPFirstOrderRecurrencePHIRecipe : public VPHeaderPHIRecipe {
1274   VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start)
1275       : VPHeaderPHIRecipe(VPVFirstOrderRecurrencePHISC,
1276                           VPFirstOrderRecurrencePHISC, Phi, &Start) {}
1277 
1278   /// Method to support type inquiry through isa, cast, and dyn_cast.
1279   static inline bool classof(const VPRecipeBase *R) {
1280     return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC;
1281   }
1282   static inline bool classof(const VPHeaderPHIRecipe *R) {
1283     return R->getVPDefID() == VPRecipeBase::VPFirstOrderRecurrencePHISC;
1284   }
1285   static inline bool classof(const VPValue *V) {
1286     return V->getVPValueID() == VPValue::VPVFirstOrderRecurrencePHISC;
1287   }
1288 
1289   void execute(VPTransformState &State) override;
1290 
1291 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1292   /// Print the recipe.
1293   void print(raw_ostream &O, const Twine &Indent,
1294              VPSlotTracker &SlotTracker) const override;
1295 #endif
1296 };
1297 
1298 /// A recipe for handling reduction phis. The start value is the first operand
1299 /// of the recipe and the incoming value from the backedge is the second
1300 /// operand.
1301 class VPReductionPHIRecipe : public VPHeaderPHIRecipe {
1302   /// Descriptor for the reduction.
1303   const RecurrenceDescriptor &RdxDesc;
1304 
1305   /// The phi is part of an in-loop reduction.
1306   bool IsInLoop;
1307 
1308   /// The phi is part of an ordered reduction. Requires IsInLoop to be true.
1309   bool IsOrdered;
1310 
1311 public:
1312   /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p
1313   /// RdxDesc.
1314   VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc,
1315                        VPValue &Start, bool IsInLoop = false,
1316                        bool IsOrdered = false)
1317       : VPHeaderPHIRecipe(VPVReductionPHISC, VPReductionPHISC, Phi, &Start),
1318         RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) {
1319     assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop");
1320   }
1321 
1322   ~VPReductionPHIRecipe() override = default;
1323 
1324   /// Method to support type inquiry through isa, cast, and dyn_cast.
1325   static inline bool classof(const VPRecipeBase *R) {
1326     return R->getVPDefID() == VPRecipeBase::VPReductionPHISC;
1327   }
1328   static inline bool classof(const VPHeaderPHIRecipe *R) {
1329     return R->getVPDefID() == VPRecipeBase::VPReductionPHISC;
1330   }
1331   static inline bool classof(const VPValue *V) {
1332     return V->getVPValueID() == VPValue::VPVReductionPHISC;
1333   }
1334 
1335   /// Generate the phi/select nodes.
1336   void execute(VPTransformState &State) override;
1337 
1338 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1339   /// Print the recipe.
1340   void print(raw_ostream &O, const Twine &Indent,
1341              VPSlotTracker &SlotTracker) const override;
1342 #endif
1343 
1344   const RecurrenceDescriptor &getRecurrenceDescriptor() const {
1345     return RdxDesc;
1346   }
1347 
1348   /// Returns true, if the phi is part of an ordered reduction.
1349   bool isOrdered() const { return IsOrdered; }
1350 
1351   /// Returns true, if the phi is part of an in-loop reduction.
1352   bool isInLoop() const { return IsInLoop; }
1353 };
1354 
1355 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
1356 /// instructions.
1357 class VPBlendRecipe : public VPRecipeBase, public VPValue {
1358   PHINode *Phi;
1359 
1360 public:
1361   /// The blend operation is a User of the incoming values and of their
1362   /// respective masks, ordered [I0, M0, I1, M1, ...]. Note that a single value
1363   /// might be incoming with a full mask for which there is no VPValue.
1364   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Operands)
1365       : VPRecipeBase(VPBlendSC, Operands),
1366         VPValue(VPValue::VPVBlendSC, Phi, this), Phi(Phi) {
1367     assert(Operands.size() > 0 &&
1368            ((Operands.size() == 1) || (Operands.size() % 2 == 0)) &&
1369            "Expected either a single incoming value or a positive even number "
1370            "of operands");
1371   }
1372 
1373   /// Method to support type inquiry through isa, cast, and dyn_cast.
1374   static inline bool classof(const VPDef *D) {
1375     return D->getVPDefID() == VPRecipeBase::VPBlendSC;
1376   }
1377 
1378   /// Return the number of incoming values, taking into account that a single
1379   /// incoming value has no mask.
1380   unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; }
1381 
1382   /// Return incoming value number \p Idx.
1383   VPValue *getIncomingValue(unsigned Idx) const { return getOperand(Idx * 2); }
1384 
1385   /// Return mask number \p Idx.
1386   VPValue *getMask(unsigned Idx) const { return getOperand(Idx * 2 + 1); }
1387 
1388   /// Generate the phi/select nodes.
1389   void execute(VPTransformState &State) override;
1390 
1391 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1392   /// Print the recipe.
1393   void print(raw_ostream &O, const Twine &Indent,
1394              VPSlotTracker &SlotTracker) const override;
1395 #endif
1396 
1397   /// Returns true if the recipe only uses the first lane of operand \p Op.
1398   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1399     assert(is_contained(operands(), Op) &&
1400            "Op must be an operand of the recipe");
1401     // Recursing through Blend recipes only, must terminate at header phi's the
1402     // latest.
1403     return all_of(users(),
1404                   [this](VPUser *U) { return U->onlyFirstLaneUsed(this); });
1405   }
1406 };
1407 
1408 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
1409 /// or stores into one wide load/store and shuffles. The first operand of a
1410 /// VPInterleave recipe is the address, followed by the stored values, followed
1411 /// by an optional mask.
1412 class VPInterleaveRecipe : public VPRecipeBase {
1413   const InterleaveGroup<Instruction> *IG;
1414 
1415   bool HasMask = false;
1416 
1417 public:
1418   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Addr,
1419                      ArrayRef<VPValue *> StoredValues, VPValue *Mask)
1420       : VPRecipeBase(VPInterleaveSC, {Addr}), IG(IG) {
1421     for (unsigned i = 0; i < IG->getFactor(); ++i)
1422       if (Instruction *I = IG->getMember(i)) {
1423         if (I->getType()->isVoidTy())
1424           continue;
1425         new VPValue(I, this);
1426       }
1427 
1428     for (auto *SV : StoredValues)
1429       addOperand(SV);
1430     if (Mask) {
1431       HasMask = true;
1432       addOperand(Mask);
1433     }
1434   }
1435   ~VPInterleaveRecipe() override = default;
1436 
1437   /// Method to support type inquiry through isa, cast, and dyn_cast.
1438   static inline bool classof(const VPDef *D) {
1439     return D->getVPDefID() == VPRecipeBase::VPInterleaveSC;
1440   }
1441 
1442   /// Return the address accessed by this recipe.
1443   VPValue *getAddr() const {
1444     return getOperand(0); // Address is the 1st, mandatory operand.
1445   }
1446 
1447   /// Return the mask used by this recipe. Note that a full mask is represented
1448   /// by a nullptr.
1449   VPValue *getMask() const {
1450     // Mask is optional and therefore the last, currently 2nd operand.
1451     return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
1452   }
1453 
1454   /// Return the VPValues stored by this interleave group. If it is a load
1455   /// interleave group, return an empty ArrayRef.
1456   ArrayRef<VPValue *> getStoredValues() const {
1457     // The first operand is the address, followed by the stored values, followed
1458     // by an optional mask.
1459     return ArrayRef<VPValue *>(op_begin(), getNumOperands())
1460         .slice(1, getNumStoreOperands());
1461   }
1462 
1463   /// Generate the wide load or store, and shuffles.
1464   void execute(VPTransformState &State) override;
1465 
1466 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1467   /// Print the recipe.
1468   void print(raw_ostream &O, const Twine &Indent,
1469              VPSlotTracker &SlotTracker) const override;
1470 #endif
1471 
1472   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
1473 
1474   /// Returns the number of stored operands of this interleave group. Returns 0
1475   /// for load interleave groups.
1476   unsigned getNumStoreOperands() const {
1477     return getNumOperands() - (HasMask ? 2 : 1);
1478   }
1479 
1480   /// The recipe only uses the first lane of the address.
1481   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1482     assert(is_contained(operands(), Op) &&
1483            "Op must be an operand of the recipe");
1484     return Op == getAddr() && all_of(getStoredValues(), [Op](VPValue *StoredV) {
1485              return Op != StoredV;
1486            });
1487   }
1488 };
1489 
1490 /// A recipe to represent inloop reduction operations, performing a reduction on
1491 /// a vector operand into a scalar value, and adding the result to a chain.
1492 /// The Operands are {ChainOp, VecOp, [Condition]}.
1493 class VPReductionRecipe : public VPRecipeBase, public VPValue {
1494   /// The recurrence decriptor for the reduction in question.
1495   const RecurrenceDescriptor *RdxDesc;
1496   /// Pointer to the TTI, needed to create the target reduction
1497   const TargetTransformInfo *TTI;
1498 
1499 public:
1500   VPReductionRecipe(const RecurrenceDescriptor *R, Instruction *I,
1501                     VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
1502                     const TargetTransformInfo *TTI)
1503       : VPRecipeBase(VPRecipeBase::VPReductionSC, {ChainOp, VecOp}),
1504         VPValue(VPValue::VPVReductionSC, I, this), RdxDesc(R), TTI(TTI) {
1505     if (CondOp)
1506       addOperand(CondOp);
1507   }
1508 
1509   ~VPReductionRecipe() override = default;
1510 
1511   /// Method to support type inquiry through isa, cast, and dyn_cast.
1512   static inline bool classof(const VPValue *V) {
1513     return V->getVPValueID() == VPValue::VPVReductionSC;
1514   }
1515 
1516   /// Generate the reduction in the loop
1517   void execute(VPTransformState &State) override;
1518 
1519 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1520   /// Print the recipe.
1521   void print(raw_ostream &O, const Twine &Indent,
1522              VPSlotTracker &SlotTracker) const override;
1523 #endif
1524 
1525   /// The VPValue of the scalar Chain being accumulated.
1526   VPValue *getChainOp() const { return getOperand(0); }
1527   /// The VPValue of the vector value to be reduced.
1528   VPValue *getVecOp() const { return getOperand(1); }
1529   /// The VPValue of the condition for the block.
1530   VPValue *getCondOp() const {
1531     return getNumOperands() > 2 ? getOperand(2) : nullptr;
1532   }
1533 };
1534 
1535 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
1536 /// copies of the original scalar type, one per lane, instead of producing a
1537 /// single copy of widened type for all lanes. If the instruction is known to be
1538 /// uniform only one copy, per lane zero, will be generated.
1539 class VPReplicateRecipe : public VPRecipeBase, public VPValue {
1540   /// Indicator if only a single replica per lane is needed.
1541   bool IsUniform;
1542 
1543   /// Indicator if the replicas are also predicated.
1544   bool IsPredicated;
1545 
1546   /// Indicator if the scalar values should also be packed into a vector.
1547   bool AlsoPack;
1548 
1549 public:
1550   template <typename IterT>
1551   VPReplicateRecipe(Instruction *I, iterator_range<IterT> Operands,
1552                     bool IsUniform, bool IsPredicated = false)
1553       : VPRecipeBase(VPReplicateSC, Operands), VPValue(VPVReplicateSC, I, this),
1554         IsUniform(IsUniform), IsPredicated(IsPredicated) {
1555     // Retain the previous behavior of predicateInstructions(), where an
1556     // insert-element of a predicated instruction got hoisted into the
1557     // predicated basic block iff it was its only user. This is achieved by
1558     // having predicated instructions also pack their values into a vector by
1559     // default unless they have a replicated user which uses their scalar value.
1560     AlsoPack = IsPredicated && !I->use_empty();
1561   }
1562 
1563   ~VPReplicateRecipe() override = default;
1564 
1565   /// Method to support type inquiry through isa, cast, and dyn_cast.
1566   static inline bool classof(const VPDef *D) {
1567     return D->getVPDefID() == VPRecipeBase::VPReplicateSC;
1568   }
1569 
1570   static inline bool classof(const VPValue *V) {
1571     return V->getVPValueID() == VPValue::VPVReplicateSC;
1572   }
1573 
1574   /// Generate replicas of the desired Ingredient. Replicas will be generated
1575   /// for all parts and lanes unless a specific part and lane are specified in
1576   /// the \p State.
1577   void execute(VPTransformState &State) override;
1578 
1579   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
1580 
1581 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1582   /// Print the recipe.
1583   void print(raw_ostream &O, const Twine &Indent,
1584              VPSlotTracker &SlotTracker) const override;
1585 #endif
1586 
1587   bool isUniform() const { return IsUniform; }
1588 
1589   bool isPacked() const { return AlsoPack; }
1590 
1591   bool isPredicated() const { return IsPredicated; }
1592 
1593   /// Returns true if the recipe only uses the first lane of operand \p Op.
1594   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1595     assert(is_contained(operands(), Op) &&
1596            "Op must be an operand of the recipe");
1597     return isUniform();
1598   }
1599 
1600   /// Returns true if the recipe uses scalars of operand \p Op.
1601   bool usesScalars(const VPValue *Op) const override {
1602     assert(is_contained(operands(), Op) &&
1603            "Op must be an operand of the recipe");
1604     return true;
1605   }
1606 };
1607 
1608 /// A recipe for generating conditional branches on the bits of a mask.
1609 class VPBranchOnMaskRecipe : public VPRecipeBase {
1610 public:
1611   VPBranchOnMaskRecipe(VPValue *BlockInMask)
1612       : VPRecipeBase(VPBranchOnMaskSC, {}) {
1613     if (BlockInMask) // nullptr means all-one mask.
1614       addOperand(BlockInMask);
1615   }
1616 
1617   /// Method to support type inquiry through isa, cast, and dyn_cast.
1618   static inline bool classof(const VPDef *D) {
1619     return D->getVPDefID() == VPRecipeBase::VPBranchOnMaskSC;
1620   }
1621 
1622   /// Generate the extraction of the appropriate bit from the block mask and the
1623   /// conditional branch.
1624   void execute(VPTransformState &State) override;
1625 
1626 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1627   /// Print the recipe.
1628   void print(raw_ostream &O, const Twine &Indent,
1629              VPSlotTracker &SlotTracker) const override {
1630     O << Indent << "BRANCH-ON-MASK ";
1631     if (VPValue *Mask = getMask())
1632       Mask->printAsOperand(O, SlotTracker);
1633     else
1634       O << " All-One";
1635   }
1636 #endif
1637 
1638   /// Return the mask used by this recipe. Note that a full mask is represented
1639   /// by a nullptr.
1640   VPValue *getMask() const {
1641     assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
1642     // Mask is optional.
1643     return getNumOperands() == 1 ? getOperand(0) : nullptr;
1644   }
1645 
1646   /// Returns true if the recipe uses scalars of operand \p Op.
1647   bool usesScalars(const VPValue *Op) const override {
1648     assert(is_contained(operands(), Op) &&
1649            "Op must be an operand of the recipe");
1650     return true;
1651   }
1652 };
1653 
1654 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
1655 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
1656 /// order to merge values that are set under such a branch and feed their uses.
1657 /// The phi nodes can be scalar or vector depending on the users of the value.
1658 /// This recipe works in concert with VPBranchOnMaskRecipe.
1659 class VPPredInstPHIRecipe : public VPRecipeBase, public VPValue {
1660 public:
1661   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
1662   /// nodes after merging back from a Branch-on-Mask.
1663   VPPredInstPHIRecipe(VPValue *PredV)
1664       : VPRecipeBase(VPPredInstPHISC, PredV),
1665         VPValue(VPValue::VPVPredInstPHI, nullptr, this) {}
1666   ~VPPredInstPHIRecipe() override = default;
1667 
1668   /// Method to support type inquiry through isa, cast, and dyn_cast.
1669   static inline bool classof(const VPDef *D) {
1670     return D->getVPDefID() == VPRecipeBase::VPPredInstPHISC;
1671   }
1672 
1673   /// Generates phi nodes for live-outs as needed to retain SSA form.
1674   void execute(VPTransformState &State) override;
1675 
1676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1677   /// Print the recipe.
1678   void print(raw_ostream &O, const Twine &Indent,
1679              VPSlotTracker &SlotTracker) const override;
1680 #endif
1681 
1682   /// Returns true if the recipe uses scalars of operand \p Op.
1683   bool usesScalars(const VPValue *Op) const override {
1684     assert(is_contained(operands(), Op) &&
1685            "Op must be an operand of the recipe");
1686     return true;
1687   }
1688 };
1689 
1690 /// A Recipe for widening load/store operations.
1691 /// The recipe uses the following VPValues:
1692 /// - For load: Address, optional mask
1693 /// - For store: Address, stored value, optional mask
1694 /// TODO: We currently execute only per-part unless a specific instance is
1695 /// provided.
1696 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
1697   Instruction &Ingredient;
1698 
1699   // Whether the loaded-from / stored-to addresses are consecutive.
1700   bool Consecutive;
1701 
1702   // Whether the consecutive loaded/stored addresses are in reverse order.
1703   bool Reverse;
1704 
1705   void setMask(VPValue *Mask) {
1706     if (!Mask)
1707       return;
1708     addOperand(Mask);
1709   }
1710 
1711   bool isMasked() const {
1712     return isStore() ? getNumOperands() == 3 : getNumOperands() == 2;
1713   }
1714 
1715 public:
1716   VPWidenMemoryInstructionRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask,
1717                                  bool Consecutive, bool Reverse)
1718       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr}), Ingredient(Load),
1719         Consecutive(Consecutive), Reverse(Reverse) {
1720     assert((Consecutive || !Reverse) && "Reverse implies consecutive");
1721     new VPValue(VPValue::VPVMemoryInstructionSC, &Load, this);
1722     setMask(Mask);
1723   }
1724 
1725   VPWidenMemoryInstructionRecipe(StoreInst &Store, VPValue *Addr,
1726                                  VPValue *StoredValue, VPValue *Mask,
1727                                  bool Consecutive, bool Reverse)
1728       : VPRecipeBase(VPWidenMemoryInstructionSC, {Addr, StoredValue}),
1729         Ingredient(Store), Consecutive(Consecutive), Reverse(Reverse) {
1730     assert((Consecutive || !Reverse) && "Reverse implies consecutive");
1731     setMask(Mask);
1732   }
1733 
1734   /// Method to support type inquiry through isa, cast, and dyn_cast.
1735   static inline bool classof(const VPDef *D) {
1736     return D->getVPDefID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1737   }
1738 
1739   /// Return the address accessed by this recipe.
1740   VPValue *getAddr() const {
1741     return getOperand(0); // Address is the 1st, mandatory operand.
1742   }
1743 
1744   /// Return the mask used by this recipe. Note that a full mask is represented
1745   /// by a nullptr.
1746   VPValue *getMask() const {
1747     // Mask is optional and therefore the last operand.
1748     return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
1749   }
1750 
1751   /// Returns true if this recipe is a store.
1752   bool isStore() const { return isa<StoreInst>(Ingredient); }
1753 
1754   /// Return the address accessed by this recipe.
1755   VPValue *getStoredValue() const {
1756     assert(isStore() && "Stored value only available for store instructions");
1757     return getOperand(1); // Stored value is the 2nd, mandatory operand.
1758   }
1759 
1760   // Return whether the loaded-from / stored-to addresses are consecutive.
1761   bool isConsecutive() const { return Consecutive; }
1762 
1763   // Return whether the consecutive loaded/stored addresses are in reverse
1764   // order.
1765   bool isReverse() const { return Reverse; }
1766 
1767   /// Generate the wide load/store.
1768   void execute(VPTransformState &State) override;
1769 
1770 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1771   /// Print the recipe.
1772   void print(raw_ostream &O, const Twine &Indent,
1773              VPSlotTracker &SlotTracker) const override;
1774 #endif
1775 
1776   /// Returns true if the recipe only uses the first lane of operand \p Op.
1777   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1778     assert(is_contained(operands(), Op) &&
1779            "Op must be an operand of the recipe");
1780 
1781     // Widened, consecutive memory operations only demand the first lane of
1782     // their address, unless the same operand is also stored. That latter can
1783     // happen with opaque pointers.
1784     return Op == getAddr() && isConsecutive() &&
1785            (!isStore() || Op != getStoredValue());
1786   }
1787 
1788   Instruction &getIngredient() const { return Ingredient; }
1789 };
1790 
1791 /// Recipe to expand a SCEV expression.
1792 class VPExpandSCEVRecipe : public VPRecipeBase, public VPValue {
1793   const SCEV *Expr;
1794   ScalarEvolution &SE;
1795 
1796 public:
1797   VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE)
1798       : VPRecipeBase(VPExpandSCEVSC, {}), VPValue(nullptr, this), Expr(Expr),
1799         SE(SE) {}
1800 
1801   ~VPExpandSCEVRecipe() override = default;
1802 
1803   /// Method to support type inquiry through isa, cast, and dyn_cast.
1804   static inline bool classof(const VPDef *D) {
1805     return D->getVPDefID() == VPExpandSCEVSC;
1806   }
1807 
1808   /// Generate a canonical vector induction variable of the vector loop, with
1809   void execute(VPTransformState &State) override;
1810 
1811 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1812   /// Print the recipe.
1813   void print(raw_ostream &O, const Twine &Indent,
1814              VPSlotTracker &SlotTracker) const override;
1815 #endif
1816 
1817   const SCEV *getSCEV() const { return Expr; }
1818 };
1819 
1820 /// Canonical scalar induction phi of the vector loop. Starting at the specified
1821 /// start value (either 0 or the resume value when vectorizing the epilogue
1822 /// loop). VPWidenCanonicalIVRecipe represents the vector version of the
1823 /// canonical induction variable.
1824 class VPCanonicalIVPHIRecipe : public VPHeaderPHIRecipe {
1825   DebugLoc DL;
1826 
1827 public:
1828   VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL)
1829       : VPHeaderPHIRecipe(VPValue::VPVCanonicalIVPHISC, VPCanonicalIVPHISC,
1830                           nullptr, StartV),
1831         DL(DL) {}
1832 
1833   ~VPCanonicalIVPHIRecipe() override = default;
1834 
1835   /// Method to support type inquiry through isa, cast, and dyn_cast.
1836   static inline bool classof(const VPDef *D) {
1837     return D->getVPDefID() == VPCanonicalIVPHISC;
1838   }
1839   static inline bool classof(const VPHeaderPHIRecipe *D) {
1840     return D->getVPDefID() == VPCanonicalIVPHISC;
1841   }
1842   static inline bool classof(const VPValue *V) {
1843     return V->getVPValueID() == VPValue::VPVCanonicalIVPHISC;
1844   }
1845 
1846   /// Generate the canonical scalar induction phi of the vector loop.
1847   void execute(VPTransformState &State) override;
1848 
1849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1850   /// Print the recipe.
1851   void print(raw_ostream &O, const Twine &Indent,
1852              VPSlotTracker &SlotTracker) const override;
1853 #endif
1854 
1855   /// Returns the scalar type of the induction.
1856   const Type *getScalarType() const {
1857     return getOperand(0)->getLiveInIRValue()->getType();
1858   }
1859 
1860   /// Returns true if the recipe only uses the first lane of operand \p Op.
1861   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1862     assert(is_contained(operands(), Op) &&
1863            "Op must be an operand of the recipe");
1864     return true;
1865   }
1866 };
1867 
1868 /// A Recipe for widening the canonical induction variable of the vector loop.
1869 class VPWidenCanonicalIVRecipe : public VPRecipeBase, public VPValue {
1870 public:
1871   VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV)
1872       : VPRecipeBase(VPWidenCanonicalIVSC, {CanonicalIV}),
1873         VPValue(VPValue::VPVWidenCanonicalIVSC, nullptr, this) {}
1874 
1875   ~VPWidenCanonicalIVRecipe() override = default;
1876 
1877   /// Method to support type inquiry through isa, cast, and dyn_cast.
1878   static inline bool classof(const VPDef *D) {
1879     return D->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1880   }
1881 
1882   /// Extra classof implementations to allow directly casting from VPUser ->
1883   /// VPWidenCanonicalIVRecipe.
1884   static inline bool classof(const VPUser *U) {
1885     auto *R = dyn_cast<VPRecipeBase>(U);
1886     return R && R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1887   }
1888   static inline bool classof(const VPRecipeBase *R) {
1889     return R->getVPDefID() == VPRecipeBase::VPWidenCanonicalIVSC;
1890   }
1891 
1892   /// Generate a canonical vector induction variable of the vector loop, with
1893   /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
1894   /// step = <VF*UF, VF*UF, ..., VF*UF>.
1895   void execute(VPTransformState &State) override;
1896 
1897 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1898   /// Print the recipe.
1899   void print(raw_ostream &O, const Twine &Indent,
1900              VPSlotTracker &SlotTracker) const override;
1901 #endif
1902 
1903   /// Returns the scalar type of the induction.
1904   const Type *getScalarType() const {
1905     return cast<VPCanonicalIVPHIRecipe>(getOperand(0)->getDef())
1906         ->getScalarType();
1907   }
1908 };
1909 
1910 /// A recipe for handling phi nodes of integer and floating-point inductions,
1911 /// producing their scalar values.
1912 class VPScalarIVStepsRecipe : public VPRecipeBase, public VPValue {
1913   /// Scalar type to use for the generated values.
1914   Type *Ty;
1915   /// If not nullptr, truncate the generated values to TruncToTy.
1916   Type *TruncToTy;
1917   const InductionDescriptor &IndDesc;
1918 
1919 public:
1920   VPScalarIVStepsRecipe(Type *Ty, const InductionDescriptor &IndDesc,
1921                         VPValue *CanonicalIV, VPValue *Start, VPValue *Step,
1922                         Type *TruncToTy)
1923       : VPRecipeBase(VPScalarIVStepsSC, {CanonicalIV, Start, Step}),
1924         VPValue(nullptr, this), Ty(Ty), TruncToTy(TruncToTy), IndDesc(IndDesc) {
1925   }
1926 
1927   ~VPScalarIVStepsRecipe() override = default;
1928 
1929   /// Method to support type inquiry through isa, cast, and dyn_cast.
1930   static inline bool classof(const VPDef *D) {
1931     return D->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1932   }
1933   /// Extra classof implementations to allow directly casting from VPUser ->
1934   /// VPScalarIVStepsRecipe.
1935   static inline bool classof(const VPUser *U) {
1936     auto *R = dyn_cast<VPRecipeBase>(U);
1937     return R && R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1938   }
1939   static inline bool classof(const VPRecipeBase *R) {
1940     return R->getVPDefID() == VPRecipeBase::VPScalarIVStepsSC;
1941   }
1942 
1943   /// Generate the scalarized versions of the phi node as needed by their users.
1944   void execute(VPTransformState &State) override;
1945 
1946 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1947   /// Print the recipe.
1948   void print(raw_ostream &O, const Twine &Indent,
1949              VPSlotTracker &SlotTracker) const override;
1950 #endif
1951 
1952   /// Returns true if the induction is canonical, i.e. starting at 0 and
1953   /// incremented by UF * VF (= the original IV is incremented by 1).
1954   bool isCanonical() const;
1955 
1956   VPCanonicalIVPHIRecipe *getCanonicalIV() const;
1957   VPValue *getStartValue() const { return getOperand(1); }
1958   VPValue *getStepValue() const { return getOperand(2); }
1959 
1960   /// Returns true if the recipe only uses the first lane of operand \p Op.
1961   bool onlyFirstLaneUsed(const VPValue *Op) const override {
1962     assert(is_contained(operands(), Op) &&
1963            "Op must be an operand of the recipe");
1964     return true;
1965   }
1966 };
1967 
1968 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1969 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1970 /// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
1971 class VPBasicBlock : public VPBlockBase {
1972 public:
1973   using RecipeListTy = iplist<VPRecipeBase>;
1974 
1975 private:
1976   /// The VPRecipes held in the order of output instructions to generate.
1977   RecipeListTy Recipes;
1978 
1979 public:
1980   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1981       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1982     if (Recipe)
1983       appendRecipe(Recipe);
1984   }
1985 
1986   ~VPBasicBlock() override {
1987     while (!Recipes.empty())
1988       Recipes.pop_back();
1989   }
1990 
1991   /// Instruction iterators...
1992   using iterator = RecipeListTy::iterator;
1993   using const_iterator = RecipeListTy::const_iterator;
1994   using reverse_iterator = RecipeListTy::reverse_iterator;
1995   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1996 
1997   //===--------------------------------------------------------------------===//
1998   /// Recipe iterator methods
1999   ///
2000   inline iterator begin() { return Recipes.begin(); }
2001   inline const_iterator begin() const { return Recipes.begin(); }
2002   inline iterator end() { return Recipes.end(); }
2003   inline const_iterator end() const { return Recipes.end(); }
2004 
2005   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
2006   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
2007   inline reverse_iterator rend() { return Recipes.rend(); }
2008   inline const_reverse_iterator rend() const { return Recipes.rend(); }
2009 
2010   inline size_t size() const { return Recipes.size(); }
2011   inline bool empty() const { return Recipes.empty(); }
2012   inline const VPRecipeBase &front() const { return Recipes.front(); }
2013   inline VPRecipeBase &front() { return Recipes.front(); }
2014   inline const VPRecipeBase &back() const { return Recipes.back(); }
2015   inline VPRecipeBase &back() { return Recipes.back(); }
2016 
2017   /// Returns a reference to the list of recipes.
2018   RecipeListTy &getRecipeList() { return Recipes; }
2019 
2020   /// Returns a pointer to a member of the recipe list.
2021   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
2022     return &VPBasicBlock::Recipes;
2023   }
2024 
2025   /// Method to support type inquiry through isa, cast, and dyn_cast.
2026   static inline bool classof(const VPBlockBase *V) {
2027     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
2028   }
2029 
2030   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
2031     assert(Recipe && "No recipe to append.");
2032     assert(!Recipe->Parent && "Recipe already in VPlan");
2033     Recipe->Parent = this;
2034     Recipes.insert(InsertPt, Recipe);
2035   }
2036 
2037   /// Augment the existing recipes of a VPBasicBlock with an additional
2038   /// \p Recipe as the last recipe.
2039   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
2040 
2041   /// The method which generates the output IR instructions that correspond to
2042   /// this VPBasicBlock, thereby "executing" the VPlan.
2043   void execute(struct VPTransformState *State) override;
2044 
2045   /// Return the position of the first non-phi node recipe in the block.
2046   iterator getFirstNonPhi();
2047 
2048   /// Returns an iterator range over the PHI-like recipes in the block.
2049   iterator_range<iterator> phis() {
2050     return make_range(begin(), getFirstNonPhi());
2051   }
2052 
2053   void dropAllReferences(VPValue *NewValue) override;
2054 
2055   /// Split current block at \p SplitAt by inserting a new block between the
2056   /// current block and its successors and moving all recipes starting at
2057   /// SplitAt to the new block. Returns the new block.
2058   VPBasicBlock *splitAt(iterator SplitAt);
2059 
2060   VPRegionBlock *getEnclosingLoopRegion();
2061 
2062 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2063   /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
2064   /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
2065   ///
2066   /// Note that the numbering is applied to the whole VPlan, so printing
2067   /// individual blocks is consistent with the whole VPlan printing.
2068   void print(raw_ostream &O, const Twine &Indent,
2069              VPSlotTracker &SlotTracker) const override;
2070   using VPBlockBase::print; // Get the print(raw_stream &O) version.
2071 #endif
2072 
2073   /// If the block has multiple successors, return the branch recipe terminating
2074   /// the block. If there are no or only a single successor, return nullptr;
2075   VPRecipeBase *getTerminator();
2076   const VPRecipeBase *getTerminator() const;
2077 
2078   /// Returns true if the block is exiting it's parent region.
2079   bool isExiting() const;
2080 
2081 private:
2082   /// Create an IR BasicBlock to hold the output instructions generated by this
2083   /// VPBasicBlock, and return it. Update the CFGState accordingly.
2084   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
2085 };
2086 
2087 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
2088 /// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
2089 /// A VPRegionBlock may indicate that its contents are to be replicated several
2090 /// times. This is designed to support predicated scalarization, in which a
2091 /// scalar if-then code structure needs to be generated VF * UF times. Having
2092 /// this replication indicator helps to keep a single model for multiple
2093 /// candidate VF's. The actual replication takes place only once the desired VF
2094 /// and UF have been determined.
2095 class VPRegionBlock : public VPBlockBase {
2096   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
2097   VPBlockBase *Entry;
2098 
2099   /// Hold the Single Exiting block of the SESE region modelled by the
2100   /// VPRegionBlock.
2101   VPBlockBase *Exiting;
2102 
2103   /// An indicator whether this region is to generate multiple replicated
2104   /// instances of output IR corresponding to its VPBlockBases.
2105   bool IsReplicator;
2106 
2107 public:
2108   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
2109                 const std::string &Name = "", bool IsReplicator = false)
2110       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting),
2111         IsReplicator(IsReplicator) {
2112     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
2113     assert(Exiting->getSuccessors().empty() && "Exit block has successors.");
2114     Entry->setParent(this);
2115     Exiting->setParent(this);
2116   }
2117   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
2118       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr),
2119         IsReplicator(IsReplicator) {}
2120 
2121   ~VPRegionBlock() override {
2122     if (Entry) {
2123       VPValue DummyValue;
2124       Entry->dropAllReferences(&DummyValue);
2125       deleteCFG(Entry);
2126     }
2127   }
2128 
2129   /// Method to support type inquiry through isa, cast, and dyn_cast.
2130   static inline bool classof(const VPBlockBase *V) {
2131     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
2132   }
2133 
2134   const VPBlockBase *getEntry() const { return Entry; }
2135   VPBlockBase *getEntry() { return Entry; }
2136 
2137   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
2138   /// EntryBlock must have no predecessors.
2139   void setEntry(VPBlockBase *EntryBlock) {
2140     assert(EntryBlock->getPredecessors().empty() &&
2141            "Entry block cannot have predecessors.");
2142     Entry = EntryBlock;
2143     EntryBlock->setParent(this);
2144   }
2145 
2146   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
2147   // specific interface of llvm::Function, instead of using
2148   // GraphTraints::getEntryNode. We should add a new template parameter to
2149   // DominatorTreeBase representing the Graph type.
2150   VPBlockBase &front() const { return *Entry; }
2151 
2152   const VPBlockBase *getExiting() const { return Exiting; }
2153   VPBlockBase *getExiting() { return Exiting; }
2154 
2155   /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
2156   /// ExitingBlock must have no successors.
2157   void setExiting(VPBlockBase *ExitingBlock) {
2158     assert(ExitingBlock->getSuccessors().empty() &&
2159            "Exit block cannot have successors.");
2160     Exiting = ExitingBlock;
2161     ExitingBlock->setParent(this);
2162   }
2163 
2164   /// Returns the pre-header VPBasicBlock of the loop region.
2165   VPBasicBlock *getPreheaderVPBB() {
2166     assert(!isReplicator() && "should only get pre-header of loop regions");
2167     return getSinglePredecessor()->getExitingBasicBlock();
2168   }
2169 
2170   /// An indicator whether this region is to generate multiple replicated
2171   /// instances of output IR corresponding to its VPBlockBases.
2172   bool isReplicator() const { return IsReplicator; }
2173 
2174   /// The method which generates the output IR instructions that correspond to
2175   /// this VPRegionBlock, thereby "executing" the VPlan.
2176   void execute(struct VPTransformState *State) override;
2177 
2178   void dropAllReferences(VPValue *NewValue) override;
2179 
2180 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2181   /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
2182   /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
2183   /// consequtive numbers.
2184   ///
2185   /// Note that the numbering is applied to the whole VPlan, so printing
2186   /// individual regions is consistent with the whole VPlan printing.
2187   void print(raw_ostream &O, const Twine &Indent,
2188              VPSlotTracker &SlotTracker) const override;
2189   using VPBlockBase::print; // Get the print(raw_stream &O) version.
2190 #endif
2191 };
2192 
2193 //===----------------------------------------------------------------------===//
2194 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
2195 //===----------------------------------------------------------------------===//
2196 
2197 // The following set of template specializations implement GraphTraits to treat
2198 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
2199 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
2200 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
2201 // successors/predecessors but not to the blocks inside the region.
2202 
2203 template <> struct GraphTraits<VPBlockBase *> {
2204   using NodeRef = VPBlockBase *;
2205   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
2206 
2207   static NodeRef getEntryNode(NodeRef N) { return N; }
2208 
2209   static inline ChildIteratorType child_begin(NodeRef N) {
2210     return N->getSuccessors().begin();
2211   }
2212 
2213   static inline ChildIteratorType child_end(NodeRef N) {
2214     return N->getSuccessors().end();
2215   }
2216 };
2217 
2218 template <> struct GraphTraits<const VPBlockBase *> {
2219   using NodeRef = const VPBlockBase *;
2220   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
2221 
2222   static NodeRef getEntryNode(NodeRef N) { return N; }
2223 
2224   static inline ChildIteratorType child_begin(NodeRef N) {
2225     return N->getSuccessors().begin();
2226   }
2227 
2228   static inline ChildIteratorType child_end(NodeRef N) {
2229     return N->getSuccessors().end();
2230   }
2231 };
2232 
2233 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
2234 // of successors for the inverse traversal.
2235 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
2236   using NodeRef = VPBlockBase *;
2237   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
2238 
2239   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
2240 
2241   static inline ChildIteratorType child_begin(NodeRef N) {
2242     return N->getPredecessors().begin();
2243   }
2244 
2245   static inline ChildIteratorType child_end(NodeRef N) {
2246     return N->getPredecessors().end();
2247   }
2248 };
2249 
2250 // The following set of template specializations implement GraphTraits to
2251 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
2252 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
2253 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
2254 // there won't be automatic recursion into other VPBlockBases that turn to be
2255 // VPRegionBlocks.
2256 
2257 template <>
2258 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
2259   using GraphRef = VPRegionBlock *;
2260   using nodes_iterator = df_iterator<NodeRef>;
2261 
2262   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
2263 
2264   static nodes_iterator nodes_begin(GraphRef N) {
2265     return nodes_iterator::begin(N->getEntry());
2266   }
2267 
2268   static nodes_iterator nodes_end(GraphRef N) {
2269     // df_iterator::end() returns an empty iterator so the node used doesn't
2270     // matter.
2271     return nodes_iterator::end(N);
2272   }
2273 };
2274 
2275 template <>
2276 struct GraphTraits<const VPRegionBlock *>
2277     : public GraphTraits<const VPBlockBase *> {
2278   using GraphRef = const VPRegionBlock *;
2279   using nodes_iterator = df_iterator<NodeRef>;
2280 
2281   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
2282 
2283   static nodes_iterator nodes_begin(GraphRef N) {
2284     return nodes_iterator::begin(N->getEntry());
2285   }
2286 
2287   static nodes_iterator nodes_end(GraphRef N) {
2288     // df_iterator::end() returns an empty iterator so the node used doesn't
2289     // matter.
2290     return nodes_iterator::end(N);
2291   }
2292 };
2293 
2294 template <>
2295 struct GraphTraits<Inverse<VPRegionBlock *>>
2296     : public GraphTraits<Inverse<VPBlockBase *>> {
2297   using GraphRef = VPRegionBlock *;
2298   using nodes_iterator = df_iterator<NodeRef>;
2299 
2300   static NodeRef getEntryNode(Inverse<GraphRef> N) {
2301     return N.Graph->getExiting();
2302   }
2303 
2304   static nodes_iterator nodes_begin(GraphRef N) {
2305     return nodes_iterator::begin(N->getExiting());
2306   }
2307 
2308   static nodes_iterator nodes_end(GraphRef N) {
2309     // df_iterator::end() returns an empty iterator so the node used doesn't
2310     // matter.
2311     return nodes_iterator::end(N);
2312   }
2313 };
2314 
2315 /// Iterator to traverse all successors of a VPBlockBase node. This includes the
2316 /// entry node of VPRegionBlocks. Exit blocks of a region implicitly have their
2317 /// parent region's successors. This ensures all blocks in a region are visited
2318 /// before any blocks in a successor region when doing a reverse post-order
2319 // traversal of the graph.
2320 template <typename BlockPtrTy>
2321 class VPAllSuccessorsIterator
2322     : public iterator_facade_base<VPAllSuccessorsIterator<BlockPtrTy>,
2323                                   std::forward_iterator_tag, VPBlockBase> {
2324   BlockPtrTy Block;
2325   /// Index of the current successor. For VPBasicBlock nodes, this simply is the
2326   /// index for the successor array. For VPRegionBlock, SuccessorIdx == 0 is
2327   /// used for the region's entry block, and SuccessorIdx - 1 are the indices
2328   /// for the successor array.
2329   size_t SuccessorIdx;
2330 
2331   static BlockPtrTy getBlockWithSuccs(BlockPtrTy Current) {
2332     while (Current && Current->getNumSuccessors() == 0)
2333       Current = Current->getParent();
2334     return Current;
2335   }
2336 
2337   /// Templated helper to dereference successor \p SuccIdx of \p Block. Used by
2338   /// both the const and non-const operator* implementations.
2339   template <typename T1> static T1 deref(T1 Block, unsigned SuccIdx) {
2340     if (auto *R = dyn_cast<VPRegionBlock>(Block)) {
2341       if (SuccIdx == 0)
2342         return R->getEntry();
2343       SuccIdx--;
2344     }
2345 
2346     // For exit blocks, use the next parent region with successors.
2347     return getBlockWithSuccs(Block)->getSuccessors()[SuccIdx];
2348   }
2349 
2350 public:
2351   VPAllSuccessorsIterator(BlockPtrTy Block, size_t Idx = 0)
2352       : Block(Block), SuccessorIdx(Idx) {}
2353   VPAllSuccessorsIterator(const VPAllSuccessorsIterator &Other)
2354       : Block(Other.Block), SuccessorIdx(Other.SuccessorIdx) {}
2355 
2356   VPAllSuccessorsIterator &operator=(const VPAllSuccessorsIterator &R) {
2357     Block = R.Block;
2358     SuccessorIdx = R.SuccessorIdx;
2359     return *this;
2360   }
2361 
2362   static VPAllSuccessorsIterator end(BlockPtrTy Block) {
2363     BlockPtrTy ParentWithSuccs = getBlockWithSuccs(Block);
2364     unsigned NumSuccessors = ParentWithSuccs
2365                                  ? ParentWithSuccs->getNumSuccessors()
2366                                  : Block->getNumSuccessors();
2367 
2368     if (auto *R = dyn_cast<VPRegionBlock>(Block))
2369       return {R, NumSuccessors + 1};
2370     return {Block, NumSuccessors};
2371   }
2372 
2373   bool operator==(const VPAllSuccessorsIterator &R) const {
2374     return Block == R.Block && SuccessorIdx == R.SuccessorIdx;
2375   }
2376 
2377   const VPBlockBase *operator*() const { return deref(Block, SuccessorIdx); }
2378 
2379   BlockPtrTy operator*() { return deref(Block, SuccessorIdx); }
2380 
2381   VPAllSuccessorsIterator &operator++() {
2382     SuccessorIdx++;
2383     return *this;
2384   }
2385 
2386   VPAllSuccessorsIterator operator++(int X) {
2387     VPAllSuccessorsIterator Orig = *this;
2388     SuccessorIdx++;
2389     return Orig;
2390   }
2391 };
2392 
2393 /// Helper for GraphTraits specialization that traverses through VPRegionBlocks.
2394 template <typename BlockTy> class VPBlockRecursiveTraversalWrapper {
2395   BlockTy Entry;
2396 
2397 public:
2398   VPBlockRecursiveTraversalWrapper(BlockTy Entry) : Entry(Entry) {}
2399   BlockTy getEntry() { return Entry; }
2400 };
2401 
2402 /// GraphTraits specialization to recursively traverse VPBlockBase nodes,
2403 /// including traversing through VPRegionBlocks.  Exit blocks of a region
2404 /// implicitly have their parent region's successors. This ensures all blocks in
2405 /// a region are visited before any blocks in a successor region when doing a
2406 /// reverse post-order traversal of the graph.
2407 template <>
2408 struct GraphTraits<VPBlockRecursiveTraversalWrapper<VPBlockBase *>> {
2409   using NodeRef = VPBlockBase *;
2410   using ChildIteratorType = VPAllSuccessorsIterator<VPBlockBase *>;
2411 
2412   static NodeRef
2413   getEntryNode(VPBlockRecursiveTraversalWrapper<VPBlockBase *> N) {
2414     return N.getEntry();
2415   }
2416 
2417   static inline ChildIteratorType child_begin(NodeRef N) {
2418     return ChildIteratorType(N);
2419   }
2420 
2421   static inline ChildIteratorType child_end(NodeRef N) {
2422     return ChildIteratorType::end(N);
2423   }
2424 };
2425 
2426 template <>
2427 struct GraphTraits<VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> {
2428   using NodeRef = const VPBlockBase *;
2429   using ChildIteratorType = VPAllSuccessorsIterator<const VPBlockBase *>;
2430 
2431   static NodeRef
2432   getEntryNode(VPBlockRecursiveTraversalWrapper<const VPBlockBase *> N) {
2433     return N.getEntry();
2434   }
2435 
2436   static inline ChildIteratorType child_begin(NodeRef N) {
2437     return ChildIteratorType(N);
2438   }
2439 
2440   static inline ChildIteratorType child_end(NodeRef N) {
2441     return ChildIteratorType::end(N);
2442   }
2443 };
2444 
2445 /// VPlan models a candidate for vectorization, encoding various decisions take
2446 /// to produce efficient output IR, including which branches, basic-blocks and
2447 /// output IR instructions to generate, and their cost. VPlan holds a
2448 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
2449 /// VPBlock.
2450 class VPlan {
2451   friend class VPlanPrinter;
2452   friend class VPSlotTracker;
2453 
2454   /// Hold the single entry to the Hierarchical CFG of the VPlan.
2455   VPBlockBase *Entry;
2456 
2457   /// Holds the VFs applicable to this VPlan.
2458   SmallSetVector<ElementCount, 2> VFs;
2459 
2460   /// Holds the name of the VPlan, for printing.
2461   std::string Name;
2462 
2463   /// Holds all the external definitions created for this VPlan. External
2464   /// definitions must be immutable and hold a pointer to their underlying IR.
2465   DenseMap<Value *, VPValue *> VPExternalDefs;
2466 
2467   /// Represents the trip count of the original loop, for folding
2468   /// the tail.
2469   VPValue *TripCount = nullptr;
2470 
2471   /// Represents the backedge taken count of the original loop, for folding
2472   /// the tail. It equals TripCount - 1.
2473   VPValue *BackedgeTakenCount = nullptr;
2474 
2475   /// Represents the vector trip count.
2476   VPValue VectorTripCount;
2477 
2478   /// Holds a mapping between Values and their corresponding VPValue inside
2479   /// VPlan.
2480   Value2VPValueTy Value2VPValue;
2481 
2482   /// Contains all VPValues that been allocated by addVPValue directly and need
2483   /// to be free when the plan's destructor is called.
2484   SmallVector<VPValue *, 16> VPValuesToFree;
2485 
2486   /// Indicates whether it is safe use the Value2VPValue mapping or if the
2487   /// mapping cannot be used any longer, because it is stale.
2488   bool Value2VPValueEnabled = true;
2489 
2490   /// Values used outside the plan.
2491   MapVector<PHINode *, VPLiveOut *> LiveOuts;
2492 
2493 public:
2494   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {
2495     if (Entry)
2496       Entry->setPlan(this);
2497   }
2498 
2499   ~VPlan() {
2500     clearLiveOuts();
2501 
2502     if (Entry) {
2503       VPValue DummyValue;
2504       for (VPBlockBase *Block : depth_first(Entry))
2505         Block->dropAllReferences(&DummyValue);
2506 
2507       VPBlockBase::deleteCFG(Entry);
2508     }
2509     for (VPValue *VPV : VPValuesToFree)
2510       delete VPV;
2511     if (TripCount)
2512       delete TripCount;
2513     if (BackedgeTakenCount)
2514       delete BackedgeTakenCount;
2515     for (auto &P : VPExternalDefs)
2516       delete P.second;
2517   }
2518 
2519   /// Prepare the plan for execution, setting up the required live-in values.
2520   void prepareToExecute(Value *TripCount, Value *VectorTripCount,
2521                         Value *CanonicalIVStartValue, VPTransformState &State,
2522                         bool IsEpilogueVectorization);
2523 
2524   /// Generate the IR code for this VPlan.
2525   void execute(struct VPTransformState *State);
2526 
2527   VPBlockBase *getEntry() { return Entry; }
2528   const VPBlockBase *getEntry() const { return Entry; }
2529 
2530   VPBlockBase *setEntry(VPBlockBase *Block) {
2531     Entry = Block;
2532     Block->setPlan(this);
2533     return Entry;
2534   }
2535 
2536   /// The trip count of the original loop.
2537   VPValue *getOrCreateTripCount() {
2538     if (!TripCount)
2539       TripCount = new VPValue();
2540     return TripCount;
2541   }
2542 
2543   /// The backedge taken count of the original loop.
2544   VPValue *getOrCreateBackedgeTakenCount() {
2545     if (!BackedgeTakenCount)
2546       BackedgeTakenCount = new VPValue();
2547     return BackedgeTakenCount;
2548   }
2549 
2550   /// The vector trip count.
2551   VPValue &getVectorTripCount() { return VectorTripCount; }
2552 
2553   /// Mark the plan to indicate that using Value2VPValue is not safe any
2554   /// longer, because it may be stale.
2555   void disableValue2VPValue() { Value2VPValueEnabled = false; }
2556 
2557   void addVF(ElementCount VF) { VFs.insert(VF); }
2558 
2559   bool hasVF(ElementCount VF) { return VFs.count(VF); }
2560 
2561   const std::string &getName() const { return Name; }
2562 
2563   void setName(const Twine &newName) { Name = newName.str(); }
2564 
2565   /// Get the existing or add a new external definition for \p V.
2566   VPValue *getOrAddExternalDef(Value *V) {
2567     auto I = VPExternalDefs.insert({V, nullptr});
2568     if (I.second)
2569       I.first->second = new VPValue(V);
2570     return I.first->second;
2571   }
2572 
2573   void addVPValue(Value *V) {
2574     assert(Value2VPValueEnabled &&
2575            "IR value to VPValue mapping may be out of date!");
2576     assert(V && "Trying to add a null Value to VPlan");
2577     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
2578     VPValue *VPV = new VPValue(V);
2579     Value2VPValue[V] = VPV;
2580     VPValuesToFree.push_back(VPV);
2581   }
2582 
2583   void addVPValue(Value *V, VPValue *VPV) {
2584     assert(Value2VPValueEnabled && "Value2VPValue mapping may be out of date!");
2585     assert(V && "Trying to add a null Value to VPlan");
2586     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
2587     Value2VPValue[V] = VPV;
2588   }
2589 
2590   /// Returns the VPValue for \p V. \p OverrideAllowed can be used to disable
2591   /// checking whether it is safe to query VPValues using IR Values.
2592   VPValue *getVPValue(Value *V, bool OverrideAllowed = false) {
2593     assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) &&
2594            "Value2VPValue mapping may be out of date!");
2595     assert(V && "Trying to get the VPValue of a null Value");
2596     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
2597     return Value2VPValue[V];
2598   }
2599 
2600   /// Gets the VPValue or adds a new one (if none exists yet) for \p V. \p
2601   /// OverrideAllowed can be used to disable checking whether it is safe to
2602   /// query VPValues using IR Values.
2603   VPValue *getOrAddVPValue(Value *V, bool OverrideAllowed = false) {
2604     assert((OverrideAllowed || isa<Constant>(V) || Value2VPValueEnabled) &&
2605            "Value2VPValue mapping may be out of date!");
2606     assert(V && "Trying to get or add the VPValue of a null Value");
2607     if (!Value2VPValue.count(V))
2608       addVPValue(V);
2609     return getVPValue(V);
2610   }
2611 
2612   void removeVPValueFor(Value *V) {
2613     assert(Value2VPValueEnabled &&
2614            "IR value to VPValue mapping may be out of date!");
2615     Value2VPValue.erase(V);
2616   }
2617 
2618 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2619   /// Print this VPlan to \p O.
2620   void print(raw_ostream &O) const;
2621 
2622   /// Print this VPlan in DOT format to \p O.
2623   void printDOT(raw_ostream &O) const;
2624 
2625   /// Dump the plan to stderr (for debugging).
2626   LLVM_DUMP_METHOD void dump() const;
2627 #endif
2628 
2629   /// Returns a range mapping the values the range \p Operands to their
2630   /// corresponding VPValues.
2631   iterator_range<mapped_iterator<Use *, std::function<VPValue *(Value *)>>>
2632   mapToVPValues(User::op_range Operands) {
2633     std::function<VPValue *(Value *)> Fn = [this](Value *Op) {
2634       return getOrAddVPValue(Op);
2635     };
2636     return map_range(Operands, Fn);
2637   }
2638 
2639   /// Returns true if \p VPV is uniform after vectorization.
2640   bool isUniformAfterVectorization(VPValue *VPV) const {
2641     auto RepR = dyn_cast_or_null<VPReplicateRecipe>(VPV->getDef());
2642     return !VPV->getDef() || (RepR && RepR->isUniform());
2643   }
2644 
2645   /// Returns the VPRegionBlock of the vector loop.
2646   VPRegionBlock *getVectorLoopRegion() {
2647     return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
2648   }
2649   const VPRegionBlock *getVectorLoopRegion() const {
2650     return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
2651   }
2652 
2653   /// Returns the canonical induction recipe of the vector loop.
2654   VPCanonicalIVPHIRecipe *getCanonicalIV() {
2655     VPBasicBlock *EntryVPBB = getVectorLoopRegion()->getEntryBasicBlock();
2656     if (EntryVPBB->empty()) {
2657       // VPlan native path.
2658       EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor());
2659     }
2660     return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin());
2661   }
2662 
2663   void addLiveOut(PHINode *PN, VPValue *V);
2664 
2665   void clearLiveOuts() {
2666     for (auto &KV : LiveOuts)
2667       delete KV.second;
2668     LiveOuts.clear();
2669   }
2670 
2671   void removeLiveOut(PHINode *PN) {
2672     delete LiveOuts[PN];
2673     LiveOuts.erase(PN);
2674   }
2675 
2676   const MapVector<PHINode *, VPLiveOut *> &getLiveOuts() const {
2677     return LiveOuts;
2678   }
2679 
2680 private:
2681   /// Add to the given dominator tree the header block and every new basic block
2682   /// that was created between it and the latch block, inclusive.
2683   static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopLatchBB,
2684                                   BasicBlock *LoopPreHeaderBB,
2685                                   BasicBlock *LoopExitBB);
2686 };
2687 
2688 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2689 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
2690 /// indented and follows the dot format.
2691 class VPlanPrinter {
2692   raw_ostream &OS;
2693   const VPlan &Plan;
2694   unsigned Depth = 0;
2695   unsigned TabWidth = 2;
2696   std::string Indent;
2697   unsigned BID = 0;
2698   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
2699 
2700   VPSlotTracker SlotTracker;
2701 
2702   /// Handle indentation.
2703   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
2704 
2705   /// Print a given \p Block of the Plan.
2706   void dumpBlock(const VPBlockBase *Block);
2707 
2708   /// Print the information related to the CFG edges going out of a given
2709   /// \p Block, followed by printing the successor blocks themselves.
2710   void dumpEdges(const VPBlockBase *Block);
2711 
2712   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
2713   /// its successor blocks.
2714   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
2715 
2716   /// Print a given \p Region of the Plan.
2717   void dumpRegion(const VPRegionBlock *Region);
2718 
2719   unsigned getOrCreateBID(const VPBlockBase *Block) {
2720     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
2721   }
2722 
2723   Twine getOrCreateName(const VPBlockBase *Block);
2724 
2725   Twine getUID(const VPBlockBase *Block);
2726 
2727   /// Print the information related to a CFG edge between two VPBlockBases.
2728   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
2729                 const Twine &Label);
2730 
2731 public:
2732   VPlanPrinter(raw_ostream &O, const VPlan &P)
2733       : OS(O), Plan(P), SlotTracker(&P) {}
2734 
2735   LLVM_DUMP_METHOD void dump();
2736 };
2737 
2738 struct VPlanIngredient {
2739   const Value *V;
2740 
2741   VPlanIngredient(const Value *V) : V(V) {}
2742 
2743   void print(raw_ostream &O) const;
2744 };
2745 
2746 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
2747   I.print(OS);
2748   return OS;
2749 }
2750 
2751 inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
2752   Plan.print(OS);
2753   return OS;
2754 }
2755 #endif
2756 
2757 //===----------------------------------------------------------------------===//
2758 // VPlan Utilities
2759 //===----------------------------------------------------------------------===//
2760 
2761 /// Class that provides utilities for VPBlockBases in VPlan.
2762 class VPBlockUtils {
2763 public:
2764   VPBlockUtils() = delete;
2765 
2766   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
2767   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
2768   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
2769   /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must
2770   /// have neither successors nor predecessors.
2771   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
2772     assert(NewBlock->getSuccessors().empty() &&
2773            NewBlock->getPredecessors().empty() &&
2774            "Can't insert new block with predecessors or successors.");
2775     NewBlock->setParent(BlockPtr->getParent());
2776     SmallVector<VPBlockBase *> Succs(BlockPtr->successors());
2777     for (VPBlockBase *Succ : Succs) {
2778       disconnectBlocks(BlockPtr, Succ);
2779       connectBlocks(NewBlock, Succ);
2780     }
2781     connectBlocks(BlockPtr, NewBlock);
2782   }
2783 
2784   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
2785   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
2786   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
2787   /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
2788   /// and \p IfTrue and \p IfFalse must have neither successors nor
2789   /// predecessors.
2790   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
2791                                    VPBlockBase *BlockPtr) {
2792     assert(IfTrue->getSuccessors().empty() &&
2793            "Can't insert IfTrue with successors.");
2794     assert(IfFalse->getSuccessors().empty() &&
2795            "Can't insert IfFalse with successors.");
2796     BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
2797     IfTrue->setPredecessors({BlockPtr});
2798     IfFalse->setPredecessors({BlockPtr});
2799     IfTrue->setParent(BlockPtr->getParent());
2800     IfFalse->setParent(BlockPtr->getParent());
2801   }
2802 
2803   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
2804   /// the successors of \p From and \p From to the predecessors of \p To. Both
2805   /// VPBlockBases must have the same parent, which can be null. Both
2806   /// VPBlockBases can be already connected to other VPBlockBases.
2807   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
2808     assert((From->getParent() == To->getParent()) &&
2809            "Can't connect two block with different parents");
2810     assert(From->getNumSuccessors() < 2 &&
2811            "Blocks can't have more than two successors.");
2812     From->appendSuccessor(To);
2813     To->appendPredecessor(From);
2814   }
2815 
2816   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
2817   /// from the successors of \p From and \p From from the predecessors of \p To.
2818   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
2819     assert(To && "Successor to disconnect is null.");
2820     From->removeSuccessor(To);
2821     To->removePredecessor(From);
2822   }
2823 
2824   /// Try to merge \p Block into its single predecessor, if \p Block is a
2825   /// VPBasicBlock and its predecessor has a single successor. Returns a pointer
2826   /// to the predecessor \p Block was merged into or nullptr otherwise.
2827   static VPBasicBlock *tryToMergeBlockIntoPredecessor(VPBlockBase *Block) {
2828     auto *VPBB = dyn_cast<VPBasicBlock>(Block);
2829     auto *PredVPBB =
2830         dyn_cast_or_null<VPBasicBlock>(Block->getSinglePredecessor());
2831     if (!VPBB || !PredVPBB || PredVPBB->getNumSuccessors() != 1)
2832       return nullptr;
2833 
2834     for (VPRecipeBase &R : make_early_inc_range(*VPBB))
2835       R.moveBefore(*PredVPBB, PredVPBB->end());
2836     VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
2837     auto *ParentRegion = cast<VPRegionBlock>(Block->getParent());
2838     if (ParentRegion->getExiting() == Block)
2839       ParentRegion->setExiting(PredVPBB);
2840     SmallVector<VPBlockBase *> Successors(Block->successors());
2841     for (auto *Succ : Successors) {
2842       VPBlockUtils::disconnectBlocks(Block, Succ);
2843       VPBlockUtils::connectBlocks(PredVPBB, Succ);
2844     }
2845     delete Block;
2846     return PredVPBB;
2847   }
2848 
2849   /// Return an iterator range over \p Range which only includes \p BlockTy
2850   /// blocks. The accesses are casted to \p BlockTy.
2851   template <typename BlockTy, typename T>
2852   static auto blocksOnly(const T &Range) {
2853     // Create BaseTy with correct const-ness based on BlockTy.
2854     using BaseTy =
2855         typename std::conditional<std::is_const<BlockTy>::value,
2856                                   const VPBlockBase, VPBlockBase>::type;
2857 
2858     // We need to first create an iterator range over (const) BlocktTy & instead
2859     // of (const) BlockTy * for filter_range to work properly.
2860     auto Mapped =
2861         map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; });
2862     auto Filter = make_filter_range(
2863         Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); });
2864     return map_range(Filter, [](BaseTy &Block) -> BlockTy * {
2865       return cast<BlockTy>(&Block);
2866     });
2867   }
2868 };
2869 
2870 class VPInterleavedAccessInfo {
2871   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
2872       InterleaveGroupMap;
2873 
2874   /// Type for mapping of instruction based interleave groups to VPInstruction
2875   /// interleave groups
2876   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
2877                              InterleaveGroup<VPInstruction> *>;
2878 
2879   /// Recursively \p Region and populate VPlan based interleave groups based on
2880   /// \p IAI.
2881   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
2882                    InterleavedAccessInfo &IAI);
2883   /// Recursively traverse \p Block and populate VPlan based interleave groups
2884   /// based on \p IAI.
2885   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
2886                   InterleavedAccessInfo &IAI);
2887 
2888 public:
2889   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
2890 
2891   ~VPInterleavedAccessInfo() {
2892     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
2893     // Avoid releasing a pointer twice.
2894     for (auto &I : InterleaveGroupMap)
2895       DelSet.insert(I.second);
2896     for (auto *Ptr : DelSet)
2897       delete Ptr;
2898   }
2899 
2900   /// Get the interleave group that \p Instr belongs to.
2901   ///
2902   /// \returns nullptr if doesn't have such group.
2903   InterleaveGroup<VPInstruction> *
2904   getInterleaveGroup(VPInstruction *Instr) const {
2905     return InterleaveGroupMap.lookup(Instr);
2906   }
2907 };
2908 
2909 /// Class that maps (parts of) an existing VPlan to trees of combined
2910 /// VPInstructions.
2911 class VPlanSlp {
2912   enum class OpMode { Failed, Load, Opcode };
2913 
2914   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
2915   /// DenseMap keys.
2916   struct BundleDenseMapInfo {
2917     static SmallVector<VPValue *, 4> getEmptyKey() {
2918       return {reinterpret_cast<VPValue *>(-1)};
2919     }
2920 
2921     static SmallVector<VPValue *, 4> getTombstoneKey() {
2922       return {reinterpret_cast<VPValue *>(-2)};
2923     }
2924 
2925     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
2926       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2927     }
2928 
2929     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
2930                         const SmallVector<VPValue *, 4> &RHS) {
2931       return LHS == RHS;
2932     }
2933   };
2934 
2935   /// Mapping of values in the original VPlan to a combined VPInstruction.
2936   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
2937       BundleToCombined;
2938 
2939   VPInterleavedAccessInfo &IAI;
2940 
2941   /// Basic block to operate on. For now, only instructions in a single BB are
2942   /// considered.
2943   const VPBasicBlock &BB;
2944 
2945   /// Indicates whether we managed to combine all visited instructions or not.
2946   bool CompletelySLP = true;
2947 
2948   /// Width of the widest combined bundle in bits.
2949   unsigned WidestBundleBits = 0;
2950 
2951   using MultiNodeOpTy =
2952       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
2953 
2954   // Input operand bundles for the current multi node. Each multi node operand
2955   // bundle contains values not matching the multi node's opcode. They will
2956   // be reordered in reorderMultiNodeOps, once we completed building a
2957   // multi node.
2958   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
2959 
2960   /// Indicates whether we are building a multi node currently.
2961   bool MultiNodeActive = false;
2962 
2963   /// Check if we can vectorize Operands together.
2964   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
2965 
2966   /// Add combined instruction \p New for the bundle \p Operands.
2967   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
2968 
2969   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
2970   VPInstruction *markFailed();
2971 
2972   /// Reorder operands in the multi node to maximize sequential memory access
2973   /// and commutative operations.
2974   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
2975 
2976   /// Choose the best candidate to use for the lane after \p Last. The set of
2977   /// candidates to choose from are values with an opcode matching \p Last's
2978   /// or loads consecutive to \p Last.
2979   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
2980                                        SmallPtrSetImpl<VPValue *> &Candidates,
2981                                        VPInterleavedAccessInfo &IAI);
2982 
2983 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2984   /// Print bundle \p Values to dbgs().
2985   void dumpBundle(ArrayRef<VPValue *> Values);
2986 #endif
2987 
2988 public:
2989   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
2990 
2991   ~VPlanSlp() = default;
2992 
2993   /// Tries to build an SLP tree rooted at \p Operands and returns a
2994   /// VPInstruction combining \p Operands, if they can be combined.
2995   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
2996 
2997   /// Return the width of the widest combined bundle in bits.
2998   unsigned getWidestBundleBits() const { return WidestBundleBits; }
2999 
3000   /// Return true if all visited instruction can be combined.
3001   bool isCompletelySLP() const { return CompletelySLP; }
3002 };
3003 
3004 namespace vputils {
3005 
3006 /// Returns true if only the first lane of \p Def is used.
3007 bool onlyFirstLaneUsed(VPValue *Def);
3008 
3009 /// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
3010 /// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
3011 /// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
3012 /// pre-header already contains a recipe expanding \p Expr, return it. If not,
3013 /// create a new one.
3014 VPValue *getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
3015                                        ScalarEvolution &SE);
3016 } // end namespace vputils
3017 
3018 } // end namespace llvm
3019 
3020 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
3021