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