blob: c19fbe28196b7027ca4facf2579905c6dd5bf78d [file] [log] [blame]
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001//===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko6cadde72017-10-17 21:27:42 +00009//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000010/// \file
11/// This file contains the declarations of the Vectorization Plan base classes:
12/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
13/// VPBlockBase, together implementing a Hierarchical CFG;
14/// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
15/// treated as proper graphs for generic algorithms;
16/// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
17/// within VPBasicBlocks;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000018/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
19/// instruction;
20/// 5. The VPlan class holding a candidate for vectorization;
21/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000022/// These are documented in docs/VectorizationPlan.rst.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000023//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000024//===----------------------------------------------------------------------===//
25
26#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
28
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000029#include "VPlanValue.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000030#include "llvm/ADT/DenseMap.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000031#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000032#include "llvm/ADT/Optional.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000033#include "llvm/ADT/SmallPtrSet.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000034#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000035#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000037#include "llvm/ADT/ilist.h"
38#include "llvm/ADT/ilist_node.h"
39#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000040#include <algorithm>
41#include <cassert>
42#include <cstddef>
43#include <map>
44#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000045
46namespace llvm {
47
Hal Finkel0f1314c2018-01-07 16:02:58 +000048class LoopVectorizationLegality;
49class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000050class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000051class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000052class InnerLoopVectorizer;
Hal Finkel7333aa92017-12-16 01:12:50 +000053class InterleaveGroup;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000054class LoopInfo;
55class raw_ostream;
56class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000057class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000058class VPRegionBlock;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000059class VPlan;
60
61/// A range of powers-of-2 vectorization factors with fixed start and
62/// adjustable end. The range includes start and excludes end, e.g.,:
63/// [1, 9) = {1, 2, 4, 8}
64struct VFRange {
65 // A power of 2.
66 const unsigned Start;
67
68 // Need not be a power of 2. If End <= Start range is empty.
69 unsigned End;
70};
71
72using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000073
74/// In what follows, the term "input IR" refers to code that is fed into the
75/// vectorizer whereas the term "output IR" refers to code that is generated by
76/// the vectorizer.
77
78/// VPIteration represents a single point in the iteration space of the output
79/// (vectorized and/or unrolled) IR loop.
80struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000081 /// in [0..UF)
82 unsigned Part;
83
84 /// in [0..VF)
85 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000086};
87
88/// This is a helper struct for maintaining vectorization state. It's used for
89/// mapping values from the original loop to their corresponding values in
90/// the new loop. Two mappings are maintained: one for vectorized values and
91/// one for scalarized values. Vectorized values are represented with UF
92/// vector values in the new loop, and scalarized values are represented with
93/// UF x VF scalar values in the new loop. UF and VF are the unroll and
94/// vectorization factors, respectively.
95///
96/// Entries can be added to either map with setVectorValue and setScalarValue,
97/// which assert that an entry was not already added before. If an entry is to
98/// replace an existing one, call resetVectorValue and resetScalarValue. This is
99/// currently needed to modify the mapped values during "fix-up" operations that
100/// occur once the first phase of widening is complete. These operations include
101/// type truncation and the second phase of recurrence widening.
102///
103/// Entries from either map can be retrieved using the getVectorValue and
104/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000105struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000106 friend struct VPTransformState;
107
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000108private:
109 /// The unroll factor. Each entry in the vector map contains UF vector values.
110 unsigned UF;
111
112 /// The vectorization factor. Each entry in the scalar map contains UF x VF
113 /// scalar values.
114 unsigned VF;
115
116 /// The vector and scalar map storage. We use std::map and not DenseMap
117 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000118 using VectorParts = SmallVector<Value *, 2>;
119 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000120 std::map<Value *, VectorParts> VectorMapStorage;
121 std::map<Value *, ScalarParts> ScalarMapStorage;
122
123public:
124 /// Construct an empty map with the given unroll and vectorization factors.
125 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
126
127 /// \return True if the map has any vector entry for \p Key.
128 bool hasAnyVectorValue(Value *Key) const {
129 return VectorMapStorage.count(Key);
130 }
131
132 /// \return True if the map has a vector entry for \p Key and \p Part.
133 bool hasVectorValue(Value *Key, unsigned Part) const {
134 assert(Part < UF && "Queried Vector Part is too large.");
135 if (!hasAnyVectorValue(Key))
136 return false;
137 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
138 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
139 return Entry[Part] != nullptr;
140 }
141
142 /// \return True if the map has any scalar entry for \p Key.
143 bool hasAnyScalarValue(Value *Key) const {
144 return ScalarMapStorage.count(Key);
145 }
146
147 /// \return True if the map has a scalar entry for \p Key and \p Instance.
148 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
149 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
150 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
151 if (!hasAnyScalarValue(Key))
152 return false;
153 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
154 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
155 assert(Entry[Instance.Part].size() == VF &&
156 "ScalarParts has wrong dimensions.");
157 return Entry[Instance.Part][Instance.Lane] != nullptr;
158 }
159
160 /// Retrieve the existing vector value that corresponds to \p Key and
161 /// \p Part.
162 Value *getVectorValue(Value *Key, unsigned Part) {
163 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
164 return VectorMapStorage[Key][Part];
165 }
166
167 /// Retrieve the existing scalar value that corresponds to \p Key and
168 /// \p Instance.
169 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
170 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
171 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
172 }
173
174 /// Set a vector value associated with \p Key and \p Part. Assumes such a
175 /// value is not already set. If it is, use resetVectorValue() instead.
176 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
177 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
178 if (!VectorMapStorage.count(Key)) {
179 VectorParts Entry(UF);
180 VectorMapStorage[Key] = Entry;
181 }
182 VectorMapStorage[Key][Part] = Vector;
183 }
184
185 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
186 /// value is not already set.
187 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
188 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
189 if (!ScalarMapStorage.count(Key)) {
190 ScalarParts Entry(UF);
191 // TODO: Consider storing uniform values only per-part, as they occupy
192 // lane 0 only, keeping the other VF-1 redundant entries null.
193 for (unsigned Part = 0; Part < UF; ++Part)
194 Entry[Part].resize(VF, nullptr);
195 ScalarMapStorage[Key] = Entry;
196 }
197 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
198 }
199
200 /// Reset the vector value associated with \p Key for the given \p Part.
201 /// This function can be used to update values that have already been
202 /// vectorized. This is the case for "fix-up" operations including type
203 /// truncation and the second phase of recurrence vectorization.
204 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
205 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
206 VectorMapStorage[Key][Part] = Vector;
207 }
208
209 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
210 /// This function can be used to update values that have already been
211 /// scalarized. This is the case for "fix-up" operations including scalar phi
212 /// nodes for scalarized and predicated instructions.
213 void resetScalarValue(Value *Key, const VPIteration &Instance,
214 Value *Scalar) {
215 assert(hasScalarValue(Key, Instance) &&
216 "Scalar value not set for part and lane");
217 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
218 }
219};
220
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000221/// This class is used to enable the VPlan to invoke a method of ILV. This is
222/// needed until the method is refactored out of ILV and becomes reusable.
223struct VPCallback {
224 virtual ~VPCallback() {}
225 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
226};
227
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000228/// VPTransformState holds information passed down when "executing" a VPlan,
229/// needed for generating the output IR.
230struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000231 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
232 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000233 InnerLoopVectorizer *ILV, VPCallback &Callback)
234 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
235 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000236
237 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
238 unsigned VF;
239 unsigned UF;
240
241 /// Hold the indices to generate specific scalar instructions. Null indicates
242 /// that all instances are to be generated, using either scalar or vector
243 /// instructions.
244 Optional<VPIteration> Instance;
245
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000246 struct DataState {
247 /// A type for vectorized values in the new loop. Each value from the
248 /// original loop, when vectorized, is represented by UF vector values in
249 /// the new unrolled loop, where UF is the unroll factor.
250 typedef SmallVector<Value *, 2> PerPartValuesTy;
251
252 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
253 } Data;
254
255 /// Get the generated Value for a given VPValue and a given Part. Note that
256 /// as some Defs are still created by ILV and managed in its ValueMap, this
257 /// method will delegate the call to ILV in such cases in order to provide
258 /// callers a consistent API.
259 /// \see set.
260 Value *get(VPValue *Def, unsigned Part) {
261 // If Values have been set for this Def return the one relevant for \p Part.
262 if (Data.PerPartOutput.count(Def))
263 return Data.PerPartOutput[Def][Part];
264 // Def is managed by ILV: bring the Values from ValueMap.
265 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
266 }
267
268 /// Set the generated Value for a given VPValue and a given Part.
269 void set(VPValue *Def, Value *V, unsigned Part) {
270 if (!Data.PerPartOutput.count(Def)) {
271 DataState::PerPartValuesTy Entry(UF);
272 Data.PerPartOutput[Def] = Entry;
273 }
274 Data.PerPartOutput[Def][Part] = V;
275 }
276
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000277 /// Hold state information used when constructing the CFG of the output IR,
278 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
279 struct CFGState {
280 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000281 VPBasicBlock *PrevVPBB = nullptr;
282
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000283 /// The previous IR BasicBlock created or used. Initially set to the new
284 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000285 BasicBlock *PrevBB = nullptr;
286
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000287 /// The last IR BasicBlock in the output IR. Set to the new latch
288 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000289 BasicBlock *LastBB = nullptr;
290
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000291 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
292 /// of replication, maps the BasicBlock of the last replica created.
293 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
294
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000295 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000296 } CFG;
297
298 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000299 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000300
301 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000302 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000303
304 /// Hold a reference to the IRBuilder used to generate output IR code.
305 IRBuilder<> &Builder;
306
307 /// Hold a reference to the Value state information used when generating the
308 /// Values of the output IR.
309 VectorizerValueMap &ValueMap;
310
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000311 /// Hold a reference to a mapping between VPValues in VPlan and original
312 /// Values they correspond to.
313 VPValue2ValueTy VPValue2Value;
314
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000315 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000316 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000317
318 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000319};
320
321/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
322/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
323class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000324 friend class VPBlockUtils;
325
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000326private:
327 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
328
329 /// An optional name for the block.
330 std::string Name;
331
332 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
333 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000334 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000335
336 /// List of predecessor blocks.
337 SmallVector<VPBlockBase *, 1> Predecessors;
338
339 /// List of successor blocks.
340 SmallVector<VPBlockBase *, 1> Successors;
341
342 /// Add \p Successor as the last successor to this block.
343 void appendSuccessor(VPBlockBase *Successor) {
344 assert(Successor && "Cannot add nullptr successor!");
345 Successors.push_back(Successor);
346 }
347
348 /// Add \p Predecessor as the last predecessor to this block.
349 void appendPredecessor(VPBlockBase *Predecessor) {
350 assert(Predecessor && "Cannot add nullptr predecessor!");
351 Predecessors.push_back(Predecessor);
352 }
353
354 /// Remove \p Predecessor from the predecessors of this block.
355 void removePredecessor(VPBlockBase *Predecessor) {
356 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
357 assert(Pos && "Predecessor does not exist");
358 Predecessors.erase(Pos);
359 }
360
361 /// Remove \p Successor from the successors of this block.
362 void removeSuccessor(VPBlockBase *Successor) {
363 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
364 assert(Pos && "Successor does not exist");
365 Successors.erase(Pos);
366 }
367
368protected:
369 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000370 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000371
372public:
373 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
374 /// that are actually instantiated. Values of this enumeration are kept in the
375 /// SubclassID field of the VPBlockBase objects. They are used for concrete
376 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000377 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000378
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000379 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000380
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000381 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000382
383 const std::string &getName() const { return Name; }
384
385 void setName(const Twine &newName) { Name = newName.str(); }
386
387 /// \return an ID for the concrete type of this object.
388 /// This is used to implement the classof checks. This should not be used
389 /// for any other purpose, as the values may change as LLVM evolves.
390 unsigned getVPBlockID() const { return SubclassID; }
391
Diego Caballero168d04d2018-05-21 18:14:23 +0000392 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000393 const VPRegionBlock *getParent() const { return Parent; }
394
395 void setParent(VPRegionBlock *P) { Parent = P; }
396
397 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
398 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
399 /// VPBlockBase is a VPBasicBlock, it is returned.
400 const VPBasicBlock *getEntryBasicBlock() const;
401 VPBasicBlock *getEntryBasicBlock();
402
403 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
404 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
405 /// VPBlockBase is a VPBasicBlock, it is returned.
406 const VPBasicBlock *getExitBasicBlock() const;
407 VPBasicBlock *getExitBasicBlock();
408
409 const VPBlocksTy &getSuccessors() const { return Successors; }
410 VPBlocksTy &getSuccessors() { return Successors; }
411
412 const VPBlocksTy &getPredecessors() const { return Predecessors; }
413 VPBlocksTy &getPredecessors() { return Predecessors; }
414
415 /// \return the successor of this VPBlockBase if it has a single successor.
416 /// Otherwise return a null pointer.
417 VPBlockBase *getSingleSuccessor() const {
418 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
419 }
420
421 /// \return the predecessor of this VPBlockBase if it has a single
422 /// predecessor. Otherwise return a null pointer.
423 VPBlockBase *getSinglePredecessor() const {
424 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
425 }
426
Diego Caballero168d04d2018-05-21 18:14:23 +0000427 size_t getNumSuccessors() const { return Successors.size(); }
428 size_t getNumPredecessors() const { return Predecessors.size(); }
429
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000430 /// An Enclosing Block of a block B is any block containing B, including B
431 /// itself. \return the closest enclosing block starting from "this", which
432 /// has successors. \return the root enclosing block if all enclosing blocks
433 /// have no successors.
434 VPBlockBase *getEnclosingBlockWithSuccessors();
435
436 /// \return the closest enclosing block starting from "this", which has
437 /// predecessors. \return the root enclosing block if all enclosing blocks
438 /// have no predecessors.
439 VPBlockBase *getEnclosingBlockWithPredecessors();
440
441 /// \return the successors either attached directly to this VPBlockBase or, if
442 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
443 /// successors of its own, search recursively for the first enclosing
444 /// VPRegionBlock that has successors and return them. If no such
445 /// VPRegionBlock exists, return the (empty) successors of the topmost
446 /// VPBlockBase reached.
447 const VPBlocksTy &getHierarchicalSuccessors() {
448 return getEnclosingBlockWithSuccessors()->getSuccessors();
449 }
450
451 /// \return the hierarchical successor of this VPBlockBase if it has a single
452 /// hierarchical successor. Otherwise return a null pointer.
453 VPBlockBase *getSingleHierarchicalSuccessor() {
454 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
455 }
456
457 /// \return the predecessors either attached directly to this VPBlockBase or,
458 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
459 /// predecessors of its own, search recursively for the first enclosing
460 /// VPRegionBlock that has predecessors and return them. If no such
461 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
462 /// VPBlockBase reached.
463 const VPBlocksTy &getHierarchicalPredecessors() {
464 return getEnclosingBlockWithPredecessors()->getPredecessors();
465 }
466
467 /// \return the hierarchical predecessor of this VPBlockBase if it has a
468 /// single hierarchical predecessor. Otherwise return a null pointer.
469 VPBlockBase *getSingleHierarchicalPredecessor() {
470 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
471 }
472
Diego Caballero168d04d2018-05-21 18:14:23 +0000473 /// Set a given VPBlockBase \p Successor as the single successor of this
474 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
475 /// This VPBlockBase must have no successors.
476 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000477 assert(Successors.empty() && "Setting one successor when others exist.");
478 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000479 }
480
Diego Caballero168d04d2018-05-21 18:14:23 +0000481 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
482 /// successors of this VPBlockBase. This VPBlockBase is not added as
483 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
484 /// successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000485 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
486 assert(Successors.empty() && "Setting two successors when others exist.");
487 appendSuccessor(IfTrue);
488 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000489 }
490
Diego Caballero168d04d2018-05-21 18:14:23 +0000491 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
492 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
493 /// as successor of any VPBasicBlock in \p NewPreds.
494 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
495 assert(Predecessors.empty() && "Block predecessors already set.");
496 for (auto *Pred : NewPreds)
497 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000498 }
499
500 /// The method which generates the output IR that correspond to this
501 /// VPBlockBase, thereby "executing" the VPlan.
502 virtual void execute(struct VPTransformState *State) = 0;
503
504 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
505 static void deleteCFG(VPBlockBase *Entry);
506};
507
508/// VPRecipeBase is a base class modeling a sequence of one or more output IR
509/// instructions.
510class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
511 friend VPBasicBlock;
512
513private:
514 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
515
516 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000517 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000518
519public:
520 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
521 /// that is actually instantiated. Values of this enumeration are kept in the
522 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
523 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000524 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000525 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000526 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000527 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000528 VPInterleaveSC,
529 VPPredInstPHISC,
530 VPReplicateSC,
531 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000532 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000533 VPWidenPHISC,
534 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000535 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000536
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000537 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
538 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000539
540 /// \return an ID for the concrete type of this object.
541 /// This is used to implement the classof checks. This should not be used
542 /// for any other purpose, as the values may change as LLVM evolves.
543 unsigned getVPRecipeID() const { return SubclassID; }
544
545 /// \return the VPBasicBlock which this VPRecipe belongs to.
546 VPBasicBlock *getParent() { return Parent; }
547 const VPBasicBlock *getParent() const { return Parent; }
548
549 /// The method which generates the output IR instructions that correspond to
550 /// this VPRecipe, thereby "executing" the VPlan.
551 virtual void execute(struct VPTransformState &State) = 0;
552
553 /// Each recipe prints itself.
554 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
Florian Hahn7591e4e2018-06-18 11:34:17 +0000555
556 /// Insert an unlinked recipe into a basic block immediately before
557 /// the specified recipe.
558 void insertBefore(VPRecipeBase *InsertPos);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000559};
560
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000561/// This is a concrete Recipe that models a single VPlan-level instruction.
562/// While as any Recipe it may generate a sequence of IR instructions when
563/// executed, these instructions would always form a single-def expression as
564/// the VPInstruction is also a single def-use vertex.
565class VPInstruction : public VPUser, public VPRecipeBase {
566public:
567 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
568 enum { Not = Instruction::OtherOpsEnd + 1 };
569
570private:
571 typedef unsigned char OpcodeTy;
572 OpcodeTy Opcode;
573
574 /// Utility method serving execute(): generates a single instance of the
575 /// modeled instruction.
576 void generateInstruction(VPTransformState &State, unsigned Part);
577
578public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000579 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000580 : VPUser(VPValue::VPInstructionSC, Operands),
581 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
582
Diego Caballero168d04d2018-05-21 18:14:23 +0000583 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
584 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
585
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000586 /// Method to support type inquiry through isa, cast, and dyn_cast.
587 static inline bool classof(const VPValue *V) {
588 return V->getVPValueID() == VPValue::VPInstructionSC;
589 }
590
591 /// Method to support type inquiry through isa, cast, and dyn_cast.
592 static inline bool classof(const VPRecipeBase *R) {
593 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
594 }
595
596 unsigned getOpcode() const { return Opcode; }
597
598 /// Generate the instruction.
599 /// TODO: We currently execute only per-part unless a specific instance is
600 /// provided.
601 void execute(VPTransformState &State) override;
602
603 /// Print the Recipe.
604 void print(raw_ostream &O, const Twine &Indent) const override;
605
606 /// Print the VPInstruction.
607 void print(raw_ostream &O) const;
608};
609
Hal Finkel7333aa92017-12-16 01:12:50 +0000610/// VPWidenRecipe is a recipe for producing a copy of vector type for each
611/// Instruction in its ingredients independently, in order. This recipe covers
612/// most of the traditional vectorization cases where each ingredient transforms
613/// into a vectorized version of itself.
614class VPWidenRecipe : public VPRecipeBase {
615private:
616 /// Hold the ingredients by pointing to their original BasicBlock location.
617 BasicBlock::iterator Begin;
618 BasicBlock::iterator End;
619
620public:
621 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
622 End = I->getIterator();
623 Begin = End++;
624 }
625
626 ~VPWidenRecipe() override = default;
627
628 /// Method to support type inquiry through isa, cast, and dyn_cast.
629 static inline bool classof(const VPRecipeBase *V) {
630 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
631 }
632
633 /// Produce widened copies of all Ingredients.
634 void execute(VPTransformState &State) override;
635
636 /// Augment the recipe to include Instr, if it lies at its End.
637 bool appendInstruction(Instruction *Instr) {
638 if (End != Instr->getIterator())
639 return false;
640 End++;
641 return true;
642 }
643
644 /// Print the recipe.
645 void print(raw_ostream &O, const Twine &Indent) const override;
646};
647
648/// A recipe for handling phi nodes of integer and floating-point inductions,
649/// producing their vector and scalar values.
650class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
651private:
652 PHINode *IV;
653 TruncInst *Trunc;
654
655public:
656 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
657 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
658 ~VPWidenIntOrFpInductionRecipe() override = default;
659
660 /// Method to support type inquiry through isa, cast, and dyn_cast.
661 static inline bool classof(const VPRecipeBase *V) {
662 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
663 }
664
665 /// Generate the vectorized and scalarized versions of the phi node as
666 /// needed by their users.
667 void execute(VPTransformState &State) override;
668
669 /// Print the recipe.
670 void print(raw_ostream &O, const Twine &Indent) const override;
671};
672
673/// A recipe for handling all phi nodes except for integer and FP inductions.
674class VPWidenPHIRecipe : public VPRecipeBase {
675private:
676 PHINode *Phi;
677
678public:
679 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
680 ~VPWidenPHIRecipe() override = default;
681
682 /// Method to support type inquiry through isa, cast, and dyn_cast.
683 static inline bool classof(const VPRecipeBase *V) {
684 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
685 }
686
687 /// Generate the phi/select nodes.
688 void execute(VPTransformState &State) override;
689
690 /// Print the recipe.
691 void print(raw_ostream &O, const Twine &Indent) const override;
692};
693
694/// A recipe for vectorizing a phi-node as a sequence of mask-based select
695/// instructions.
696class VPBlendRecipe : public VPRecipeBase {
697private:
698 PHINode *Phi;
699
700 /// The blend operation is a User of a mask, if not null.
701 std::unique_ptr<VPUser> User;
702
703public:
704 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
705 : VPRecipeBase(VPBlendSC), Phi(Phi) {
706 assert((Phi->getNumIncomingValues() == 1 ||
707 Phi->getNumIncomingValues() == Masks.size()) &&
708 "Expected the same number of incoming values and masks");
709 if (!Masks.empty())
710 User.reset(new VPUser(Masks));
711 }
712
713 /// Method to support type inquiry through isa, cast, and dyn_cast.
714 static inline bool classof(const VPRecipeBase *V) {
715 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
716 }
717
718 /// Generate the phi/select nodes.
719 void execute(VPTransformState &State) override;
720
721 /// Print the recipe.
722 void print(raw_ostream &O, const Twine &Indent) const override;
723};
724
725/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
726/// or stores into one wide load/store and shuffles.
727class VPInterleaveRecipe : public VPRecipeBase {
728private:
729 const InterleaveGroup *IG;
730
731public:
732 VPInterleaveRecipe(const InterleaveGroup *IG)
733 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
734 ~VPInterleaveRecipe() override = default;
735
736 /// Method to support type inquiry through isa, cast, and dyn_cast.
737 static inline bool classof(const VPRecipeBase *V) {
738 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
739 }
740
741 /// Generate the wide load or store, and shuffles.
742 void execute(VPTransformState &State) override;
743
744 /// Print the recipe.
745 void print(raw_ostream &O, const Twine &Indent) const override;
746
747 const InterleaveGroup *getInterleaveGroup() { return IG; }
748};
749
750/// VPReplicateRecipe replicates a given instruction producing multiple scalar
751/// copies of the original scalar type, one per lane, instead of producing a
752/// single copy of widened type for all lanes. If the instruction is known to be
753/// uniform only one copy, per lane zero, will be generated.
754class VPReplicateRecipe : public VPRecipeBase {
755private:
756 /// The instruction being replicated.
757 Instruction *Ingredient;
758
759 /// Indicator if only a single replica per lane is needed.
760 bool IsUniform;
761
762 /// Indicator if the replicas are also predicated.
763 bool IsPredicated;
764
765 /// Indicator if the scalar values should also be packed into a vector.
766 bool AlsoPack;
767
768public:
769 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
770 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
771 IsPredicated(IsPredicated) {
772 // Retain the previous behavior of predicateInstructions(), where an
773 // insert-element of a predicated instruction got hoisted into the
774 // predicated basic block iff it was its only user. This is achieved by
775 // having predicated instructions also pack their values into a vector by
776 // default unless they have a replicated user which uses their scalar value.
777 AlsoPack = IsPredicated && !I->use_empty();
778 }
779
780 ~VPReplicateRecipe() override = default;
781
782 /// Method to support type inquiry through isa, cast, and dyn_cast.
783 static inline bool classof(const VPRecipeBase *V) {
784 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
785 }
786
787 /// Generate replicas of the desired Ingredient. Replicas will be generated
788 /// for all parts and lanes unless a specific part and lane are specified in
789 /// the \p State.
790 void execute(VPTransformState &State) override;
791
792 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
793
794 /// Print the recipe.
795 void print(raw_ostream &O, const Twine &Indent) const override;
796};
797
798/// A recipe for generating conditional branches on the bits of a mask.
799class VPBranchOnMaskRecipe : public VPRecipeBase {
800private:
801 std::unique_ptr<VPUser> User;
802
803public:
804 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
805 if (BlockInMask) // nullptr means all-one mask.
806 User.reset(new VPUser({BlockInMask}));
807 }
808
809 /// Method to support type inquiry through isa, cast, and dyn_cast.
810 static inline bool classof(const VPRecipeBase *V) {
811 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
812 }
813
814 /// Generate the extraction of the appropriate bit from the block mask and the
815 /// conditional branch.
816 void execute(VPTransformState &State) override;
817
818 /// Print the recipe.
819 void print(raw_ostream &O, const Twine &Indent) const override {
820 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
821 if (User)
822 O << *User->getOperand(0);
823 else
824 O << " All-One";
825 O << "\\l\"";
826 }
827};
828
829/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
830/// control converges back from a Branch-on-Mask. The phi nodes are needed in
831/// order to merge values that are set under such a branch and feed their uses.
832/// The phi nodes can be scalar or vector depending on the users of the value.
833/// This recipe works in concert with VPBranchOnMaskRecipe.
834class VPPredInstPHIRecipe : public VPRecipeBase {
835private:
836 Instruction *PredInst;
837
838public:
839 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
840 /// nodes after merging back from a Branch-on-Mask.
841 VPPredInstPHIRecipe(Instruction *PredInst)
842 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
843 ~VPPredInstPHIRecipe() override = default;
844
845 /// Method to support type inquiry through isa, cast, and dyn_cast.
846 static inline bool classof(const VPRecipeBase *V) {
847 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
848 }
849
850 /// Generates phi nodes for live-outs as needed to retain SSA form.
851 void execute(VPTransformState &State) override;
852
853 /// Print the recipe.
854 void print(raw_ostream &O, const Twine &Indent) const override;
855};
856
857/// A Recipe for widening load/store operations.
858/// TODO: We currently execute only per-part unless a specific instance is
859/// provided.
860class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
861private:
862 Instruction &Instr;
863 std::unique_ptr<VPUser> User;
864
865public:
866 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
867 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
868 if (Mask) // Create a VPInstruction to register as a user of the mask.
869 User.reset(new VPUser({Mask}));
870 }
871
872 /// Method to support type inquiry through isa, cast, and dyn_cast.
873 static inline bool classof(const VPRecipeBase *V) {
874 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
875 }
876
877 /// Generate the wide load/store.
878 void execute(VPTransformState &State) override;
879
880 /// Print the recipe.
881 void print(raw_ostream &O, const Twine &Indent) const override;
882};
883
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000884/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
885/// holds a sequence of zero or more VPRecipe's each representing a sequence of
886/// output IR instructions.
887class VPBasicBlock : public VPBlockBase {
888public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000889 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000890
891private:
892 /// The VPRecipes held in the order of output instructions to generate.
893 RecipeListTy Recipes;
894
895public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000896 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
897 : VPBlockBase(VPBasicBlockSC, Name.str()) {
898 if (Recipe)
899 appendRecipe(Recipe);
900 }
901
902 ~VPBasicBlock() override { Recipes.clear(); }
903
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000904 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000905 using iterator = RecipeListTy::iterator;
906 using const_iterator = RecipeListTy::const_iterator;
907 using reverse_iterator = RecipeListTy::reverse_iterator;
908 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000909
910 //===--------------------------------------------------------------------===//
911 /// Recipe iterator methods
912 ///
913 inline iterator begin() { return Recipes.begin(); }
914 inline const_iterator begin() const { return Recipes.begin(); }
915 inline iterator end() { return Recipes.end(); }
916 inline const_iterator end() const { return Recipes.end(); }
917
918 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
919 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
920 inline reverse_iterator rend() { return Recipes.rend(); }
921 inline const_reverse_iterator rend() const { return Recipes.rend(); }
922
923 inline size_t size() const { return Recipes.size(); }
924 inline bool empty() const { return Recipes.empty(); }
925 inline const VPRecipeBase &front() const { return Recipes.front(); }
926 inline VPRecipeBase &front() { return Recipes.front(); }
927 inline const VPRecipeBase &back() const { return Recipes.back(); }
928 inline VPRecipeBase &back() { return Recipes.back(); }
929
Florian Hahn7591e4e2018-06-18 11:34:17 +0000930 /// Returns a reference to the list of recipes.
931 RecipeListTy &getRecipeList() { return Recipes; }
932
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000933 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000934 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
935 return &VPBasicBlock::Recipes;
936 }
937
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000938 /// Method to support type inquiry through isa, cast, and dyn_cast.
939 static inline bool classof(const VPBlockBase *V) {
940 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
941 }
942
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000943 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000944 assert(Recipe && "No recipe to append.");
945 assert(!Recipe->Parent && "Recipe already in VPlan");
946 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000947 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000948 }
949
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000950 /// Augment the existing recipes of a VPBasicBlock with an additional
951 /// \p Recipe as the last recipe.
952 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
953
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000954 /// The method which generates the output IR instructions that correspond to
955 /// this VPBasicBlock, thereby "executing" the VPlan.
956 void execute(struct VPTransformState *State) override;
957
958private:
959 /// Create an IR BasicBlock to hold the output instructions generated by this
960 /// VPBasicBlock, and return it. Update the CFGState accordingly.
961 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
962};
963
964/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
965/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
966/// A VPRegionBlock may indicate that its contents are to be replicated several
967/// times. This is designed to support predicated scalarization, in which a
968/// scalar if-then code structure needs to be generated VF * UF times. Having
969/// this replication indicator helps to keep a single model for multiple
970/// candidate VF's. The actual replication takes place only once the desired VF
971/// and UF have been determined.
972class VPRegionBlock : public VPBlockBase {
973private:
974 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
975 VPBlockBase *Entry;
976
977 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
978 VPBlockBase *Exit;
979
980 /// An indicator whether this region is to generate multiple replicated
981 /// instances of output IR corresponding to its VPBlockBases.
982 bool IsReplicator;
983
984public:
985 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
986 const std::string &Name = "", bool IsReplicator = false)
987 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
988 IsReplicator(IsReplicator) {
989 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
990 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
991 Entry->setParent(this);
992 Exit->setParent(this);
993 }
Diego Caballero168d04d2018-05-21 18:14:23 +0000994 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
995 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
996 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000997
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000998 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000999 if (Entry)
1000 deleteCFG(Entry);
1001 }
1002
1003 /// Method to support type inquiry through isa, cast, and dyn_cast.
1004 static inline bool classof(const VPBlockBase *V) {
1005 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1006 }
1007
1008 const VPBlockBase *getEntry() const { return Entry; }
1009 VPBlockBase *getEntry() { return Entry; }
1010
Diego Caballero168d04d2018-05-21 18:14:23 +00001011 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1012 /// EntryBlock must have no predecessors.
1013 void setEntry(VPBlockBase *EntryBlock) {
1014 assert(EntryBlock->getPredecessors().empty() &&
1015 "Entry block cannot have predecessors.");
1016 Entry = EntryBlock;
1017 EntryBlock->setParent(this);
1018 }
1019
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001020 const VPBlockBase *getExit() const { return Exit; }
1021 VPBlockBase *getExit() { return Exit; }
1022
Diego Caballero168d04d2018-05-21 18:14:23 +00001023 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1024 /// ExitBlock must have no successors.
1025 void setExit(VPBlockBase *ExitBlock) {
1026 assert(ExitBlock->getSuccessors().empty() &&
1027 "Exit block cannot have successors.");
1028 Exit = ExitBlock;
1029 ExitBlock->setParent(this);
1030 }
1031
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001032 /// An indicator whether this region is to generate multiple replicated
1033 /// instances of output IR corresponding to its VPBlockBases.
1034 bool isReplicator() const { return IsReplicator; }
1035
1036 /// The method which generates the output IR instructions that correspond to
1037 /// this VPRegionBlock, thereby "executing" the VPlan.
1038 void execute(struct VPTransformState *State) override;
1039};
1040
1041/// VPlan models a candidate for vectorization, encoding various decisions take
1042/// to produce efficient output IR, including which branches, basic-blocks and
1043/// output IR instructions to generate, and their cost. VPlan holds a
1044/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1045/// VPBlock.
1046class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001047 friend class VPlanPrinter;
1048
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001049private:
1050 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1051 VPBlockBase *Entry;
1052
1053 /// Holds the VFs applicable to this VPlan.
1054 SmallSet<unsigned, 2> VFs;
1055
1056 /// Holds the name of the VPlan, for printing.
1057 std::string Name;
1058
Diego Caballero168d04d2018-05-21 18:14:23 +00001059 /// Holds all the external definitions created for this VPlan.
1060 // TODO: Introduce a specific representation for external definitions in
1061 // VPlan. External definitions must be immutable and hold a pointer to its
1062 // underlying IR that will be used to implement its structural comparison
1063 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001064 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001065
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001066 /// Holds a mapping between Values and their corresponding VPValue inside
1067 /// VPlan.
1068 Value2VPValueTy Value2VPValue;
1069
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001070public:
1071 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1072
1073 ~VPlan() {
1074 if (Entry)
1075 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001076 for (auto &MapEntry : Value2VPValue)
1077 delete MapEntry.second;
Diego Caballero168d04d2018-05-21 18:14:23 +00001078 for (VPValue *Def : VPExternalDefs)
1079 delete Def;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001080 }
1081
1082 /// Generate the IR code for this VPlan.
1083 void execute(struct VPTransformState *State);
1084
1085 VPBlockBase *getEntry() { return Entry; }
1086 const VPBlockBase *getEntry() const { return Entry; }
1087
1088 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1089
1090 void addVF(unsigned VF) { VFs.insert(VF); }
1091
1092 bool hasVF(unsigned VF) { return VFs.count(VF); }
1093
1094 const std::string &getName() const { return Name; }
1095
1096 void setName(const Twine &newName) { Name = newName.str(); }
1097
Diego Caballero168d04d2018-05-21 18:14:23 +00001098 /// Add \p VPVal to the pool of external definitions if it's not already
1099 /// in the pool.
1100 void addExternalDef(VPValue *VPVal) {
1101 VPExternalDefs.insert(VPVal);
1102 }
1103
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001104 void addVPValue(Value *V) {
1105 assert(V && "Trying to add a null Value to VPlan");
1106 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1107 Value2VPValue[V] = new VPValue();
1108 }
1109
1110 VPValue *getVPValue(Value *V) {
1111 assert(V && "Trying to get the VPValue of a null Value");
1112 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1113 return Value2VPValue[V];
1114 }
1115
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001116private:
1117 /// Add to the given dominator tree the header block and every new basic block
1118 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001119 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001120 BasicBlock *LoopPreHeaderBB,
1121 BasicBlock *LoopLatchBB);
1122};
1123
1124/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1125/// indented and follows the dot format.
1126class VPlanPrinter {
1127 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1128 friend inline raw_ostream &operator<<(raw_ostream &OS,
1129 const struct VPlanIngredient &I);
1130
1131private:
1132 raw_ostream &OS;
1133 VPlan &Plan;
1134 unsigned Depth;
1135 unsigned TabWidth = 2;
1136 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001137 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001138 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1139
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001140 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1141
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001142 /// Handle indentation.
1143 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1144
1145 /// Print a given \p Block of the Plan.
1146 void dumpBlock(const VPBlockBase *Block);
1147
1148 /// Print the information related to the CFG edges going out of a given
1149 /// \p Block, followed by printing the successor blocks themselves.
1150 void dumpEdges(const VPBlockBase *Block);
1151
1152 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1153 /// its successor blocks.
1154 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1155
1156 /// Print a given \p Region of the Plan.
1157 void dumpRegion(const VPRegionBlock *Region);
1158
1159 unsigned getOrCreateBID(const VPBlockBase *Block) {
1160 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1161 }
1162
1163 const Twine getOrCreateName(const VPBlockBase *Block);
1164
1165 const Twine getUID(const VPBlockBase *Block);
1166
1167 /// Print the information related to a CFG edge between two VPBlockBases.
1168 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1169 const Twine &Label);
1170
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001171 void dump();
1172
1173 static void printAsIngredient(raw_ostream &O, Value *V);
1174};
1175
1176struct VPlanIngredient {
1177 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001178
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001179 VPlanIngredient(Value *V) : V(V) {}
1180};
1181
1182inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1183 VPlanPrinter::printAsIngredient(OS, I.V);
1184 return OS;
1185}
1186
1187inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1188 VPlanPrinter Printer(OS, Plan);
1189 Printer.dump();
1190 return OS;
1191}
1192
1193//===--------------------------------------------------------------------===//
1194// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
1195//===--------------------------------------------------------------------===//
1196
1197// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1198// graph of VPBlockBase nodes...
1199
1200template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001201 using NodeRef = VPBlockBase *;
1202 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001203
1204 static NodeRef getEntryNode(NodeRef N) { return N; }
1205
1206 static inline ChildIteratorType child_begin(NodeRef N) {
1207 return N->getSuccessors().begin();
1208 }
1209
1210 static inline ChildIteratorType child_end(NodeRef N) {
1211 return N->getSuccessors().end();
1212 }
1213};
1214
1215template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001216 using NodeRef = const VPBlockBase *;
1217 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001218
1219 static NodeRef getEntryNode(NodeRef N) { return N; }
1220
1221 static inline ChildIteratorType child_begin(NodeRef N) {
1222 return N->getSuccessors().begin();
1223 }
1224
1225 static inline ChildIteratorType child_end(NodeRef N) {
1226 return N->getSuccessors().end();
1227 }
1228};
1229
1230// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1231// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1232// for a VPBlockBase is considered to be when traversing the predecessors of a
1233// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001234template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001235 using NodeRef = VPBlockBase *;
1236 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001237
1238 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1239 return B;
1240 }
1241
1242 static inline ChildIteratorType child_begin(NodeRef N) {
1243 return N->getPredecessors().begin();
1244 }
1245
1246 static inline ChildIteratorType child_end(NodeRef N) {
1247 return N->getPredecessors().end();
1248 }
1249};
1250
Diego Caballero168d04d2018-05-21 18:14:23 +00001251//===----------------------------------------------------------------------===//
1252// VPlan Utilities
1253//===----------------------------------------------------------------------===//
1254
1255/// Class that provides utilities for VPBlockBases in VPlan.
1256class VPBlockUtils {
1257public:
1258 VPBlockUtils() = delete;
1259
1260 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1261 /// NewBlock as successor of \p BlockPtr and \p Block as predecessor of \p
1262 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p NewBlock
1263 /// must have neither successors nor predecessors.
1264 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1265 assert(NewBlock->getSuccessors().empty() &&
1266 "Can't insert new block with successors.");
1267 // TODO: move successors from BlockPtr to NewBlock when this functionality
1268 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1269 // already has successors.
1270 BlockPtr->setOneSuccessor(NewBlock);
1271 NewBlock->setPredecessors({BlockPtr});
1272 NewBlock->setParent(BlockPtr->getParent());
1273 }
1274
1275 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1276 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1277 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1278 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
1279 /// and \p IfTrue and \p IfFalse must have neither successors nor
1280 /// predecessors.
1281 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1282 VPBlockBase *BlockPtr) {
1283 assert(IfTrue->getSuccessors().empty() &&
1284 "Can't insert IfTrue with successors.");
1285 assert(IfFalse->getSuccessors().empty() &&
1286 "Can't insert IfFalse with successors.");
1287 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
1288 IfTrue->setPredecessors({BlockPtr});
1289 IfFalse->setPredecessors({BlockPtr});
1290 IfTrue->setParent(BlockPtr->getParent());
1291 IfFalse->setParent(BlockPtr->getParent());
1292 }
1293
1294 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1295 /// the successors of \p From and \p From to the predecessors of \p To. Both
1296 /// VPBlockBases must have the same parent, which can be null. Both
1297 /// VPBlockBases can be already connected to other VPBlockBases.
1298 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1299 assert((From->getParent() == To->getParent()) &&
1300 "Can't connect two block with different parents");
1301 assert(From->getNumSuccessors() < 2 &&
1302 "Blocks can't have more than two successors.");
1303 From->appendSuccessor(To);
1304 To->appendPredecessor(From);
1305 }
1306
1307 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1308 /// from the successors of \p From and \p From from the predecessors of \p To.
1309 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1310 assert(To && "Successor to disconnect is null.");
1311 From->removeSuccessor(To);
1312 To->removePredecessor(From);
1313 }
1314};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001315
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001316} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001317
1318#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H