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