blob: 9f7bd5d8ea7539ef4ac7d8588b85d958490c31a7 [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"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000033#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000036#include "llvm/ADT/ilist.h"
37#include "llvm/ADT/ilist_node.h"
38#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000039#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <map>
43#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000044
45namespace llvm {
46
Hal Finkel0f1314c2018-01-07 16:02:58 +000047class LoopVectorizationLegality;
48class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000049class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000050class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000051class InnerLoopVectorizer;
Hal Finkel7333aa92017-12-16 01:12:50 +000052class InterleaveGroup;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000053class LoopInfo;
54class raw_ostream;
55class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000056class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057class VPRegionBlock;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000058class VPlan;
59
60/// A range of powers-of-2 vectorization factors with fixed start and
61/// adjustable end. The range includes start and excludes end, e.g.,:
62/// [1, 9) = {1, 2, 4, 8}
63struct VFRange {
64 // A power of 2.
65 const unsigned Start;
66
67 // Need not be a power of 2. If End <= Start range is empty.
68 unsigned End;
69};
70
71using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000072
73/// In what follows, the term "input IR" refers to code that is fed into the
74/// vectorizer whereas the term "output IR" refers to code that is generated by
75/// the vectorizer.
76
77/// VPIteration represents a single point in the iteration space of the output
78/// (vectorized and/or unrolled) IR loop.
79struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000080 /// in [0..UF)
81 unsigned Part;
82
83 /// in [0..VF)
84 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000085};
86
87/// This is a helper struct for maintaining vectorization state. It's used for
88/// mapping values from the original loop to their corresponding values in
89/// the new loop. Two mappings are maintained: one for vectorized values and
90/// one for scalarized values. Vectorized values are represented with UF
91/// vector values in the new loop, and scalarized values are represented with
92/// UF x VF scalar values in the new loop. UF and VF are the unroll and
93/// vectorization factors, respectively.
94///
95/// Entries can be added to either map with setVectorValue and setScalarValue,
96/// which assert that an entry was not already added before. If an entry is to
97/// replace an existing one, call resetVectorValue and resetScalarValue. This is
98/// currently needed to modify the mapped values during "fix-up" operations that
99/// occur once the first phase of widening is complete. These operations include
100/// type truncation and the second phase of recurrence widening.
101///
102/// Entries from either map can be retrieved using the getVectorValue and
103/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000104struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000105 friend struct VPTransformState;
106
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000107private:
108 /// The unroll factor. Each entry in the vector map contains UF vector values.
109 unsigned UF;
110
111 /// The vectorization factor. Each entry in the scalar map contains UF x VF
112 /// scalar values.
113 unsigned VF;
114
115 /// The vector and scalar map storage. We use std::map and not DenseMap
116 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000117 using VectorParts = SmallVector<Value *, 2>;
118 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000119 std::map<Value *, VectorParts> VectorMapStorage;
120 std::map<Value *, ScalarParts> ScalarMapStorage;
121
122public:
123 /// Construct an empty map with the given unroll and vectorization factors.
124 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
125
126 /// \return True if the map has any vector entry for \p Key.
127 bool hasAnyVectorValue(Value *Key) const {
128 return VectorMapStorage.count(Key);
129 }
130
131 /// \return True if the map has a vector entry for \p Key and \p Part.
132 bool hasVectorValue(Value *Key, unsigned Part) const {
133 assert(Part < UF && "Queried Vector Part is too large.");
134 if (!hasAnyVectorValue(Key))
135 return false;
136 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
137 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
138 return Entry[Part] != nullptr;
139 }
140
141 /// \return True if the map has any scalar entry for \p Key.
142 bool hasAnyScalarValue(Value *Key) const {
143 return ScalarMapStorage.count(Key);
144 }
145
146 /// \return True if the map has a scalar entry for \p Key and \p Instance.
147 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
148 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
149 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
150 if (!hasAnyScalarValue(Key))
151 return false;
152 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
153 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
154 assert(Entry[Instance.Part].size() == VF &&
155 "ScalarParts has wrong dimensions.");
156 return Entry[Instance.Part][Instance.Lane] != nullptr;
157 }
158
159 /// Retrieve the existing vector value that corresponds to \p Key and
160 /// \p Part.
161 Value *getVectorValue(Value *Key, unsigned Part) {
162 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
163 return VectorMapStorage[Key][Part];
164 }
165
166 /// Retrieve the existing scalar value that corresponds to \p Key and
167 /// \p Instance.
168 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
169 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
170 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
171 }
172
173 /// Set a vector value associated with \p Key and \p Part. Assumes such a
174 /// value is not already set. If it is, use resetVectorValue() instead.
175 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
176 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
177 if (!VectorMapStorage.count(Key)) {
178 VectorParts Entry(UF);
179 VectorMapStorage[Key] = Entry;
180 }
181 VectorMapStorage[Key][Part] = Vector;
182 }
183
184 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
185 /// value is not already set.
186 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
187 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
188 if (!ScalarMapStorage.count(Key)) {
189 ScalarParts Entry(UF);
190 // TODO: Consider storing uniform values only per-part, as they occupy
191 // lane 0 only, keeping the other VF-1 redundant entries null.
192 for (unsigned Part = 0; Part < UF; ++Part)
193 Entry[Part].resize(VF, nullptr);
194 ScalarMapStorage[Key] = Entry;
195 }
196 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
197 }
198
199 /// Reset the vector value associated with \p Key for the given \p Part.
200 /// This function can be used to update values that have already been
201 /// vectorized. This is the case for "fix-up" operations including type
202 /// truncation and the second phase of recurrence vectorization.
203 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
204 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
205 VectorMapStorage[Key][Part] = Vector;
206 }
207
208 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
209 /// This function can be used to update values that have already been
210 /// scalarized. This is the case for "fix-up" operations including scalar phi
211 /// nodes for scalarized and predicated instructions.
212 void resetScalarValue(Value *Key, const VPIteration &Instance,
213 Value *Scalar) {
214 assert(hasScalarValue(Key, Instance) &&
215 "Scalar value not set for part and lane");
216 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
217 }
218};
219
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000220/// This class is used to enable the VPlan to invoke a method of ILV. This is
221/// needed until the method is refactored out of ILV and becomes reusable.
222struct VPCallback {
223 virtual ~VPCallback() {}
224 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
225};
226
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000227/// VPTransformState holds information passed down when "executing" a VPlan,
228/// needed for generating the output IR.
229struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000230 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
231 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000232 InnerLoopVectorizer *ILV, VPCallback &Callback)
233 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
234 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000235
236 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
237 unsigned VF;
238 unsigned UF;
239
240 /// Hold the indices to generate specific scalar instructions. Null indicates
241 /// that all instances are to be generated, using either scalar or vector
242 /// instructions.
243 Optional<VPIteration> Instance;
244
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000245 struct DataState {
246 /// A type for vectorized values in the new loop. Each value from the
247 /// original loop, when vectorized, is represented by UF vector values in
248 /// the new unrolled loop, where UF is the unroll factor.
249 typedef SmallVector<Value *, 2> PerPartValuesTy;
250
251 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
252 } Data;
253
254 /// Get the generated Value for a given VPValue and a given Part. Note that
255 /// as some Defs are still created by ILV and managed in its ValueMap, this
256 /// method will delegate the call to ILV in such cases in order to provide
257 /// callers a consistent API.
258 /// \see set.
259 Value *get(VPValue *Def, unsigned Part) {
260 // If Values have been set for this Def return the one relevant for \p Part.
261 if (Data.PerPartOutput.count(Def))
262 return Data.PerPartOutput[Def][Part];
263 // Def is managed by ILV: bring the Values from ValueMap.
264 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
265 }
266
267 /// Set the generated Value for a given VPValue and a given Part.
268 void set(VPValue *Def, Value *V, unsigned Part) {
269 if (!Data.PerPartOutput.count(Def)) {
270 DataState::PerPartValuesTy Entry(UF);
271 Data.PerPartOutput[Def] = Entry;
272 }
273 Data.PerPartOutput[Def][Part] = V;
274 }
275
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000276 /// Hold state information used when constructing the CFG of the output IR,
277 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
278 struct CFGState {
279 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000280 VPBasicBlock *PrevVPBB = nullptr;
281
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000282 /// The previous IR BasicBlock created or used. Initially set to the new
283 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000284 BasicBlock *PrevBB = nullptr;
285
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000286 /// The last IR BasicBlock in the output IR. Set to the new latch
287 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000288 BasicBlock *LastBB = nullptr;
289
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000290 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
291 /// of replication, maps the BasicBlock of the last replica created.
292 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
293
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000294 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000295 } CFG;
296
297 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000298 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000299
300 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000301 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000302
303 /// Hold a reference to the IRBuilder used to generate output IR code.
304 IRBuilder<> &Builder;
305
306 /// Hold a reference to the Value state information used when generating the
307 /// Values of the output IR.
308 VectorizerValueMap &ValueMap;
309
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000310 /// Hold a reference to a mapping between VPValues in VPlan and original
311 /// Values they correspond to.
312 VPValue2ValueTy VPValue2Value;
313
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000314 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000315 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000316
317 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000318};
319
320/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
321/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
322class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000323 friend class VPBlockUtils;
324
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000325private:
326 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
327
328 /// An optional name for the block.
329 std::string Name;
330
331 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
332 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000333 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000334
335 /// List of predecessor blocks.
336 SmallVector<VPBlockBase *, 1> Predecessors;
337
338 /// List of successor blocks.
339 SmallVector<VPBlockBase *, 1> Successors;
340
341 /// Add \p Successor as the last successor to this block.
342 void appendSuccessor(VPBlockBase *Successor) {
343 assert(Successor && "Cannot add nullptr successor!");
344 Successors.push_back(Successor);
345 }
346
347 /// Add \p Predecessor as the last predecessor to this block.
348 void appendPredecessor(VPBlockBase *Predecessor) {
349 assert(Predecessor && "Cannot add nullptr predecessor!");
350 Predecessors.push_back(Predecessor);
351 }
352
353 /// Remove \p Predecessor from the predecessors of this block.
354 void removePredecessor(VPBlockBase *Predecessor) {
355 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
356 assert(Pos && "Predecessor does not exist");
357 Predecessors.erase(Pos);
358 }
359
360 /// Remove \p Successor from the successors of this block.
361 void removeSuccessor(VPBlockBase *Successor) {
362 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
363 assert(Pos && "Successor does not exist");
364 Successors.erase(Pos);
365 }
366
367protected:
368 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000369 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000370
371public:
372 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
373 /// that are actually instantiated. Values of this enumeration are kept in the
374 /// SubclassID field of the VPBlockBase objects. They are used for concrete
375 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000376 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000377
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000378 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000379
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000380 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000381
382 const std::string &getName() const { return Name; }
383
384 void setName(const Twine &newName) { Name = newName.str(); }
385
386 /// \return an ID for the concrete type of this object.
387 /// This is used to implement the classof checks. This should not be used
388 /// for any other purpose, as the values may change as LLVM evolves.
389 unsigned getVPBlockID() const { return SubclassID; }
390
Diego Caballero168d04d2018-05-21 18:14:23 +0000391 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000392 const VPRegionBlock *getParent() const { return Parent; }
393
394 void setParent(VPRegionBlock *P) { Parent = P; }
395
396 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
397 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
398 /// VPBlockBase is a VPBasicBlock, it is returned.
399 const VPBasicBlock *getEntryBasicBlock() const;
400 VPBasicBlock *getEntryBasicBlock();
401
402 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
403 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
404 /// VPBlockBase is a VPBasicBlock, it is returned.
405 const VPBasicBlock *getExitBasicBlock() const;
406 VPBasicBlock *getExitBasicBlock();
407
408 const VPBlocksTy &getSuccessors() const { return Successors; }
409 VPBlocksTy &getSuccessors() { return Successors; }
410
411 const VPBlocksTy &getPredecessors() const { return Predecessors; }
412 VPBlocksTy &getPredecessors() { return Predecessors; }
413
414 /// \return the successor of this VPBlockBase if it has a single successor.
415 /// Otherwise return a null pointer.
416 VPBlockBase *getSingleSuccessor() const {
417 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
418 }
419
420 /// \return the predecessor of this VPBlockBase if it has a single
421 /// predecessor. Otherwise return a null pointer.
422 VPBlockBase *getSinglePredecessor() const {
423 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
424 }
425
Diego Caballero168d04d2018-05-21 18:14:23 +0000426 size_t getNumSuccessors() const { return Successors.size(); }
427 size_t getNumPredecessors() const { return Predecessors.size(); }
428
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000429 /// An Enclosing Block of a block B is any block containing B, including B
430 /// itself. \return the closest enclosing block starting from "this", which
431 /// has successors. \return the root enclosing block if all enclosing blocks
432 /// have no successors.
433 VPBlockBase *getEnclosingBlockWithSuccessors();
434
435 /// \return the closest enclosing block starting from "this", which has
436 /// predecessors. \return the root enclosing block if all enclosing blocks
437 /// have no predecessors.
438 VPBlockBase *getEnclosingBlockWithPredecessors();
439
440 /// \return the successors either attached directly to this VPBlockBase or, if
441 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
442 /// successors of its own, search recursively for the first enclosing
443 /// VPRegionBlock that has successors and return them. If no such
444 /// VPRegionBlock exists, return the (empty) successors of the topmost
445 /// VPBlockBase reached.
446 const VPBlocksTy &getHierarchicalSuccessors() {
447 return getEnclosingBlockWithSuccessors()->getSuccessors();
448 }
449
450 /// \return the hierarchical successor of this VPBlockBase if it has a single
451 /// hierarchical successor. Otherwise return a null pointer.
452 VPBlockBase *getSingleHierarchicalSuccessor() {
453 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
454 }
455
456 /// \return the predecessors either attached directly to this VPBlockBase or,
457 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
458 /// predecessors of its own, search recursively for the first enclosing
459 /// VPRegionBlock that has predecessors and return them. If no such
460 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
461 /// VPBlockBase reached.
462 const VPBlocksTy &getHierarchicalPredecessors() {
463 return getEnclosingBlockWithPredecessors()->getPredecessors();
464 }
465
466 /// \return the hierarchical predecessor of this VPBlockBase if it has a
467 /// single hierarchical predecessor. Otherwise return a null pointer.
468 VPBlockBase *getSingleHierarchicalPredecessor() {
469 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
470 }
471
Diego Caballero168d04d2018-05-21 18:14:23 +0000472 /// Set a given VPBlockBase \p Successor as the single successor of this
473 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
474 /// This VPBlockBase must have no successors.
475 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000476 assert(Successors.empty() && "Setting one successor when others exist.");
477 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000478 }
479
Diego Caballero168d04d2018-05-21 18:14:23 +0000480 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
481 /// successors of this VPBlockBase. This VPBlockBase is not added as
482 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
483 /// successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000484 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
485 assert(Successors.empty() && "Setting two successors when others exist.");
486 appendSuccessor(IfTrue);
487 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000488 }
489
Diego Caballero168d04d2018-05-21 18:14:23 +0000490 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
491 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
492 /// as successor of any VPBasicBlock in \p NewPreds.
493 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
494 assert(Predecessors.empty() && "Block predecessors already set.");
495 for (auto *Pred : NewPreds)
496 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000497 }
498
499 /// The method which generates the output IR that correspond to this
500 /// VPBlockBase, thereby "executing" the VPlan.
501 virtual void execute(struct VPTransformState *State) = 0;
502
503 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
504 static void deleteCFG(VPBlockBase *Entry);
505};
506
507/// VPRecipeBase is a base class modeling a sequence of one or more output IR
508/// instructions.
509class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
510 friend VPBasicBlock;
511
512private:
513 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
514
515 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000516 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000517
518public:
519 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
520 /// that is actually instantiated. Values of this enumeration are kept in the
521 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
522 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000523 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000524 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000525 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000526 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000527 VPInterleaveSC,
528 VPPredInstPHISC,
529 VPReplicateSC,
530 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000531 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000532 VPWidenPHISC,
533 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000534 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000535
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000536 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
537 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000538
539 /// \return an ID for the concrete type of this object.
540 /// This is used to implement the classof checks. This should not be used
541 /// for any other purpose, as the values may change as LLVM evolves.
542 unsigned getVPRecipeID() const { return SubclassID; }
543
544 /// \return the VPBasicBlock which this VPRecipe belongs to.
545 VPBasicBlock *getParent() { return Parent; }
546 const VPBasicBlock *getParent() const { return Parent; }
547
548 /// The method which generates the output IR instructions that correspond to
549 /// this VPRecipe, thereby "executing" the VPlan.
550 virtual void execute(struct VPTransformState &State) = 0;
551
552 /// Each recipe prints itself.
553 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
554};
555
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000556/// This is a concrete Recipe that models a single VPlan-level instruction.
557/// While as any Recipe it may generate a sequence of IR instructions when
558/// executed, these instructions would always form a single-def expression as
559/// the VPInstruction is also a single def-use vertex.
560class VPInstruction : public VPUser, public VPRecipeBase {
561public:
562 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
563 enum { Not = Instruction::OtherOpsEnd + 1 };
564
565private:
566 typedef unsigned char OpcodeTy;
567 OpcodeTy Opcode;
568
569 /// Utility method serving execute(): generates a single instance of the
570 /// modeled instruction.
571 void generateInstruction(VPTransformState &State, unsigned Part);
572
573public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000574 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000575 : VPUser(VPValue::VPInstructionSC, Operands),
576 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
577
Diego Caballero168d04d2018-05-21 18:14:23 +0000578 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
579 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
580
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000581 /// Method to support type inquiry through isa, cast, and dyn_cast.
582 static inline bool classof(const VPValue *V) {
583 return V->getVPValueID() == VPValue::VPInstructionSC;
584 }
585
586 /// Method to support type inquiry through isa, cast, and dyn_cast.
587 static inline bool classof(const VPRecipeBase *R) {
588 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
589 }
590
591 unsigned getOpcode() const { return Opcode; }
592
593 /// Generate the instruction.
594 /// TODO: We currently execute only per-part unless a specific instance is
595 /// provided.
596 void execute(VPTransformState &State) override;
597
598 /// Print the Recipe.
599 void print(raw_ostream &O, const Twine &Indent) const override;
600
601 /// Print the VPInstruction.
602 void print(raw_ostream &O) const;
603};
604
Hal Finkel7333aa92017-12-16 01:12:50 +0000605/// VPWidenRecipe is a recipe for producing a copy of vector type for each
606/// Instruction in its ingredients independently, in order. This recipe covers
607/// most of the traditional vectorization cases where each ingredient transforms
608/// into a vectorized version of itself.
609class VPWidenRecipe : public VPRecipeBase {
610private:
611 /// Hold the ingredients by pointing to their original BasicBlock location.
612 BasicBlock::iterator Begin;
613 BasicBlock::iterator End;
614
615public:
616 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
617 End = I->getIterator();
618 Begin = End++;
619 }
620
621 ~VPWidenRecipe() override = default;
622
623 /// Method to support type inquiry through isa, cast, and dyn_cast.
624 static inline bool classof(const VPRecipeBase *V) {
625 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
626 }
627
628 /// Produce widened copies of all Ingredients.
629 void execute(VPTransformState &State) override;
630
631 /// Augment the recipe to include Instr, if it lies at its End.
632 bool appendInstruction(Instruction *Instr) {
633 if (End != Instr->getIterator())
634 return false;
635 End++;
636 return true;
637 }
638
639 /// Print the recipe.
640 void print(raw_ostream &O, const Twine &Indent) const override;
641};
642
643/// A recipe for handling phi nodes of integer and floating-point inductions,
644/// producing their vector and scalar values.
645class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
646private:
647 PHINode *IV;
648 TruncInst *Trunc;
649
650public:
651 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
652 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
653 ~VPWidenIntOrFpInductionRecipe() override = default;
654
655 /// Method to support type inquiry through isa, cast, and dyn_cast.
656 static inline bool classof(const VPRecipeBase *V) {
657 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
658 }
659
660 /// Generate the vectorized and scalarized versions of the phi node as
661 /// needed by their users.
662 void execute(VPTransformState &State) override;
663
664 /// Print the recipe.
665 void print(raw_ostream &O, const Twine &Indent) const override;
666};
667
668/// A recipe for handling all phi nodes except for integer and FP inductions.
669class VPWidenPHIRecipe : public VPRecipeBase {
670private:
671 PHINode *Phi;
672
673public:
674 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
675 ~VPWidenPHIRecipe() override = default;
676
677 /// Method to support type inquiry through isa, cast, and dyn_cast.
678 static inline bool classof(const VPRecipeBase *V) {
679 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
680 }
681
682 /// Generate the phi/select nodes.
683 void execute(VPTransformState &State) override;
684
685 /// Print the recipe.
686 void print(raw_ostream &O, const Twine &Indent) const override;
687};
688
689/// A recipe for vectorizing a phi-node as a sequence of mask-based select
690/// instructions.
691class VPBlendRecipe : public VPRecipeBase {
692private:
693 PHINode *Phi;
694
695 /// The blend operation is a User of a mask, if not null.
696 std::unique_ptr<VPUser> User;
697
698public:
699 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
700 : VPRecipeBase(VPBlendSC), Phi(Phi) {
701 assert((Phi->getNumIncomingValues() == 1 ||
702 Phi->getNumIncomingValues() == Masks.size()) &&
703 "Expected the same number of incoming values and masks");
704 if (!Masks.empty())
705 User.reset(new VPUser(Masks));
706 }
707
708 /// Method to support type inquiry through isa, cast, and dyn_cast.
709 static inline bool classof(const VPRecipeBase *V) {
710 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
711 }
712
713 /// Generate the phi/select nodes.
714 void execute(VPTransformState &State) override;
715
716 /// Print the recipe.
717 void print(raw_ostream &O, const Twine &Indent) const override;
718};
719
720/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
721/// or stores into one wide load/store and shuffles.
722class VPInterleaveRecipe : public VPRecipeBase {
723private:
724 const InterleaveGroup *IG;
725
726public:
727 VPInterleaveRecipe(const InterleaveGroup *IG)
728 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
729 ~VPInterleaveRecipe() override = default;
730
731 /// Method to support type inquiry through isa, cast, and dyn_cast.
732 static inline bool classof(const VPRecipeBase *V) {
733 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
734 }
735
736 /// Generate the wide load or store, and shuffles.
737 void execute(VPTransformState &State) override;
738
739 /// Print the recipe.
740 void print(raw_ostream &O, const Twine &Indent) const override;
741
742 const InterleaveGroup *getInterleaveGroup() { return IG; }
743};
744
745/// VPReplicateRecipe replicates a given instruction producing multiple scalar
746/// copies of the original scalar type, one per lane, instead of producing a
747/// single copy of widened type for all lanes. If the instruction is known to be
748/// uniform only one copy, per lane zero, will be generated.
749class VPReplicateRecipe : public VPRecipeBase {
750private:
751 /// The instruction being replicated.
752 Instruction *Ingredient;
753
754 /// Indicator if only a single replica per lane is needed.
755 bool IsUniform;
756
757 /// Indicator if the replicas are also predicated.
758 bool IsPredicated;
759
760 /// Indicator if the scalar values should also be packed into a vector.
761 bool AlsoPack;
762
763public:
764 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
765 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
766 IsPredicated(IsPredicated) {
767 // Retain the previous behavior of predicateInstructions(), where an
768 // insert-element of a predicated instruction got hoisted into the
769 // predicated basic block iff it was its only user. This is achieved by
770 // having predicated instructions also pack their values into a vector by
771 // default unless they have a replicated user which uses their scalar value.
772 AlsoPack = IsPredicated && !I->use_empty();
773 }
774
775 ~VPReplicateRecipe() override = default;
776
777 /// Method to support type inquiry through isa, cast, and dyn_cast.
778 static inline bool classof(const VPRecipeBase *V) {
779 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
780 }
781
782 /// Generate replicas of the desired Ingredient. Replicas will be generated
783 /// for all parts and lanes unless a specific part and lane are specified in
784 /// the \p State.
785 void execute(VPTransformState &State) override;
786
787 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
788
789 /// Print the recipe.
790 void print(raw_ostream &O, const Twine &Indent) const override;
791};
792
793/// A recipe for generating conditional branches on the bits of a mask.
794class VPBranchOnMaskRecipe : public VPRecipeBase {
795private:
796 std::unique_ptr<VPUser> User;
797
798public:
799 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
800 if (BlockInMask) // nullptr means all-one mask.
801 User.reset(new VPUser({BlockInMask}));
802 }
803
804 /// Method to support type inquiry through isa, cast, and dyn_cast.
805 static inline bool classof(const VPRecipeBase *V) {
806 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
807 }
808
809 /// Generate the extraction of the appropriate bit from the block mask and the
810 /// conditional branch.
811 void execute(VPTransformState &State) override;
812
813 /// Print the recipe.
814 void print(raw_ostream &O, const Twine &Indent) const override {
815 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
816 if (User)
817 O << *User->getOperand(0);
818 else
819 O << " All-One";
820 O << "\\l\"";
821 }
822};
823
824/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
825/// control converges back from a Branch-on-Mask. The phi nodes are needed in
826/// order to merge values that are set under such a branch and feed their uses.
827/// The phi nodes can be scalar or vector depending on the users of the value.
828/// This recipe works in concert with VPBranchOnMaskRecipe.
829class VPPredInstPHIRecipe : public VPRecipeBase {
830private:
831 Instruction *PredInst;
832
833public:
834 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
835 /// nodes after merging back from a Branch-on-Mask.
836 VPPredInstPHIRecipe(Instruction *PredInst)
837 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
838 ~VPPredInstPHIRecipe() override = default;
839
840 /// Method to support type inquiry through isa, cast, and dyn_cast.
841 static inline bool classof(const VPRecipeBase *V) {
842 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
843 }
844
845 /// Generates phi nodes for live-outs as needed to retain SSA form.
846 void execute(VPTransformState &State) override;
847
848 /// Print the recipe.
849 void print(raw_ostream &O, const Twine &Indent) const override;
850};
851
852/// A Recipe for widening load/store operations.
853/// TODO: We currently execute only per-part unless a specific instance is
854/// provided.
855class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
856private:
857 Instruction &Instr;
858 std::unique_ptr<VPUser> User;
859
860public:
861 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
862 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
863 if (Mask) // Create a VPInstruction to register as a user of the mask.
864 User.reset(new VPUser({Mask}));
865 }
866
867 /// Method to support type inquiry through isa, cast, and dyn_cast.
868 static inline bool classof(const VPRecipeBase *V) {
869 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
870 }
871
872 /// Generate the wide load/store.
873 void execute(VPTransformState &State) override;
874
875 /// Print the recipe.
876 void print(raw_ostream &O, const Twine &Indent) const override;
877};
878
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000879/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
880/// holds a sequence of zero or more VPRecipe's each representing a sequence of
881/// output IR instructions.
882class VPBasicBlock : public VPBlockBase {
883public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000884 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000885
886private:
887 /// The VPRecipes held in the order of output instructions to generate.
888 RecipeListTy Recipes;
889
890public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000891 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
892 : VPBlockBase(VPBasicBlockSC, Name.str()) {
893 if (Recipe)
894 appendRecipe(Recipe);
895 }
896
897 ~VPBasicBlock() override { Recipes.clear(); }
898
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000899 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000900 using iterator = RecipeListTy::iterator;
901 using const_iterator = RecipeListTy::const_iterator;
902 using reverse_iterator = RecipeListTy::reverse_iterator;
903 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000904
905 //===--------------------------------------------------------------------===//
906 /// Recipe iterator methods
907 ///
908 inline iterator begin() { return Recipes.begin(); }
909 inline const_iterator begin() const { return Recipes.begin(); }
910 inline iterator end() { return Recipes.end(); }
911 inline const_iterator end() const { return Recipes.end(); }
912
913 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
914 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
915 inline reverse_iterator rend() { return Recipes.rend(); }
916 inline const_reverse_iterator rend() const { return Recipes.rend(); }
917
918 inline size_t size() const { return Recipes.size(); }
919 inline bool empty() const { return Recipes.empty(); }
920 inline const VPRecipeBase &front() const { return Recipes.front(); }
921 inline VPRecipeBase &front() { return Recipes.front(); }
922 inline const VPRecipeBase &back() const { return Recipes.back(); }
923 inline VPRecipeBase &back() { return Recipes.back(); }
924
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000925 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000926 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
927 return &VPBasicBlock::Recipes;
928 }
929
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000930 /// Method to support type inquiry through isa, cast, and dyn_cast.
931 static inline bool classof(const VPBlockBase *V) {
932 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
933 }
934
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000935 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000936 assert(Recipe && "No recipe to append.");
937 assert(!Recipe->Parent && "Recipe already in VPlan");
938 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000939 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000940 }
941
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000942 /// Augment the existing recipes of a VPBasicBlock with an additional
943 /// \p Recipe as the last recipe.
944 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
945
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000946 /// The method which generates the output IR instructions that correspond to
947 /// this VPBasicBlock, thereby "executing" the VPlan.
948 void execute(struct VPTransformState *State) override;
949
950private:
951 /// Create an IR BasicBlock to hold the output instructions generated by this
952 /// VPBasicBlock, and return it. Update the CFGState accordingly.
953 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
954};
955
956/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
957/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
958/// A VPRegionBlock may indicate that its contents are to be replicated several
959/// times. This is designed to support predicated scalarization, in which a
960/// scalar if-then code structure needs to be generated VF * UF times. Having
961/// this replication indicator helps to keep a single model for multiple
962/// candidate VF's. The actual replication takes place only once the desired VF
963/// and UF have been determined.
964class VPRegionBlock : public VPBlockBase {
965private:
966 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
967 VPBlockBase *Entry;
968
969 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
970 VPBlockBase *Exit;
971
972 /// An indicator whether this region is to generate multiple replicated
973 /// instances of output IR corresponding to its VPBlockBases.
974 bool IsReplicator;
975
976public:
977 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
978 const std::string &Name = "", bool IsReplicator = false)
979 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
980 IsReplicator(IsReplicator) {
981 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
982 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
983 Entry->setParent(this);
984 Exit->setParent(this);
985 }
Diego Caballero168d04d2018-05-21 18:14:23 +0000986 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
987 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
988 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000989
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000990 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000991 if (Entry)
992 deleteCFG(Entry);
993 }
994
995 /// Method to support type inquiry through isa, cast, and dyn_cast.
996 static inline bool classof(const VPBlockBase *V) {
997 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
998 }
999
1000 const VPBlockBase *getEntry() const { return Entry; }
1001 VPBlockBase *getEntry() { return Entry; }
1002
Diego Caballero168d04d2018-05-21 18:14:23 +00001003 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1004 /// EntryBlock must have no predecessors.
1005 void setEntry(VPBlockBase *EntryBlock) {
1006 assert(EntryBlock->getPredecessors().empty() &&
1007 "Entry block cannot have predecessors.");
1008 Entry = EntryBlock;
1009 EntryBlock->setParent(this);
1010 }
1011
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001012 const VPBlockBase *getExit() const { return Exit; }
1013 VPBlockBase *getExit() { return Exit; }
1014
Diego Caballero168d04d2018-05-21 18:14:23 +00001015 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1016 /// ExitBlock must have no successors.
1017 void setExit(VPBlockBase *ExitBlock) {
1018 assert(ExitBlock->getSuccessors().empty() &&
1019 "Exit block cannot have successors.");
1020 Exit = ExitBlock;
1021 ExitBlock->setParent(this);
1022 }
1023
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001024 /// An indicator whether this region is to generate multiple replicated
1025 /// instances of output IR corresponding to its VPBlockBases.
1026 bool isReplicator() const { return IsReplicator; }
1027
1028 /// The method which generates the output IR instructions that correspond to
1029 /// this VPRegionBlock, thereby "executing" the VPlan.
1030 void execute(struct VPTransformState *State) override;
1031};
1032
1033/// VPlan models a candidate for vectorization, encoding various decisions take
1034/// to produce efficient output IR, including which branches, basic-blocks and
1035/// output IR instructions to generate, and their cost. VPlan holds a
1036/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1037/// VPBlock.
1038class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001039 friend class VPlanPrinter;
1040
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001041private:
1042 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1043 VPBlockBase *Entry;
1044
1045 /// Holds the VFs applicable to this VPlan.
1046 SmallSet<unsigned, 2> VFs;
1047
1048 /// Holds the name of the VPlan, for printing.
1049 std::string Name;
1050
Diego Caballero168d04d2018-05-21 18:14:23 +00001051 /// Holds all the external definitions created for this VPlan.
1052 // TODO: Introduce a specific representation for external definitions in
1053 // VPlan. External definitions must be immutable and hold a pointer to its
1054 // underlying IR that will be used to implement its structural comparison
1055 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001056 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001057
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001058 /// Holds a mapping between Values and their corresponding VPValue inside
1059 /// VPlan.
1060 Value2VPValueTy Value2VPValue;
1061
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001062public:
1063 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1064
1065 ~VPlan() {
1066 if (Entry)
1067 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001068 for (auto &MapEntry : Value2VPValue)
1069 delete MapEntry.second;
Diego Caballero168d04d2018-05-21 18:14:23 +00001070 for (VPValue *Def : VPExternalDefs)
1071 delete Def;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001072 }
1073
1074 /// Generate the IR code for this VPlan.
1075 void execute(struct VPTransformState *State);
1076
1077 VPBlockBase *getEntry() { return Entry; }
1078 const VPBlockBase *getEntry() const { return Entry; }
1079
1080 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1081
1082 void addVF(unsigned VF) { VFs.insert(VF); }
1083
1084 bool hasVF(unsigned VF) { return VFs.count(VF); }
1085
1086 const std::string &getName() const { return Name; }
1087
1088 void setName(const Twine &newName) { Name = newName.str(); }
1089
Diego Caballero168d04d2018-05-21 18:14:23 +00001090 /// Add \p VPVal to the pool of external definitions if it's not already
1091 /// in the pool.
1092 void addExternalDef(VPValue *VPVal) {
1093 VPExternalDefs.insert(VPVal);
1094 }
1095
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001096 void addVPValue(Value *V) {
1097 assert(V && "Trying to add a null Value to VPlan");
1098 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1099 Value2VPValue[V] = new VPValue();
1100 }
1101
1102 VPValue *getVPValue(Value *V) {
1103 assert(V && "Trying to get the VPValue of a null Value");
1104 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1105 return Value2VPValue[V];
1106 }
1107
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001108private:
1109 /// Add to the given dominator tree the header block and every new basic block
1110 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001111 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001112 BasicBlock *LoopPreHeaderBB,
1113 BasicBlock *LoopLatchBB);
1114};
1115
1116/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1117/// indented and follows the dot format.
1118class VPlanPrinter {
1119 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1120 friend inline raw_ostream &operator<<(raw_ostream &OS,
1121 const struct VPlanIngredient &I);
1122
1123private:
1124 raw_ostream &OS;
1125 VPlan &Plan;
1126 unsigned Depth;
1127 unsigned TabWidth = 2;
1128 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001129 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001130 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1131
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001132 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1133
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001134 /// Handle indentation.
1135 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1136
1137 /// Print a given \p Block of the Plan.
1138 void dumpBlock(const VPBlockBase *Block);
1139
1140 /// Print the information related to the CFG edges going out of a given
1141 /// \p Block, followed by printing the successor blocks themselves.
1142 void dumpEdges(const VPBlockBase *Block);
1143
1144 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1145 /// its successor blocks.
1146 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1147
1148 /// Print a given \p Region of the Plan.
1149 void dumpRegion(const VPRegionBlock *Region);
1150
1151 unsigned getOrCreateBID(const VPBlockBase *Block) {
1152 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1153 }
1154
1155 const Twine getOrCreateName(const VPBlockBase *Block);
1156
1157 const Twine getUID(const VPBlockBase *Block);
1158
1159 /// Print the information related to a CFG edge between two VPBlockBases.
1160 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1161 const Twine &Label);
1162
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001163 void dump();
1164
1165 static void printAsIngredient(raw_ostream &O, Value *V);
1166};
1167
1168struct VPlanIngredient {
1169 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001170
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001171 VPlanIngredient(Value *V) : V(V) {}
1172};
1173
1174inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1175 VPlanPrinter::printAsIngredient(OS, I.V);
1176 return OS;
1177}
1178
1179inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1180 VPlanPrinter Printer(OS, Plan);
1181 Printer.dump();
1182 return OS;
1183}
1184
1185//===--------------------------------------------------------------------===//
1186// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
1187//===--------------------------------------------------------------------===//
1188
1189// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1190// graph of VPBlockBase nodes...
1191
1192template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001193 using NodeRef = VPBlockBase *;
1194 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001195
1196 static NodeRef getEntryNode(NodeRef N) { return N; }
1197
1198 static inline ChildIteratorType child_begin(NodeRef N) {
1199 return N->getSuccessors().begin();
1200 }
1201
1202 static inline ChildIteratorType child_end(NodeRef N) {
1203 return N->getSuccessors().end();
1204 }
1205};
1206
1207template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001208 using NodeRef = const VPBlockBase *;
1209 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001210
1211 static NodeRef getEntryNode(NodeRef N) { return N; }
1212
1213 static inline ChildIteratorType child_begin(NodeRef N) {
1214 return N->getSuccessors().begin();
1215 }
1216
1217 static inline ChildIteratorType child_end(NodeRef N) {
1218 return N->getSuccessors().end();
1219 }
1220};
1221
1222// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1223// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1224// for a VPBlockBase is considered to be when traversing the predecessors of a
1225// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001226template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001227 using NodeRef = VPBlockBase *;
1228 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001229
1230 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1231 return B;
1232 }
1233
1234 static inline ChildIteratorType child_begin(NodeRef N) {
1235 return N->getPredecessors().begin();
1236 }
1237
1238 static inline ChildIteratorType child_end(NodeRef N) {
1239 return N->getPredecessors().end();
1240 }
1241};
1242
Diego Caballero168d04d2018-05-21 18:14:23 +00001243//===----------------------------------------------------------------------===//
1244// VPlan Utilities
1245//===----------------------------------------------------------------------===//
1246
1247/// Class that provides utilities for VPBlockBases in VPlan.
1248class VPBlockUtils {
1249public:
1250 VPBlockUtils() = delete;
1251
1252 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
1253 /// NewBlock as successor of \p BlockPtr and \p Block as predecessor of \p
1254 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p NewBlock
1255 /// must have neither successors nor predecessors.
1256 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1257 assert(NewBlock->getSuccessors().empty() &&
1258 "Can't insert new block with successors.");
1259 // TODO: move successors from BlockPtr to NewBlock when this functionality
1260 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1261 // already has successors.
1262 BlockPtr->setOneSuccessor(NewBlock);
1263 NewBlock->setPredecessors({BlockPtr});
1264 NewBlock->setParent(BlockPtr->getParent());
1265 }
1266
1267 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1268 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1269 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
1270 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
1271 /// and \p IfTrue and \p IfFalse must have neither successors nor
1272 /// predecessors.
1273 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
1274 VPBlockBase *BlockPtr) {
1275 assert(IfTrue->getSuccessors().empty() &&
1276 "Can't insert IfTrue with successors.");
1277 assert(IfFalse->getSuccessors().empty() &&
1278 "Can't insert IfFalse with successors.");
1279 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
1280 IfTrue->setPredecessors({BlockPtr});
1281 IfFalse->setPredecessors({BlockPtr});
1282 IfTrue->setParent(BlockPtr->getParent());
1283 IfFalse->setParent(BlockPtr->getParent());
1284 }
1285
1286 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1287 /// the successors of \p From and \p From to the predecessors of \p To. Both
1288 /// VPBlockBases must have the same parent, which can be null. Both
1289 /// VPBlockBases can be already connected to other VPBlockBases.
1290 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1291 assert((From->getParent() == To->getParent()) &&
1292 "Can't connect two block with different parents");
1293 assert(From->getNumSuccessors() < 2 &&
1294 "Blocks can't have more than two successors.");
1295 From->appendSuccessor(To);
1296 To->appendPredecessor(From);
1297 }
1298
1299 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1300 /// from the successors of \p From and \p From from the predecessors of \p To.
1301 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1302 assert(To && "Successor to disconnect is null.");
1303 From->removeSuccessor(To);
1304 To->removePredecessor(From);
1305 }
1306};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001307
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001308} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001309
1310#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H