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