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/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/ADT/ilist.h"
39 #include "llvm/ADT/ilist_node.h"
40 #include "llvm/Analysis/VectorUtils.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstddef>
45 #include <map>
46 #include <string>
47 
48 namespace llvm {
49 
50 class LoopVectorizationLegality;
51 class LoopVectorizationCostModel;
52 class BasicBlock;
53 class DominatorTree;
54 class InnerLoopVectorizer;
55 template <class T> class InterleaveGroup;
56 class LoopInfo;
57 class raw_ostream;
58 class Value;
59 class VPBasicBlock;
60 class VPRegionBlock;
61 class VPlan;
62 class VPlanSlp;
63 
64 /// A range of powers-of-2 vectorization factors with fixed start and
65 /// adjustable end. The range includes start and excludes end, e.g.,:
66 /// [1, 9) = {1, 2, 4, 8}
67 struct VFRange {
68   // A power of 2.
69   const unsigned Start;
70 
71   // Need not be a power of 2. If End <= Start range is empty.
72   unsigned End;
73 };
74 
75 using VPlanPtr = std::unique_ptr<VPlan>;
76 
77 /// In what follows, the term "input IR" refers to code that is fed into the
78 /// vectorizer whereas the term "output IR" refers to code that is generated by
79 /// the vectorizer.
80 
81 /// VPIteration represents a single point in the iteration space of the output
82 /// (vectorized and/or unrolled) IR loop.
83 struct VPIteration {
84   /// in [0..UF)
85   unsigned Part;
86 
87   /// in [0..VF)
88   unsigned Lane;
89 };
90 
91 /// This is a helper struct for maintaining vectorization state. It's used for
92 /// mapping values from the original loop to their corresponding values in
93 /// the new loop. Two mappings are maintained: one for vectorized values and
94 /// one for scalarized values. Vectorized values are represented with UF
95 /// vector values in the new loop, and scalarized values are represented with
96 /// UF x VF scalar values in the new loop. UF and VF are the unroll and
97 /// vectorization factors, respectively.
98 ///
99 /// Entries can be added to either map with setVectorValue and setScalarValue,
100 /// which assert that an entry was not already added before. If an entry is to
101 /// replace an existing one, call resetVectorValue and resetScalarValue. This is
102 /// currently needed to modify the mapped values during "fix-up" operations that
103 /// occur once the first phase of widening is complete. These operations include
104 /// type truncation and the second phase of recurrence widening.
105 ///
106 /// Entries from either map can be retrieved using the getVectorValue and
107 /// getScalarValue functions, which assert that the desired value exists.
108 struct VectorizerValueMap {
109   friend struct VPTransformState;
110 
111 private:
112   /// The unroll factor. Each entry in the vector map contains UF vector values.
113   unsigned UF;
114 
115   /// The vectorization factor. Each entry in the scalar map contains UF x VF
116   /// scalar values.
117   unsigned VF;
118 
119   /// The vector and scalar map storage. We use std::map and not DenseMap
120   /// because insertions to DenseMap invalidate its iterators.
121   using VectorParts = SmallVector<Value *, 2>;
122   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
123   std::map<Value *, VectorParts> VectorMapStorage;
124   std::map<Value *, ScalarParts> ScalarMapStorage;
125 
126 public:
127   /// Construct an empty map with the given unroll and vectorization factors.
128   VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
129 
130   /// \return True if the map has any vector entry for \p Key.
131   bool hasAnyVectorValue(Value *Key) const {
132     return VectorMapStorage.count(Key);
133   }
134 
135   /// \return True if the map has a vector entry for \p Key and \p Part.
136   bool hasVectorValue(Value *Key, unsigned Part) const {
137     assert(Part < UF && "Queried Vector Part is too large.");
138     if (!hasAnyVectorValue(Key))
139       return false;
140     const VectorParts &Entry = VectorMapStorage.find(Key)->second;
141     assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
142     return Entry[Part] != nullptr;
143   }
144 
145   /// \return True if the map has any scalar entry for \p Key.
146   bool hasAnyScalarValue(Value *Key) const {
147     return ScalarMapStorage.count(Key);
148   }
149 
150   /// \return True if the map has a scalar entry for \p Key and \p Instance.
151   bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
152     assert(Instance.Part < UF && "Queried Scalar Part is too large.");
153     assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
154     if (!hasAnyScalarValue(Key))
155       return false;
156     const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
157     assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
158     assert(Entry[Instance.Part].size() == VF &&
159            "ScalarParts has wrong dimensions.");
160     return Entry[Instance.Part][Instance.Lane] != nullptr;
161   }
162 
163   /// Retrieve the existing vector value that corresponds to \p Key and
164   /// \p Part.
165   Value *getVectorValue(Value *Key, unsigned Part) {
166     assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
167     return VectorMapStorage[Key][Part];
168   }
169 
170   /// Retrieve the existing scalar value that corresponds to \p Key and
171   /// \p Instance.
172   Value *getScalarValue(Value *Key, const VPIteration &Instance) {
173     assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
174     return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
175   }
176 
177   /// Set a vector value associated with \p Key and \p Part. Assumes such a
178   /// value is not already set. If it is, use resetVectorValue() instead.
179   void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
180     assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
181     if (!VectorMapStorage.count(Key)) {
182       VectorParts Entry(UF);
183       VectorMapStorage[Key] = Entry;
184     }
185     VectorMapStorage[Key][Part] = Vector;
186   }
187 
188   /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
189   /// value is not already set.
190   void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
191     assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
192     if (!ScalarMapStorage.count(Key)) {
193       ScalarParts Entry(UF);
194       // TODO: Consider storing uniform values only per-part, as they occupy
195       //       lane 0 only, keeping the other VF-1 redundant entries null.
196       for (unsigned Part = 0; Part < UF; ++Part)
197         Entry[Part].resize(VF, nullptr);
198       ScalarMapStorage[Key] = Entry;
199     }
200     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
201   }
202 
203   /// Reset the vector value associated with \p Key for the given \p Part.
204   /// This function can be used to update values that have already been
205   /// vectorized. This is the case for "fix-up" operations including type
206   /// truncation and the second phase of recurrence vectorization.
207   void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
208     assert(hasVectorValue(Key, Part) && "Vector value not set for part");
209     VectorMapStorage[Key][Part] = Vector;
210   }
211 
212   /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
213   /// This function can be used to update values that have already been
214   /// scalarized. This is the case for "fix-up" operations including scalar phi
215   /// nodes for scalarized and predicated instructions.
216   void resetScalarValue(Value *Key, const VPIteration &Instance,
217                         Value *Scalar) {
218     assert(hasScalarValue(Key, Instance) &&
219            "Scalar value not set for part and lane");
220     ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
221   }
222 };
223 
224 /// This class is used to enable the VPlan to invoke a method of ILV. This is
225 /// needed until the method is refactored out of ILV and becomes reusable.
226 struct VPCallback {
227   virtual ~VPCallback() {}
228   virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
229 };
230 
231 /// VPTransformState holds information passed down when "executing" a VPlan,
232 /// needed for generating the output IR.
233 struct VPTransformState {
234   VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
235                    IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
236                    InnerLoopVectorizer *ILV, VPCallback &Callback)
237       : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
238         ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
239 
240   /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
241   unsigned VF;
242   unsigned UF;
243 
244   /// Hold the indices to generate specific scalar instructions. Null indicates
245   /// that all instances are to be generated, using either scalar or vector
246   /// instructions.
247   Optional<VPIteration> Instance;
248 
249   struct DataState {
250     /// A type for vectorized values in the new loop. Each value from the
251     /// original loop, when vectorized, is represented by UF vector values in
252     /// the new unrolled loop, where UF is the unroll factor.
253     typedef SmallVector<Value *, 2> PerPartValuesTy;
254 
255     DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
256   } Data;
257 
258   /// Get the generated Value for a given VPValue and a given Part. Note that
259   /// as some Defs are still created by ILV and managed in its ValueMap, this
260   /// method will delegate the call to ILV in such cases in order to provide
261   /// callers a consistent API.
262   /// \see set.
263   Value *get(VPValue *Def, unsigned Part) {
264     // If Values have been set for this Def return the one relevant for \p Part.
265     if (Data.PerPartOutput.count(Def))
266       return Data.PerPartOutput[Def][Part];
267     // Def is managed by ILV: bring the Values from ValueMap.
268     return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
269   }
270 
271   /// Set the generated Value for a given VPValue and a given Part.
272   void set(VPValue *Def, Value *V, unsigned Part) {
273     if (!Data.PerPartOutput.count(Def)) {
274       DataState::PerPartValuesTy Entry(UF);
275       Data.PerPartOutput[Def] = Entry;
276     }
277     Data.PerPartOutput[Def][Part] = V;
278   }
279 
280   /// Hold state information used when constructing the CFG of the output IR,
281   /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
282   struct CFGState {
283     /// The previous VPBasicBlock visited. Initially set to null.
284     VPBasicBlock *PrevVPBB = nullptr;
285 
286     /// The previous IR BasicBlock created or used. Initially set to the new
287     /// header BasicBlock.
288     BasicBlock *PrevBB = nullptr;
289 
290     /// The last IR BasicBlock in the output IR. Set to the new latch
291     /// BasicBlock, used for placing the newly created BasicBlocks.
292     BasicBlock *LastBB = nullptr;
293 
294     /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
295     /// of replication, maps the BasicBlock of the last replica created.
296     SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
297 
298     /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
299     /// up at the end of vector code generation.
300     SmallVector<VPBasicBlock *, 8> VPBBsToFix;
301 
302     CFGState() = default;
303   } CFG;
304 
305   /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
306   LoopInfo *LI;
307 
308   /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
309   DominatorTree *DT;
310 
311   /// Hold a reference to the IRBuilder used to generate output IR code.
312   IRBuilder<> &Builder;
313 
314   /// Hold a reference to the Value state information used when generating the
315   /// Values of the output IR.
316   VectorizerValueMap &ValueMap;
317 
318   /// Hold a reference to a mapping between VPValues in VPlan and original
319   /// Values they correspond to.
320   VPValue2ValueTy VPValue2Value;
321 
322   /// Hold the trip count of the scalar loop.
323   Value *TripCount = nullptr;
324 
325   /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
326   InnerLoopVectorizer *ILV;
327 
328   VPCallback &Callback;
329 };
330 
331 /// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
332 /// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
333 class VPBlockBase {
334   friend class VPBlockUtils;
335 
336 private:
337   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
338 
339   /// An optional name for the block.
340   std::string Name;
341 
342   /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
343   /// it is a topmost VPBlockBase.
344   VPRegionBlock *Parent = nullptr;
345 
346   /// List of predecessor blocks.
347   SmallVector<VPBlockBase *, 1> Predecessors;
348 
349   /// List of successor blocks.
350   SmallVector<VPBlockBase *, 1> Successors;
351 
352   /// Successor selector, null for zero or single successor blocks.
353   VPValue *CondBit = nullptr;
354 
355   /// Current block predicate - null if the block does not need a predicate.
356   VPValue *Predicate = nullptr;
357 
358   /// Add \p Successor as the last successor to this block.
359   void appendSuccessor(VPBlockBase *Successor) {
360     assert(Successor && "Cannot add nullptr successor!");
361     Successors.push_back(Successor);
362   }
363 
364   /// Add \p Predecessor as the last predecessor to this block.
365   void appendPredecessor(VPBlockBase *Predecessor) {
366     assert(Predecessor && "Cannot add nullptr predecessor!");
367     Predecessors.push_back(Predecessor);
368   }
369 
370   /// Remove \p Predecessor from the predecessors of this block.
371   void removePredecessor(VPBlockBase *Predecessor) {
372     auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
373     assert(Pos && "Predecessor does not exist");
374     Predecessors.erase(Pos);
375   }
376 
377   /// Remove \p Successor from the successors of this block.
378   void removeSuccessor(VPBlockBase *Successor) {
379     auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
380     assert(Pos && "Successor does not exist");
381     Successors.erase(Pos);
382   }
383 
384 protected:
385   VPBlockBase(const unsigned char SC, const std::string &N)
386       : SubclassID(SC), Name(N) {}
387 
388 public:
389   /// An enumeration for keeping track of the concrete subclass of VPBlockBase
390   /// that are actually instantiated. Values of this enumeration are kept in the
391   /// SubclassID field of the VPBlockBase objects. They are used for concrete
392   /// type identification.
393   using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
394 
395   using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
396 
397   virtual ~VPBlockBase() = default;
398 
399   const std::string &getName() const { return Name; }
400 
401   void setName(const Twine &newName) { Name = newName.str(); }
402 
403   /// \return an ID for the concrete type of this object.
404   /// This is used to implement the classof checks. This should not be used
405   /// for any other purpose, as the values may change as LLVM evolves.
406   unsigned getVPBlockID() const { return SubclassID; }
407 
408   VPRegionBlock *getParent() { return Parent; }
409   const VPRegionBlock *getParent() const { return Parent; }
410 
411   void setParent(VPRegionBlock *P) { Parent = P; }
412 
413   /// \return the VPBasicBlock that is the entry of this VPBlockBase,
414   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
415   /// VPBlockBase is a VPBasicBlock, it is returned.
416   const VPBasicBlock *getEntryBasicBlock() const;
417   VPBasicBlock *getEntryBasicBlock();
418 
419   /// \return the VPBasicBlock that is the exit of this VPBlockBase,
420   /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
421   /// VPBlockBase is a VPBasicBlock, it is returned.
422   const VPBasicBlock *getExitBasicBlock() const;
423   VPBasicBlock *getExitBasicBlock();
424 
425   const VPBlocksTy &getSuccessors() const { return Successors; }
426   VPBlocksTy &getSuccessors() { return Successors; }
427 
428   const VPBlocksTy &getPredecessors() const { return Predecessors; }
429   VPBlocksTy &getPredecessors() { return Predecessors; }
430 
431   /// \return the successor of this VPBlockBase if it has a single successor.
432   /// Otherwise return a null pointer.
433   VPBlockBase *getSingleSuccessor() const {
434     return (Successors.size() == 1 ? *Successors.begin() : nullptr);
435   }
436 
437   /// \return the predecessor of this VPBlockBase if it has a single
438   /// predecessor. Otherwise return a null pointer.
439   VPBlockBase *getSinglePredecessor() const {
440     return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
441   }
442 
443   size_t getNumSuccessors() const { return Successors.size(); }
444   size_t getNumPredecessors() const { return Predecessors.size(); }
445 
446   /// An Enclosing Block of a block B is any block containing B, including B
447   /// itself. \return the closest enclosing block starting from "this", which
448   /// has successors. \return the root enclosing block if all enclosing blocks
449   /// have no successors.
450   VPBlockBase *getEnclosingBlockWithSuccessors();
451 
452   /// \return the closest enclosing block starting from "this", which has
453   /// predecessors. \return the root enclosing block if all enclosing blocks
454   /// have no predecessors.
455   VPBlockBase *getEnclosingBlockWithPredecessors();
456 
457   /// \return the successors either attached directly to this VPBlockBase or, if
458   /// this VPBlockBase is the exit block of a VPRegionBlock and has no
459   /// successors of its own, search recursively for the first enclosing
460   /// VPRegionBlock that has successors and return them. If no such
461   /// VPRegionBlock exists, return the (empty) successors of the topmost
462   /// VPBlockBase reached.
463   const VPBlocksTy &getHierarchicalSuccessors() {
464     return getEnclosingBlockWithSuccessors()->getSuccessors();
465   }
466 
467   /// \return the hierarchical successor of this VPBlockBase if it has a single
468   /// hierarchical successor. Otherwise return a null pointer.
469   VPBlockBase *getSingleHierarchicalSuccessor() {
470     return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
471   }
472 
473   /// \return the predecessors either attached directly to this VPBlockBase or,
474   /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
475   /// predecessors of its own, search recursively for the first enclosing
476   /// VPRegionBlock that has predecessors and return them. If no such
477   /// VPRegionBlock exists, return the (empty) predecessors of the topmost
478   /// VPBlockBase reached.
479   const VPBlocksTy &getHierarchicalPredecessors() {
480     return getEnclosingBlockWithPredecessors()->getPredecessors();
481   }
482 
483   /// \return the hierarchical predecessor of this VPBlockBase if it has a
484   /// single hierarchical predecessor. Otherwise return a null pointer.
485   VPBlockBase *getSingleHierarchicalPredecessor() {
486     return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
487   }
488 
489   /// \return the condition bit selecting the successor.
490   VPValue *getCondBit() { return CondBit; }
491 
492   const VPValue *getCondBit() const { return CondBit; }
493 
494   void setCondBit(VPValue *CV) { CondBit = CV; }
495 
496   VPValue *getPredicate() { return Predicate; }
497 
498   const VPValue *getPredicate() const { return Predicate; }
499 
500   void setPredicate(VPValue *Pred) { Predicate = Pred; }
501 
502   /// Set a given VPBlockBase \p Successor as the single successor of this
503   /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
504   /// This VPBlockBase must have no successors.
505   void setOneSuccessor(VPBlockBase *Successor) {
506     assert(Successors.empty() && "Setting one successor when others exist.");
507     appendSuccessor(Successor);
508   }
509 
510   /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
511   /// successors of this VPBlockBase. \p Condition is set as the successor
512   /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
513   /// IfFalse. This VPBlockBase must have no successors.
514   void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
515                         VPValue *Condition) {
516     assert(Successors.empty() && "Setting two successors when others exist.");
517     assert(Condition && "Setting two successors without condition!");
518     CondBit = Condition;
519     appendSuccessor(IfTrue);
520     appendSuccessor(IfFalse);
521   }
522 
523   /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
524   /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
525   /// as successor of any VPBasicBlock in \p NewPreds.
526   void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
527     assert(Predecessors.empty() && "Block predecessors already set.");
528     for (auto *Pred : NewPreds)
529       appendPredecessor(Pred);
530   }
531 
532   /// Remove all the predecessor of this block.
533   void clearPredecessors() { Predecessors.clear(); }
534 
535   /// Remove all the successors of this block and set to null its condition bit
536   void clearSuccessors() {
537     Successors.clear();
538     CondBit = nullptr;
539   }
540 
541   /// The method which generates the output IR that correspond to this
542   /// VPBlockBase, thereby "executing" the VPlan.
543   virtual void execute(struct VPTransformState *State) = 0;
544 
545   /// Delete all blocks reachable from a given VPBlockBase, inclusive.
546   static void deleteCFG(VPBlockBase *Entry);
547 
548   void printAsOperand(raw_ostream &OS, bool PrintType) const {
549     OS << getName();
550   }
551 
552   void print(raw_ostream &OS) const {
553     // TODO: Only printing VPBB name for now since we only have dot printing
554     // support for VPInstructions/Recipes.
555     printAsOperand(OS, false);
556   }
557 
558   /// Return true if it is legal to hoist instructions into this block.
559   bool isLegalToHoistInto() {
560     // There are currently no constraints that prevent an instruction to be
561     // hoisted into a VPBlockBase.
562     return true;
563   }
564 };
565 
566 /// VPRecipeBase is a base class modeling a sequence of one or more output IR
567 /// instructions.
568 class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
569   friend VPBasicBlock;
570   friend class VPBlockUtils;
571 
572 private:
573   const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
574 
575   /// Each VPRecipe belongs to a single VPBasicBlock.
576   VPBasicBlock *Parent = nullptr;
577 
578 public:
579   /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
580   /// that is actually instantiated. Values of this enumeration are kept in the
581   /// SubclassID field of the VPRecipeBase objects. They are used for concrete
582   /// type identification.
583   using VPRecipeTy = enum {
584     VPBlendSC,
585     VPBranchOnMaskSC,
586     VPInstructionSC,
587     VPInterleaveSC,
588     VPPredInstPHISC,
589     VPReplicateSC,
590     VPWidenIntOrFpInductionSC,
591     VPWidenMemoryInstructionSC,
592     VPWidenPHISC,
593     VPWidenSC,
594   };
595 
596   VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
597   virtual ~VPRecipeBase() = default;
598 
599   /// \return an ID for the concrete type of this object.
600   /// This is used to implement the classof checks. This should not be used
601   /// for any other purpose, as the values may change as LLVM evolves.
602   unsigned getVPRecipeID() const { return SubclassID; }
603 
604   /// \return the VPBasicBlock which this VPRecipe belongs to.
605   VPBasicBlock *getParent() { return Parent; }
606   const VPBasicBlock *getParent() const { return Parent; }
607 
608   /// The method which generates the output IR instructions that correspond to
609   /// this VPRecipe, thereby "executing" the VPlan.
610   virtual void execute(struct VPTransformState &State) = 0;
611 
612   /// Each recipe prints itself.
613   virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
614 
615   /// Insert an unlinked recipe into a basic block immediately before
616   /// the specified recipe.
617   void insertBefore(VPRecipeBase *InsertPos);
618 
619   /// Insert an unlinked Recipe into a basic block immediately after
620   /// the specified Recipe.
621   void insertAfter(VPRecipeBase *InsertPos);
622 
623   /// Unlink this recipe from its current VPBasicBlock and insert it into
624   /// the VPBasicBlock that MovePos lives in, right after MovePos.
625   void moveAfter(VPRecipeBase *MovePos);
626 
627   /// This method unlinks 'this' from the containing basic block, but does not
628   /// delete it.
629   void removeFromParent();
630 
631   /// This method unlinks 'this' from the containing basic block and deletes it.
632   ///
633   /// \returns an iterator pointing to the element after the erased one
634   iplist<VPRecipeBase>::iterator eraseFromParent();
635 };
636 
637 /// This is a concrete Recipe that models a single VPlan-level instruction.
638 /// While as any Recipe it may generate a sequence of IR instructions when
639 /// executed, these instructions would always form a single-def expression as
640 /// the VPInstruction is also a single def-use vertex.
641 class VPInstruction : public VPUser, public VPRecipeBase {
642   friend class VPlanHCFGTransforms;
643   friend class VPlanSlp;
644 
645 public:
646   /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
647   enum {
648     Not = Instruction::OtherOpsEnd + 1,
649     ICmpULE,
650     SLPLoad,
651     SLPStore,
652   };
653 
654 private:
655   typedef unsigned char OpcodeTy;
656   OpcodeTy Opcode;
657 
658   /// Utility method serving execute(): generates a single instance of the
659   /// modeled instruction.
660   void generateInstruction(VPTransformState &State, unsigned Part);
661 
662 protected:
663   Instruction *getUnderlyingInstr() {
664     return cast_or_null<Instruction>(getUnderlyingValue());
665   }
666 
667   void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
668 
669 public:
670   VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
671       : VPUser(VPValue::VPInstructionSC, Operands),
672         VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
673 
674   VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
675       : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
676 
677   /// Method to support type inquiry through isa, cast, and dyn_cast.
678   static inline bool classof(const VPValue *V) {
679     return V->getVPValueID() == VPValue::VPInstructionSC;
680   }
681 
682   VPInstruction *clone() const {
683     SmallVector<VPValue *, 2> Operands(operands());
684     return new VPInstruction(Opcode, Operands);
685   }
686 
687   /// Method to support type inquiry through isa, cast, and dyn_cast.
688   static inline bool classof(const VPRecipeBase *R) {
689     return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
690   }
691 
692   unsigned getOpcode() const { return Opcode; }
693 
694   /// Generate the instruction.
695   /// TODO: We currently execute only per-part unless a specific instance is
696   /// provided.
697   void execute(VPTransformState &State) override;
698 
699   /// Print the Recipe.
700   void print(raw_ostream &O, const Twine &Indent) const override;
701 
702   /// Print the VPInstruction.
703   void print(raw_ostream &O) const;
704 
705   /// Return true if this instruction may modify memory.
706   bool mayWriteToMemory() const {
707     // TODO: we can use attributes of the called function to rule out memory
708     //       modifications.
709     return Opcode == Instruction::Store || Opcode == Instruction::Call ||
710            Opcode == Instruction::Invoke || Opcode == SLPStore;
711   }
712 };
713 
714 /// VPWidenRecipe is a recipe for producing a copy of vector type for each
715 /// Instruction in its ingredients independently, in order. This recipe covers
716 /// most of the traditional vectorization cases where each ingredient transforms
717 /// into a vectorized version of itself.
718 class VPWidenRecipe : public VPRecipeBase {
719 private:
720   /// Hold the ingredients by pointing to their original BasicBlock location.
721   BasicBlock::iterator Begin;
722   BasicBlock::iterator End;
723 
724 public:
725   VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
726     End = I->getIterator();
727     Begin = End++;
728   }
729 
730   ~VPWidenRecipe() override = default;
731 
732   /// Method to support type inquiry through isa, cast, and dyn_cast.
733   static inline bool classof(const VPRecipeBase *V) {
734     return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
735   }
736 
737   /// Produce widened copies of all Ingredients.
738   void execute(VPTransformState &State) override;
739 
740   /// Augment the recipe to include Instr, if it lies at its End.
741   bool appendInstruction(Instruction *Instr) {
742     if (End != Instr->getIterator())
743       return false;
744     End++;
745     return true;
746   }
747 
748   /// Print the recipe.
749   void print(raw_ostream &O, const Twine &Indent) const override;
750 };
751 
752 /// A recipe for handling phi nodes of integer and floating-point inductions,
753 /// producing their vector and scalar values.
754 class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
755 private:
756   PHINode *IV;
757   TruncInst *Trunc;
758 
759 public:
760   VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
761       : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
762   ~VPWidenIntOrFpInductionRecipe() override = default;
763 
764   /// Method to support type inquiry through isa, cast, and dyn_cast.
765   static inline bool classof(const VPRecipeBase *V) {
766     return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
767   }
768 
769   /// Generate the vectorized and scalarized versions of the phi node as
770   /// needed by their users.
771   void execute(VPTransformState &State) override;
772 
773   /// Print the recipe.
774   void print(raw_ostream &O, const Twine &Indent) const override;
775 };
776 
777 /// A recipe for handling all phi nodes except for integer and FP inductions.
778 class VPWidenPHIRecipe : public VPRecipeBase {
779 private:
780   PHINode *Phi;
781 
782 public:
783   VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
784   ~VPWidenPHIRecipe() override = default;
785 
786   /// Method to support type inquiry through isa, cast, and dyn_cast.
787   static inline bool classof(const VPRecipeBase *V) {
788     return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
789   }
790 
791   /// Generate the phi/select nodes.
792   void execute(VPTransformState &State) override;
793 
794   /// Print the recipe.
795   void print(raw_ostream &O, const Twine &Indent) const override;
796 };
797 
798 /// A recipe for vectorizing a phi-node as a sequence of mask-based select
799 /// instructions.
800 class VPBlendRecipe : public VPRecipeBase {
801 private:
802   PHINode *Phi;
803 
804   /// The blend operation is a User of a mask, if not null.
805   std::unique_ptr<VPUser> User;
806 
807 public:
808   VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
809       : VPRecipeBase(VPBlendSC), Phi(Phi) {
810     assert((Phi->getNumIncomingValues() == 1 ||
811             Phi->getNumIncomingValues() == Masks.size()) &&
812            "Expected the same number of incoming values and masks");
813     if (!Masks.empty())
814       User.reset(new VPUser(Masks));
815   }
816 
817   /// Method to support type inquiry through isa, cast, and dyn_cast.
818   static inline bool classof(const VPRecipeBase *V) {
819     return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
820   }
821 
822   /// Generate the phi/select nodes.
823   void execute(VPTransformState &State) override;
824 
825   /// Print the recipe.
826   void print(raw_ostream &O, const Twine &Indent) const override;
827 };
828 
829 /// VPInterleaveRecipe is a recipe for transforming an interleave group of load
830 /// or stores into one wide load/store and shuffles.
831 class VPInterleaveRecipe : public VPRecipeBase {
832 private:
833   const InterleaveGroup<Instruction> *IG;
834   std::unique_ptr<VPUser> User;
835 
836 public:
837   VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Mask)
838       : VPRecipeBase(VPInterleaveSC), IG(IG) {
839     if (Mask) // Create a VPInstruction to register as a user of the mask.
840       User.reset(new VPUser({Mask}));
841   }
842   ~VPInterleaveRecipe() override = default;
843 
844   /// Method to support type inquiry through isa, cast, and dyn_cast.
845   static inline bool classof(const VPRecipeBase *V) {
846     return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
847   }
848 
849   /// Generate the wide load or store, and shuffles.
850   void execute(VPTransformState &State) override;
851 
852   /// Print the recipe.
853   void print(raw_ostream &O, const Twine &Indent) const override;
854 
855   const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
856 };
857 
858 /// VPReplicateRecipe replicates a given instruction producing multiple scalar
859 /// copies of the original scalar type, one per lane, instead of producing a
860 /// single copy of widened type for all lanes. If the instruction is known to be
861 /// uniform only one copy, per lane zero, will be generated.
862 class VPReplicateRecipe : public VPRecipeBase {
863 private:
864   /// The instruction being replicated.
865   Instruction *Ingredient;
866 
867   /// Indicator if only a single replica per lane is needed.
868   bool IsUniform;
869 
870   /// Indicator if the replicas are also predicated.
871   bool IsPredicated;
872 
873   /// Indicator if the scalar values should also be packed into a vector.
874   bool AlsoPack;
875 
876 public:
877   VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
878       : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
879         IsPredicated(IsPredicated) {
880     // Retain the previous behavior of predicateInstructions(), where an
881     // insert-element of a predicated instruction got hoisted into the
882     // predicated basic block iff it was its only user. This is achieved by
883     // having predicated instructions also pack their values into a vector by
884     // default unless they have a replicated user which uses their scalar value.
885     AlsoPack = IsPredicated && !I->use_empty();
886   }
887 
888   ~VPReplicateRecipe() override = default;
889 
890   /// Method to support type inquiry through isa, cast, and dyn_cast.
891   static inline bool classof(const VPRecipeBase *V) {
892     return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
893   }
894 
895   /// Generate replicas of the desired Ingredient. Replicas will be generated
896   /// for all parts and lanes unless a specific part and lane are specified in
897   /// the \p State.
898   void execute(VPTransformState &State) override;
899 
900   void setAlsoPack(bool Pack) { AlsoPack = Pack; }
901 
902   /// Print the recipe.
903   void print(raw_ostream &O, const Twine &Indent) const override;
904 };
905 
906 /// A recipe for generating conditional branches on the bits of a mask.
907 class VPBranchOnMaskRecipe : public VPRecipeBase {
908 private:
909   std::unique_ptr<VPUser> User;
910 
911 public:
912   VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
913     if (BlockInMask) // nullptr means all-one mask.
914       User.reset(new VPUser({BlockInMask}));
915   }
916 
917   /// Method to support type inquiry through isa, cast, and dyn_cast.
918   static inline bool classof(const VPRecipeBase *V) {
919     return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
920   }
921 
922   /// Generate the extraction of the appropriate bit from the block mask and the
923   /// conditional branch.
924   void execute(VPTransformState &State) override;
925 
926   /// Print the recipe.
927   void print(raw_ostream &O, const Twine &Indent) const override {
928     O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
929     if (User)
930       O << *User->getOperand(0);
931     else
932       O << " All-One";
933     O << "\\l\"";
934   }
935 };
936 
937 /// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
938 /// control converges back from a Branch-on-Mask. The phi nodes are needed in
939 /// order to merge values that are set under such a branch and feed their uses.
940 /// The phi nodes can be scalar or vector depending on the users of the value.
941 /// This recipe works in concert with VPBranchOnMaskRecipe.
942 class VPPredInstPHIRecipe : public VPRecipeBase {
943 private:
944   Instruction *PredInst;
945 
946 public:
947   /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
948   /// nodes after merging back from a Branch-on-Mask.
949   VPPredInstPHIRecipe(Instruction *PredInst)
950       : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
951   ~VPPredInstPHIRecipe() override = default;
952 
953   /// Method to support type inquiry through isa, cast, and dyn_cast.
954   static inline bool classof(const VPRecipeBase *V) {
955     return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
956   }
957 
958   /// Generates phi nodes for live-outs as needed to retain SSA form.
959   void execute(VPTransformState &State) override;
960 
961   /// Print the recipe.
962   void print(raw_ostream &O, const Twine &Indent) const override;
963 };
964 
965 /// A Recipe for widening load/store operations.
966 /// TODO: We currently execute only per-part unless a specific instance is
967 /// provided.
968 class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
969 private:
970   Instruction &Instr;
971   std::unique_ptr<VPUser> User;
972 
973 public:
974   VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
975       : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
976     if (Mask) // Create a VPInstruction to register as a user of the mask.
977       User.reset(new VPUser({Mask}));
978   }
979 
980   /// Method to support type inquiry through isa, cast, and dyn_cast.
981   static inline bool classof(const VPRecipeBase *V) {
982     return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
983   }
984 
985   /// Return the mask used by this recipe. Note that a full mask is represented
986   /// by a nullptr.
987   VPValue *getMask() {
988     // Mask is the last operand.
989     return User ? User->getOperand(User->getNumOperands() - 1) : nullptr;
990   }
991 
992   /// Generate the wide load/store.
993   void execute(VPTransformState &State) override;
994 
995   /// Print the recipe.
996   void print(raw_ostream &O, const Twine &Indent) const override;
997 };
998 
999 /// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1000 /// holds a sequence of zero or more VPRecipe's each representing a sequence of
1001 /// output IR instructions.
1002 class VPBasicBlock : public VPBlockBase {
1003 public:
1004   using RecipeListTy = iplist<VPRecipeBase>;
1005 
1006 private:
1007   /// The VPRecipes held in the order of output instructions to generate.
1008   RecipeListTy Recipes;
1009 
1010 public:
1011   VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1012       : VPBlockBase(VPBasicBlockSC, Name.str()) {
1013     if (Recipe)
1014       appendRecipe(Recipe);
1015   }
1016 
1017   ~VPBasicBlock() override { Recipes.clear(); }
1018 
1019   /// Instruction iterators...
1020   using iterator = RecipeListTy::iterator;
1021   using const_iterator = RecipeListTy::const_iterator;
1022   using reverse_iterator = RecipeListTy::reverse_iterator;
1023   using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
1024 
1025   //===--------------------------------------------------------------------===//
1026   /// Recipe iterator methods
1027   ///
1028   inline iterator begin() { return Recipes.begin(); }
1029   inline const_iterator begin() const { return Recipes.begin(); }
1030   inline iterator end() { return Recipes.end(); }
1031   inline const_iterator end() const { return Recipes.end(); }
1032 
1033   inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1034   inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1035   inline reverse_iterator rend() { return Recipes.rend(); }
1036   inline const_reverse_iterator rend() const { return Recipes.rend(); }
1037 
1038   inline size_t size() const { return Recipes.size(); }
1039   inline bool empty() const { return Recipes.empty(); }
1040   inline const VPRecipeBase &front() const { return Recipes.front(); }
1041   inline VPRecipeBase &front() { return Recipes.front(); }
1042   inline const VPRecipeBase &back() const { return Recipes.back(); }
1043   inline VPRecipeBase &back() { return Recipes.back(); }
1044 
1045   /// Returns a reference to the list of recipes.
1046   RecipeListTy &getRecipeList() { return Recipes; }
1047 
1048   /// Returns a pointer to a member of the recipe list.
1049   static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1050     return &VPBasicBlock::Recipes;
1051   }
1052 
1053   /// Method to support type inquiry through isa, cast, and dyn_cast.
1054   static inline bool classof(const VPBlockBase *V) {
1055     return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1056   }
1057 
1058   void insert(VPRecipeBase *Recipe, iterator InsertPt) {
1059     assert(Recipe && "No recipe to append.");
1060     assert(!Recipe->Parent && "Recipe already in VPlan");
1061     Recipe->Parent = this;
1062     Recipes.insert(InsertPt, Recipe);
1063   }
1064 
1065   /// Augment the existing recipes of a VPBasicBlock with an additional
1066   /// \p Recipe as the last recipe.
1067   void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1068 
1069   /// The method which generates the output IR instructions that correspond to
1070   /// this VPBasicBlock, thereby "executing" the VPlan.
1071   void execute(struct VPTransformState *State) override;
1072 
1073 private:
1074   /// Create an IR BasicBlock to hold the output instructions generated by this
1075   /// VPBasicBlock, and return it. Update the CFGState accordingly.
1076   BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1077 };
1078 
1079 /// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1080 /// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1081 /// A VPRegionBlock may indicate that its contents are to be replicated several
1082 /// times. This is designed to support predicated scalarization, in which a
1083 /// scalar if-then code structure needs to be generated VF * UF times. Having
1084 /// this replication indicator helps to keep a single model for multiple
1085 /// candidate VF's. The actual replication takes place only once the desired VF
1086 /// and UF have been determined.
1087 class VPRegionBlock : public VPBlockBase {
1088 private:
1089   /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1090   VPBlockBase *Entry;
1091 
1092   /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1093   VPBlockBase *Exit;
1094 
1095   /// An indicator whether this region is to generate multiple replicated
1096   /// instances of output IR corresponding to its VPBlockBases.
1097   bool IsReplicator;
1098 
1099 public:
1100   VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1101                 const std::string &Name = "", bool IsReplicator = false)
1102       : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1103         IsReplicator(IsReplicator) {
1104     assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1105     assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1106     Entry->setParent(this);
1107     Exit->setParent(this);
1108   }
1109   VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1110       : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1111         IsReplicator(IsReplicator) {}
1112 
1113   ~VPRegionBlock() override {
1114     if (Entry)
1115       deleteCFG(Entry);
1116   }
1117 
1118   /// Method to support type inquiry through isa, cast, and dyn_cast.
1119   static inline bool classof(const VPBlockBase *V) {
1120     return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1121   }
1122 
1123   const VPBlockBase *getEntry() const { return Entry; }
1124   VPBlockBase *getEntry() { return Entry; }
1125 
1126   /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1127   /// EntryBlock must have no predecessors.
1128   void setEntry(VPBlockBase *EntryBlock) {
1129     assert(EntryBlock->getPredecessors().empty() &&
1130            "Entry block cannot have predecessors.");
1131     Entry = EntryBlock;
1132     EntryBlock->setParent(this);
1133   }
1134 
1135   // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1136   // specific interface of llvm::Function, instead of using
1137   // GraphTraints::getEntryNode. We should add a new template parameter to
1138   // DominatorTreeBase representing the Graph type.
1139   VPBlockBase &front() const { return *Entry; }
1140 
1141   const VPBlockBase *getExit() const { return Exit; }
1142   VPBlockBase *getExit() { return Exit; }
1143 
1144   /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1145   /// ExitBlock must have no successors.
1146   void setExit(VPBlockBase *ExitBlock) {
1147     assert(ExitBlock->getSuccessors().empty() &&
1148            "Exit block cannot have successors.");
1149     Exit = ExitBlock;
1150     ExitBlock->setParent(this);
1151   }
1152 
1153   /// An indicator whether this region is to generate multiple replicated
1154   /// instances of output IR corresponding to its VPBlockBases.
1155   bool isReplicator() const { return IsReplicator; }
1156 
1157   /// The method which generates the output IR instructions that correspond to
1158   /// this VPRegionBlock, thereby "executing" the VPlan.
1159   void execute(struct VPTransformState *State) override;
1160 };
1161 
1162 /// VPlan models a candidate for vectorization, encoding various decisions take
1163 /// to produce efficient output IR, including which branches, basic-blocks and
1164 /// output IR instructions to generate, and their cost. VPlan holds a
1165 /// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1166 /// VPBlock.
1167 class VPlan {
1168   friend class VPlanPrinter;
1169 
1170 private:
1171   /// Hold the single entry to the Hierarchical CFG of the VPlan.
1172   VPBlockBase *Entry;
1173 
1174   /// Holds the VFs applicable to this VPlan.
1175   SmallSet<unsigned, 2> VFs;
1176 
1177   /// Holds the name of the VPlan, for printing.
1178   std::string Name;
1179 
1180   /// Holds all the external definitions created for this VPlan.
1181   // TODO: Introduce a specific representation for external definitions in
1182   // VPlan. External definitions must be immutable and hold a pointer to its
1183   // underlying IR that will be used to implement its structural comparison
1184   // (operators '==' and '<').
1185   SmallPtrSet<VPValue *, 16> VPExternalDefs;
1186 
1187   /// Represents the backedge taken count of the original loop, for folding
1188   /// the tail.
1189   VPValue *BackedgeTakenCount = nullptr;
1190 
1191   /// Holds a mapping between Values and their corresponding VPValue inside
1192   /// VPlan.
1193   Value2VPValueTy Value2VPValue;
1194 
1195   /// Holds the VPLoopInfo analysis for this VPlan.
1196   VPLoopInfo VPLInfo;
1197 
1198   /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1199   SmallVector<VPValue *, 4> VPCBVs;
1200 
1201 public:
1202   VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1203 
1204   ~VPlan() {
1205     if (Entry)
1206       VPBlockBase::deleteCFG(Entry);
1207     for (auto &MapEntry : Value2VPValue)
1208       if (MapEntry.second != BackedgeTakenCount)
1209         delete MapEntry.second;
1210     if (BackedgeTakenCount)
1211       delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not.
1212     for (VPValue *Def : VPExternalDefs)
1213       delete Def;
1214     for (VPValue *CBV : VPCBVs)
1215       delete CBV;
1216   }
1217 
1218   /// Generate the IR code for this VPlan.
1219   void execute(struct VPTransformState *State);
1220 
1221   VPBlockBase *getEntry() { return Entry; }
1222   const VPBlockBase *getEntry() const { return Entry; }
1223 
1224   VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1225 
1226   /// The backedge taken count of the original loop.
1227   VPValue *getOrCreateBackedgeTakenCount() {
1228     if (!BackedgeTakenCount)
1229       BackedgeTakenCount = new VPValue();
1230     return BackedgeTakenCount;
1231   }
1232 
1233   void addVF(unsigned VF) { VFs.insert(VF); }
1234 
1235   bool hasVF(unsigned VF) { return VFs.count(VF); }
1236 
1237   const std::string &getName() const { return Name; }
1238 
1239   void setName(const Twine &newName) { Name = newName.str(); }
1240 
1241   /// Add \p VPVal to the pool of external definitions if it's not already
1242   /// in the pool.
1243   void addExternalDef(VPValue *VPVal) {
1244     VPExternalDefs.insert(VPVal);
1245   }
1246 
1247   /// Add \p CBV to the vector of condition bit values.
1248   void addCBV(VPValue *CBV) {
1249     VPCBVs.push_back(CBV);
1250   }
1251 
1252   void addVPValue(Value *V) {
1253     assert(V && "Trying to add a null Value to VPlan");
1254     assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1255     Value2VPValue[V] = new VPValue();
1256   }
1257 
1258   VPValue *getVPValue(Value *V) {
1259     assert(V && "Trying to get the VPValue of a null Value");
1260     assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1261     return Value2VPValue[V];
1262   }
1263 
1264   /// Return the VPLoopInfo analysis for this VPlan.
1265   VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1266   const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1267 
1268 private:
1269   /// Add to the given dominator tree the header block and every new basic block
1270   /// that was created between it and the latch block, inclusive.
1271   static void updateDominatorTree(DominatorTree *DT,
1272                                   BasicBlock *LoopPreHeaderBB,
1273                                   BasicBlock *LoopLatchBB);
1274 };
1275 
1276 /// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1277 /// indented and follows the dot format.
1278 class VPlanPrinter {
1279   friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1280   friend inline raw_ostream &operator<<(raw_ostream &OS,
1281                                         const struct VPlanIngredient &I);
1282 
1283 private:
1284   raw_ostream &OS;
1285   VPlan &Plan;
1286   unsigned Depth = 0;
1287   unsigned TabWidth = 2;
1288   std::string Indent;
1289   unsigned BID = 0;
1290   SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1291 
1292   VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1293 
1294   /// Handle indentation.
1295   void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1296 
1297   /// Print a given \p Block of the Plan.
1298   void dumpBlock(const VPBlockBase *Block);
1299 
1300   /// Print the information related to the CFG edges going out of a given
1301   /// \p Block, followed by printing the successor blocks themselves.
1302   void dumpEdges(const VPBlockBase *Block);
1303 
1304   /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1305   /// its successor blocks.
1306   void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1307 
1308   /// Print a given \p Region of the Plan.
1309   void dumpRegion(const VPRegionBlock *Region);
1310 
1311   unsigned getOrCreateBID(const VPBlockBase *Block) {
1312     return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1313   }
1314 
1315   const Twine getOrCreateName(const VPBlockBase *Block);
1316 
1317   const Twine getUID(const VPBlockBase *Block);
1318 
1319   /// Print the information related to a CFG edge between two VPBlockBases.
1320   void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1321                 const Twine &Label);
1322 
1323   void dump();
1324 
1325   static void printAsIngredient(raw_ostream &O, Value *V);
1326 };
1327 
1328 struct VPlanIngredient {
1329   Value *V;
1330 
1331   VPlanIngredient(Value *V) : V(V) {}
1332 };
1333 
1334 inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1335   VPlanPrinter::printAsIngredient(OS, I.V);
1336   return OS;
1337 }
1338 
1339 inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1340   VPlanPrinter Printer(OS, Plan);
1341   Printer.dump();
1342   return OS;
1343 }
1344 
1345 //===----------------------------------------------------------------------===//
1346 // GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs     //
1347 //===----------------------------------------------------------------------===//
1348 
1349 // The following set of template specializations implement GraphTraits to treat
1350 // any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1351 // that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1352 // VPBlockBase is a VPRegionBlock, this specialization provides access to its
1353 // successors/predecessors but not to the blocks inside the region.
1354 
1355 template <> struct GraphTraits<VPBlockBase *> {
1356   using NodeRef = VPBlockBase *;
1357   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1358 
1359   static NodeRef getEntryNode(NodeRef N) { return N; }
1360 
1361   static inline ChildIteratorType child_begin(NodeRef N) {
1362     return N->getSuccessors().begin();
1363   }
1364 
1365   static inline ChildIteratorType child_end(NodeRef N) {
1366     return N->getSuccessors().end();
1367   }
1368 };
1369 
1370 template <> struct GraphTraits<const VPBlockBase *> {
1371   using NodeRef = const VPBlockBase *;
1372   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1373 
1374   static NodeRef getEntryNode(NodeRef N) { return N; }
1375 
1376   static inline ChildIteratorType child_begin(NodeRef N) {
1377     return N->getSuccessors().begin();
1378   }
1379 
1380   static inline ChildIteratorType child_end(NodeRef N) {
1381     return N->getSuccessors().end();
1382   }
1383 };
1384 
1385 // Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1386 // of successors for the inverse traversal.
1387 template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1388   using NodeRef = VPBlockBase *;
1389   using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1390 
1391   static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1392 
1393   static inline ChildIteratorType child_begin(NodeRef N) {
1394     return N->getPredecessors().begin();
1395   }
1396 
1397   static inline ChildIteratorType child_end(NodeRef N) {
1398     return N->getPredecessors().end();
1399   }
1400 };
1401 
1402 // The following set of template specializations implement GraphTraits to
1403 // treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1404 // to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1405 // (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1406 // there won't be automatic recursion into other VPBlockBases that turn to be
1407 // VPRegionBlocks.
1408 
1409 template <>
1410 struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1411   using GraphRef = VPRegionBlock *;
1412   using nodes_iterator = df_iterator<NodeRef>;
1413 
1414   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1415 
1416   static nodes_iterator nodes_begin(GraphRef N) {
1417     return nodes_iterator::begin(N->getEntry());
1418   }
1419 
1420   static nodes_iterator nodes_end(GraphRef N) {
1421     // df_iterator::end() returns an empty iterator so the node used doesn't
1422     // matter.
1423     return nodes_iterator::end(N);
1424   }
1425 };
1426 
1427 template <>
1428 struct GraphTraits<const VPRegionBlock *>
1429     : public GraphTraits<const VPBlockBase *> {
1430   using GraphRef = const VPRegionBlock *;
1431   using nodes_iterator = df_iterator<NodeRef>;
1432 
1433   static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1434 
1435   static nodes_iterator nodes_begin(GraphRef N) {
1436     return nodes_iterator::begin(N->getEntry());
1437   }
1438 
1439   static nodes_iterator nodes_end(GraphRef N) {
1440     // df_iterator::end() returns an empty iterator so the node used doesn't
1441     // matter.
1442     return nodes_iterator::end(N);
1443   }
1444 };
1445 
1446 template <>
1447 struct GraphTraits<Inverse<VPRegionBlock *>>
1448     : public GraphTraits<Inverse<VPBlockBase *>> {
1449   using GraphRef = VPRegionBlock *;
1450   using nodes_iterator = df_iterator<NodeRef>;
1451 
1452   static NodeRef getEntryNode(Inverse<GraphRef> N) {
1453     return N.Graph->getExit();
1454   }
1455 
1456   static nodes_iterator nodes_begin(GraphRef N) {
1457     return nodes_iterator::begin(N->getExit());
1458   }
1459 
1460   static nodes_iterator nodes_end(GraphRef N) {
1461     // df_iterator::end() returns an empty iterator so the node used doesn't
1462     // matter.
1463     return nodes_iterator::end(N);
1464   }
1465 };
1466 
1467 //===----------------------------------------------------------------------===//
1468 // VPlan Utilities
1469 //===----------------------------------------------------------------------===//
1470 
1471 /// Class that provides utilities for VPBlockBases in VPlan.
1472 class VPBlockUtils {
1473 public:
1474   VPBlockUtils() = delete;
1475 
1476   /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1477   /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1478   /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1479   /// has more than one successor, its conditional bit is propagated to \p
1480   /// NewBlock. \p NewBlock must have neither successors nor predecessors.
1481   static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1482     assert(NewBlock->getSuccessors().empty() &&
1483            "Can't insert new block with successors.");
1484     // TODO: move successors from BlockPtr to NewBlock when this functionality
1485     // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1486     // already has successors.
1487     BlockPtr->setOneSuccessor(NewBlock);
1488     NewBlock->setPredecessors({BlockPtr});
1489     NewBlock->setParent(BlockPtr->getParent());
1490   }
1491 
1492   /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1493   /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1494   /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1495   /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1496   /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1497   /// must have neither successors nor predecessors.
1498   static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1499                                    VPValue *Condition, VPBlockBase *BlockPtr) {
1500     assert(IfTrue->getSuccessors().empty() &&
1501            "Can't insert IfTrue with successors.");
1502     assert(IfFalse->getSuccessors().empty() &&
1503            "Can't insert IfFalse with successors.");
1504     BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
1505     IfTrue->setPredecessors({BlockPtr});
1506     IfFalse->setPredecessors({BlockPtr});
1507     IfTrue->setParent(BlockPtr->getParent());
1508     IfFalse->setParent(BlockPtr->getParent());
1509   }
1510 
1511   /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1512   /// the successors of \p From and \p From to the predecessors of \p To. Both
1513   /// VPBlockBases must have the same parent, which can be null. Both
1514   /// VPBlockBases can be already connected to other VPBlockBases.
1515   static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1516     assert((From->getParent() == To->getParent()) &&
1517            "Can't connect two block with different parents");
1518     assert(From->getNumSuccessors() < 2 &&
1519            "Blocks can't have more than two successors.");
1520     From->appendSuccessor(To);
1521     To->appendPredecessor(From);
1522   }
1523 
1524   /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1525   /// from the successors of \p From and \p From from the predecessors of \p To.
1526   static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1527     assert(To && "Successor to disconnect is null.");
1528     From->removeSuccessor(To);
1529     To->removePredecessor(From);
1530   }
1531 
1532   /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1533   static bool isBackEdge(const VPBlockBase *FromBlock,
1534                          const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
1535     assert(FromBlock->getParent() == ToBlock->getParent() &&
1536            FromBlock->getParent() && "Must be in same region");
1537     const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
1538     const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
1539     if (!FromLoop || !ToLoop || FromLoop != ToLoop)
1540       return false;
1541 
1542     // A back-edge is a branch from the loop latch to its header.
1543     return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
1544   }
1545 
1546   /// Returns true if \p Block is a loop latch
1547   static bool blockIsLoopLatch(const VPBlockBase *Block,
1548                                const VPLoopInfo *VPLInfo) {
1549     if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
1550       return ParentVPL->isLoopLatch(Block);
1551 
1552     return false;
1553   }
1554 
1555   /// Count and return the number of succesors of \p PredBlock excluding any
1556   /// backedges.
1557   static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
1558                                       VPLoopInfo *VPLI) {
1559     unsigned Count = 0;
1560     for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
1561       if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
1562         Count++;
1563     }
1564     return Count;
1565   }
1566 };
1567 
1568 class VPInterleavedAccessInfo {
1569 private:
1570   DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1571       InterleaveGroupMap;
1572 
1573   /// Type for mapping of instruction based interleave groups to VPInstruction
1574   /// interleave groups
1575   using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1576                              InterleaveGroup<VPInstruction> *>;
1577 
1578   /// Recursively \p Region and populate VPlan based interleave groups based on
1579   /// \p IAI.
1580   void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1581                    InterleavedAccessInfo &IAI);
1582   /// Recursively traverse \p Block and populate VPlan based interleave groups
1583   /// based on \p IAI.
1584   void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1585                   InterleavedAccessInfo &IAI);
1586 
1587 public:
1588   VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1589 
1590   ~VPInterleavedAccessInfo() {
1591     SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1592     // Avoid releasing a pointer twice.
1593     for (auto &I : InterleaveGroupMap)
1594       DelSet.insert(I.second);
1595     for (auto *Ptr : DelSet)
1596       delete Ptr;
1597   }
1598 
1599   /// Get the interleave group that \p Instr belongs to.
1600   ///
1601   /// \returns nullptr if doesn't have such group.
1602   InterleaveGroup<VPInstruction> *
1603   getInterleaveGroup(VPInstruction *Instr) const {
1604     if (InterleaveGroupMap.count(Instr))
1605       return InterleaveGroupMap.find(Instr)->second;
1606     return nullptr;
1607   }
1608 };
1609 
1610 /// Class that maps (parts of) an existing VPlan to trees of combined
1611 /// VPInstructions.
1612 class VPlanSlp {
1613 private:
1614   enum class OpMode { Failed, Load, Opcode };
1615 
1616   /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
1617   /// DenseMap keys.
1618   struct BundleDenseMapInfo {
1619     static SmallVector<VPValue *, 4> getEmptyKey() {
1620       return {reinterpret_cast<VPValue *>(-1)};
1621     }
1622 
1623     static SmallVector<VPValue *, 4> getTombstoneKey() {
1624       return {reinterpret_cast<VPValue *>(-2)};
1625     }
1626 
1627     static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
1628       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1629     }
1630 
1631     static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
1632                         const SmallVector<VPValue *, 4> &RHS) {
1633       return LHS == RHS;
1634     }
1635   };
1636 
1637   /// Mapping of values in the original VPlan to a combined VPInstruction.
1638   DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
1639       BundleToCombined;
1640 
1641   VPInterleavedAccessInfo &IAI;
1642 
1643   /// Basic block to operate on. For now, only instructions in a single BB are
1644   /// considered.
1645   const VPBasicBlock &BB;
1646 
1647   /// Indicates whether we managed to combine all visited instructions or not.
1648   bool CompletelySLP = true;
1649 
1650   /// Width of the widest combined bundle in bits.
1651   unsigned WidestBundleBits = 0;
1652 
1653   using MultiNodeOpTy =
1654       typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
1655 
1656   // Input operand bundles for the current multi node. Each multi node operand
1657   // bundle contains values not matching the multi node's opcode. They will
1658   // be reordered in reorderMultiNodeOps, once we completed building a
1659   // multi node.
1660   SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
1661 
1662   /// Indicates whether we are building a multi node currently.
1663   bool MultiNodeActive = false;
1664 
1665   /// Check if we can vectorize Operands together.
1666   bool areVectorizable(ArrayRef<VPValue *> Operands) const;
1667 
1668   /// Add combined instruction \p New for the bundle \p Operands.
1669   void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
1670 
1671   /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
1672   VPInstruction *markFailed();
1673 
1674   /// Reorder operands in the multi node to maximize sequential memory access
1675   /// and commutative operations.
1676   SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
1677 
1678   /// Choose the best candidate to use for the lane after \p Last. The set of
1679   /// candidates to choose from are values with an opcode matching \p Last's
1680   /// or loads consecutive to \p Last.
1681   std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
1682                                        SmallPtrSetImpl<VPValue *> &Candidates,
1683                                        VPInterleavedAccessInfo &IAI);
1684 
1685   /// Print bundle \p Values to dbgs().
1686   void dumpBundle(ArrayRef<VPValue *> Values);
1687 
1688 public:
1689   VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
1690 
1691   ~VPlanSlp() {
1692     for (auto &KV : BundleToCombined)
1693       delete KV.second;
1694   }
1695 
1696   /// Tries to build an SLP tree rooted at \p Operands and returns a
1697   /// VPInstruction combining \p Operands, if they can be combined.
1698   VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
1699 
1700   /// Return the width of the widest combined bundle in bits.
1701   unsigned getWidestBundleBits() const { return WidestBundleBits; }
1702 
1703   /// Return true if all visited instruction can be combined.
1704   bool isCompletelySLP() const { return CompletelySLP; }
1705 };
1706 } // end namespace llvm
1707 
1708 #endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
1709