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