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