blob: 866951cb79a463e412034068ce874e464b1420b1 [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
Diego Caballerod0953012018-07-09 15:57:09 +0000342 /// Successor selector, null for zero or single successor blocks.
343 VPValue *CondBit = nullptr;
344
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000345 /// Add \p Successor as the last successor to this block.
346 void appendSuccessor(VPBlockBase *Successor) {
347 assert(Successor && "Cannot add nullptr successor!");
348 Successors.push_back(Successor);
349 }
350
351 /// Add \p Predecessor as the last predecessor to this block.
352 void appendPredecessor(VPBlockBase *Predecessor) {
353 assert(Predecessor && "Cannot add nullptr predecessor!");
354 Predecessors.push_back(Predecessor);
355 }
356
357 /// Remove \p Predecessor from the predecessors of this block.
358 void removePredecessor(VPBlockBase *Predecessor) {
359 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
360 assert(Pos && "Predecessor does not exist");
361 Predecessors.erase(Pos);
362 }
363
364 /// Remove \p Successor from the successors of this block.
365 void removeSuccessor(VPBlockBase *Successor) {
366 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
367 assert(Pos && "Successor does not exist");
368 Successors.erase(Pos);
369 }
370
371protected:
372 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000373 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000374
375public:
376 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
377 /// that are actually instantiated. Values of this enumeration are kept in the
378 /// SubclassID field of the VPBlockBase objects. They are used for concrete
379 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000380 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000381
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000382 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000383
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000384 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000385
386 const std::string &getName() const { return Name; }
387
388 void setName(const Twine &newName) { Name = newName.str(); }
389
390 /// \return an ID for the concrete type of this object.
391 /// This is used to implement the classof checks. This should not be used
392 /// for any other purpose, as the values may change as LLVM evolves.
393 unsigned getVPBlockID() const { return SubclassID; }
394
Diego Caballero168d04d2018-05-21 18:14:23 +0000395 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000396 const VPRegionBlock *getParent() const { return Parent; }
397
398 void setParent(VPRegionBlock *P) { Parent = P; }
399
400 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
401 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
402 /// VPBlockBase is a VPBasicBlock, it is returned.
403 const VPBasicBlock *getEntryBasicBlock() const;
404 VPBasicBlock *getEntryBasicBlock();
405
406 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
407 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
408 /// VPBlockBase is a VPBasicBlock, it is returned.
409 const VPBasicBlock *getExitBasicBlock() const;
410 VPBasicBlock *getExitBasicBlock();
411
412 const VPBlocksTy &getSuccessors() const { return Successors; }
413 VPBlocksTy &getSuccessors() { return Successors; }
414
415 const VPBlocksTy &getPredecessors() const { return Predecessors; }
416 VPBlocksTy &getPredecessors() { return Predecessors; }
417
418 /// \return the successor of this VPBlockBase if it has a single successor.
419 /// Otherwise return a null pointer.
420 VPBlockBase *getSingleSuccessor() const {
421 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
422 }
423
424 /// \return the predecessor of this VPBlockBase if it has a single
425 /// predecessor. Otherwise return a null pointer.
426 VPBlockBase *getSinglePredecessor() const {
427 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
428 }
429
Diego Caballero168d04d2018-05-21 18:14:23 +0000430 size_t getNumSuccessors() const { return Successors.size(); }
431 size_t getNumPredecessors() const { return Predecessors.size(); }
432
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000433 /// An Enclosing Block of a block B is any block containing B, including B
434 /// itself. \return the closest enclosing block starting from "this", which
435 /// has successors. \return the root enclosing block if all enclosing blocks
436 /// have no successors.
437 VPBlockBase *getEnclosingBlockWithSuccessors();
438
439 /// \return the closest enclosing block starting from "this", which has
440 /// predecessors. \return the root enclosing block if all enclosing blocks
441 /// have no predecessors.
442 VPBlockBase *getEnclosingBlockWithPredecessors();
443
444 /// \return the successors either attached directly to this VPBlockBase or, if
445 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
446 /// successors of its own, search recursively for the first enclosing
447 /// VPRegionBlock that has successors and return them. If no such
448 /// VPRegionBlock exists, return the (empty) successors of the topmost
449 /// VPBlockBase reached.
450 const VPBlocksTy &getHierarchicalSuccessors() {
451 return getEnclosingBlockWithSuccessors()->getSuccessors();
452 }
453
454 /// \return the hierarchical successor of this VPBlockBase if it has a single
455 /// hierarchical successor. Otherwise return a null pointer.
456 VPBlockBase *getSingleHierarchicalSuccessor() {
457 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
458 }
459
460 /// \return the predecessors either attached directly to this VPBlockBase or,
461 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
462 /// predecessors of its own, search recursively for the first enclosing
463 /// VPRegionBlock that has predecessors and return them. If no such
464 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
465 /// VPBlockBase reached.
466 const VPBlocksTy &getHierarchicalPredecessors() {
467 return getEnclosingBlockWithPredecessors()->getPredecessors();
468 }
469
470 /// \return the hierarchical predecessor of this VPBlockBase if it has a
471 /// single hierarchical predecessor. Otherwise return a null pointer.
472 VPBlockBase *getSingleHierarchicalPredecessor() {
473 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
474 }
475
Diego Caballerod0953012018-07-09 15:57:09 +0000476 /// \return the condition bit selecting the successor.
477 VPValue *getCondBit() { return CondBit; }
478
479 const VPValue *getCondBit() const { return CondBit; }
480
481 void setCondBit(VPValue *CV) { CondBit = CV; }
482
Diego Caballero168d04d2018-05-21 18:14:23 +0000483 /// Set a given VPBlockBase \p Successor as the single successor of this
484 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
485 /// This VPBlockBase must have no successors.
486 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000487 assert(Successors.empty() && "Setting one successor when others exist.");
488 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000489 }
490
Diego Caballero168d04d2018-05-21 18:14:23 +0000491 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
Diego Caballerod0953012018-07-09 15:57:09 +0000492 /// successors of this VPBlockBase. \p Condition is set as the successor
493 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
494 /// IfFalse. This VPBlockBase must have no successors.
495 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
496 VPValue *Condition) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000497 assert(Successors.empty() && "Setting two successors when others exist.");
Diego Caballerod0953012018-07-09 15:57:09 +0000498 assert(Condition && "Setting two successors without condition!");
499 CondBit = Condition;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000500 appendSuccessor(IfTrue);
501 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000502 }
503
Diego Caballero168d04d2018-05-21 18:14:23 +0000504 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
505 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
506 /// as successor of any VPBasicBlock in \p NewPreds.
507 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
508 assert(Predecessors.empty() && "Block predecessors already set.");
509 for (auto *Pred : NewPreds)
510 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000511 }
512
513 /// The method which generates the output IR that correspond to this
514 /// VPBlockBase, thereby "executing" the VPlan.
515 virtual void execute(struct VPTransformState *State) = 0;
516
517 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
518 static void deleteCFG(VPBlockBase *Entry);
519};
520
521/// VPRecipeBase is a base class modeling a sequence of one or more output IR
522/// instructions.
523class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
524 friend VPBasicBlock;
525
526private:
527 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
528
529 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000530 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000531
532public:
533 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
534 /// that is actually instantiated. Values of this enumeration are kept in the
535 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
536 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000537 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000538 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000539 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000540 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000541 VPInterleaveSC,
542 VPPredInstPHISC,
543 VPReplicateSC,
544 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000545 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000546 VPWidenPHISC,
547 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000548 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000549
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000550 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
551 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000552
553 /// \return an ID for the concrete type of this object.
554 /// This is used to implement the classof checks. This should not be used
555 /// for any other purpose, as the values may change as LLVM evolves.
556 unsigned getVPRecipeID() const { return SubclassID; }
557
558 /// \return the VPBasicBlock which this VPRecipe belongs to.
559 VPBasicBlock *getParent() { return Parent; }
560 const VPBasicBlock *getParent() const { return Parent; }
561
562 /// The method which generates the output IR instructions that correspond to
563 /// this VPRecipe, thereby "executing" the VPlan.
564 virtual void execute(struct VPTransformState &State) = 0;
565
566 /// Each recipe prints itself.
567 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
Florian Hahn7591e4e2018-06-18 11:34:17 +0000568
569 /// Insert an unlinked recipe into a basic block immediately before
570 /// the specified recipe.
571 void insertBefore(VPRecipeBase *InsertPos);
Florian Hahn63cbcf92018-06-18 15:18:48 +0000572
573 /// This method unlinks 'this' from the containing basic block and deletes it.
574 ///
575 /// \returns an iterator pointing to the element after the erased one
576 iplist<VPRecipeBase>::iterator eraseFromParent();
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000577};
578
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000579/// This is a concrete Recipe that models a single VPlan-level instruction.
580/// While as any Recipe it may generate a sequence of IR instructions when
581/// executed, these instructions would always form a single-def expression as
582/// the VPInstruction is also a single def-use vertex.
583class VPInstruction : public VPUser, public VPRecipeBase {
Florian Hahn3385caa2018-06-18 18:28:49 +0000584 friend class VPlanHCFGTransforms;
585
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000586public:
587 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
588 enum { Not = Instruction::OtherOpsEnd + 1 };
589
590private:
591 typedef unsigned char OpcodeTy;
592 OpcodeTy Opcode;
593
594 /// Utility method serving execute(): generates a single instance of the
595 /// modeled instruction.
596 void generateInstruction(VPTransformState &State, unsigned Part);
597
598public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000599 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000600 : VPUser(VPValue::VPInstructionSC, Operands),
601 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
602
Diego Caballero168d04d2018-05-21 18:14:23 +0000603 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
604 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
605
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000606 /// Method to support type inquiry through isa, cast, and dyn_cast.
607 static inline bool classof(const VPValue *V) {
608 return V->getVPValueID() == VPValue::VPInstructionSC;
609 }
610
611 /// Method to support type inquiry through isa, cast, and dyn_cast.
612 static inline bool classof(const VPRecipeBase *R) {
613 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
614 }
615
616 unsigned getOpcode() const { return Opcode; }
617
618 /// Generate the instruction.
619 /// TODO: We currently execute only per-part unless a specific instance is
620 /// provided.
621 void execute(VPTransformState &State) override;
622
623 /// Print the Recipe.
624 void print(raw_ostream &O, const Twine &Indent) const override;
625
626 /// Print the VPInstruction.
627 void print(raw_ostream &O) const;
628};
629
Hal Finkel7333aa92017-12-16 01:12:50 +0000630/// VPWidenRecipe is a recipe for producing a copy of vector type for each
631/// Instruction in its ingredients independently, in order. This recipe covers
632/// most of the traditional vectorization cases where each ingredient transforms
633/// into a vectorized version of itself.
634class VPWidenRecipe : public VPRecipeBase {
635private:
636 /// Hold the ingredients by pointing to their original BasicBlock location.
637 BasicBlock::iterator Begin;
638 BasicBlock::iterator End;
639
640public:
641 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
642 End = I->getIterator();
643 Begin = End++;
644 }
645
646 ~VPWidenRecipe() override = default;
647
648 /// Method to support type inquiry through isa, cast, and dyn_cast.
649 static inline bool classof(const VPRecipeBase *V) {
650 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
651 }
652
653 /// Produce widened copies of all Ingredients.
654 void execute(VPTransformState &State) override;
655
656 /// Augment the recipe to include Instr, if it lies at its End.
657 bool appendInstruction(Instruction *Instr) {
658 if (End != Instr->getIterator())
659 return false;
660 End++;
661 return true;
662 }
663
664 /// Print the recipe.
665 void print(raw_ostream &O, const Twine &Indent) const override;
666};
667
668/// A recipe for handling phi nodes of integer and floating-point inductions,
669/// producing their vector and scalar values.
670class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
671private:
672 PHINode *IV;
673 TruncInst *Trunc;
674
675public:
676 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
677 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
678 ~VPWidenIntOrFpInductionRecipe() override = default;
679
680 /// Method to support type inquiry through isa, cast, and dyn_cast.
681 static inline bool classof(const VPRecipeBase *V) {
682 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
683 }
684
685 /// Generate the vectorized and scalarized versions of the phi node as
686 /// needed by their users.
687 void execute(VPTransformState &State) override;
688
689 /// Print the recipe.
690 void print(raw_ostream &O, const Twine &Indent) const override;
691};
692
693/// A recipe for handling all phi nodes except for integer and FP inductions.
694class VPWidenPHIRecipe : public VPRecipeBase {
695private:
696 PHINode *Phi;
697
698public:
699 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
700 ~VPWidenPHIRecipe() override = default;
701
702 /// Method to support type inquiry through isa, cast, and dyn_cast.
703 static inline bool classof(const VPRecipeBase *V) {
704 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
705 }
706
707 /// Generate the phi/select nodes.
708 void execute(VPTransformState &State) override;
709
710 /// Print the recipe.
711 void print(raw_ostream &O, const Twine &Indent) const override;
712};
713
714/// A recipe for vectorizing a phi-node as a sequence of mask-based select
715/// instructions.
716class VPBlendRecipe : public VPRecipeBase {
717private:
718 PHINode *Phi;
719
720 /// The blend operation is a User of a mask, if not null.
721 std::unique_ptr<VPUser> User;
722
723public:
724 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
725 : VPRecipeBase(VPBlendSC), Phi(Phi) {
726 assert((Phi->getNumIncomingValues() == 1 ||
727 Phi->getNumIncomingValues() == Masks.size()) &&
728 "Expected the same number of incoming values and masks");
729 if (!Masks.empty())
730 User.reset(new VPUser(Masks));
731 }
732
733 /// Method to support type inquiry through isa, cast, and dyn_cast.
734 static inline bool classof(const VPRecipeBase *V) {
735 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
736 }
737
738 /// Generate the phi/select nodes.
739 void execute(VPTransformState &State) override;
740
741 /// Print the recipe.
742 void print(raw_ostream &O, const Twine &Indent) const override;
743};
744
745/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
746/// or stores into one wide load/store and shuffles.
747class VPInterleaveRecipe : public VPRecipeBase {
748private:
749 const InterleaveGroup *IG;
750
751public:
752 VPInterleaveRecipe(const InterleaveGroup *IG)
753 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
754 ~VPInterleaveRecipe() override = default;
755
756 /// Method to support type inquiry through isa, cast, and dyn_cast.
757 static inline bool classof(const VPRecipeBase *V) {
758 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
759 }
760
761 /// Generate the wide load or store, and shuffles.
762 void execute(VPTransformState &State) override;
763
764 /// Print the recipe.
765 void print(raw_ostream &O, const Twine &Indent) const override;
766
767 const InterleaveGroup *getInterleaveGroup() { return IG; }
768};
769
770/// VPReplicateRecipe replicates a given instruction producing multiple scalar
771/// copies of the original scalar type, one per lane, instead of producing a
772/// single copy of widened type for all lanes. If the instruction is known to be
773/// uniform only one copy, per lane zero, will be generated.
774class VPReplicateRecipe : public VPRecipeBase {
775private:
776 /// The instruction being replicated.
777 Instruction *Ingredient;
778
779 /// Indicator if only a single replica per lane is needed.
780 bool IsUniform;
781
782 /// Indicator if the replicas are also predicated.
783 bool IsPredicated;
784
785 /// Indicator if the scalar values should also be packed into a vector.
786 bool AlsoPack;
787
788public:
789 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
790 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
791 IsPredicated(IsPredicated) {
792 // Retain the previous behavior of predicateInstructions(), where an
793 // insert-element of a predicated instruction got hoisted into the
794 // predicated basic block iff it was its only user. This is achieved by
795 // having predicated instructions also pack their values into a vector by
796 // default unless they have a replicated user which uses their scalar value.
797 AlsoPack = IsPredicated && !I->use_empty();
798 }
799
800 ~VPReplicateRecipe() override = default;
801
802 /// Method to support type inquiry through isa, cast, and dyn_cast.
803 static inline bool classof(const VPRecipeBase *V) {
804 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
805 }
806
807 /// Generate replicas of the desired Ingredient. Replicas will be generated
808 /// for all parts and lanes unless a specific part and lane are specified in
809 /// the \p State.
810 void execute(VPTransformState &State) override;
811
812 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
813
814 /// Print the recipe.
815 void print(raw_ostream &O, const Twine &Indent) const override;
816};
817
818/// A recipe for generating conditional branches on the bits of a mask.
819class VPBranchOnMaskRecipe : public VPRecipeBase {
820private:
821 std::unique_ptr<VPUser> User;
822
823public:
824 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
825 if (BlockInMask) // nullptr means all-one mask.
826 User.reset(new VPUser({BlockInMask}));
827 }
828
829 /// Method to support type inquiry through isa, cast, and dyn_cast.
830 static inline bool classof(const VPRecipeBase *V) {
831 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
832 }
833
834 /// Generate the extraction of the appropriate bit from the block mask and the
835 /// conditional branch.
836 void execute(VPTransformState &State) override;
837
838 /// Print the recipe.
839 void print(raw_ostream &O, const Twine &Indent) const override {
840 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
841 if (User)
842 O << *User->getOperand(0);
843 else
844 O << " All-One";
845 O << "\\l\"";
846 }
847};
848
849/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
850/// control converges back from a Branch-on-Mask. The phi nodes are needed in
851/// order to merge values that are set under such a branch and feed their uses.
852/// The phi nodes can be scalar or vector depending on the users of the value.
853/// This recipe works in concert with VPBranchOnMaskRecipe.
854class VPPredInstPHIRecipe : public VPRecipeBase {
855private:
856 Instruction *PredInst;
857
858public:
859 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
860 /// nodes after merging back from a Branch-on-Mask.
861 VPPredInstPHIRecipe(Instruction *PredInst)
862 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
863 ~VPPredInstPHIRecipe() override = default;
864
865 /// Method to support type inquiry through isa, cast, and dyn_cast.
866 static inline bool classof(const VPRecipeBase *V) {
867 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
868 }
869
870 /// Generates phi nodes for live-outs as needed to retain SSA form.
871 void execute(VPTransformState &State) override;
872
873 /// Print the recipe.
874 void print(raw_ostream &O, const Twine &Indent) const override;
875};
876
877/// A Recipe for widening load/store operations.
878/// TODO: We currently execute only per-part unless a specific instance is
879/// provided.
880class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
881private:
882 Instruction &Instr;
883 std::unique_ptr<VPUser> User;
884
885public:
886 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
887 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
888 if (Mask) // Create a VPInstruction to register as a user of the mask.
889 User.reset(new VPUser({Mask}));
890 }
891
892 /// Method to support type inquiry through isa, cast, and dyn_cast.
893 static inline bool classof(const VPRecipeBase *V) {
894 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
895 }
896
897 /// Generate the wide load/store.
898 void execute(VPTransformState &State) override;
899
900 /// Print the recipe.
901 void print(raw_ostream &O, const Twine &Indent) const override;
902};
903
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000904/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
905/// holds a sequence of zero or more VPRecipe's each representing a sequence of
906/// output IR instructions.
907class VPBasicBlock : public VPBlockBase {
908public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000909 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000910
911private:
912 /// The VPRecipes held in the order of output instructions to generate.
913 RecipeListTy Recipes;
914
915public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000916 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
917 : VPBlockBase(VPBasicBlockSC, Name.str()) {
918 if (Recipe)
919 appendRecipe(Recipe);
920 }
921
922 ~VPBasicBlock() override { Recipes.clear(); }
923
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000924 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000925 using iterator = RecipeListTy::iterator;
926 using const_iterator = RecipeListTy::const_iterator;
927 using reverse_iterator = RecipeListTy::reverse_iterator;
928 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000929
930 //===--------------------------------------------------------------------===//
931 /// Recipe iterator methods
932 ///
933 inline iterator begin() { return Recipes.begin(); }
934 inline const_iterator begin() const { return Recipes.begin(); }
935 inline iterator end() { return Recipes.end(); }
936 inline const_iterator end() const { return Recipes.end(); }
937
938 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
939 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
940 inline reverse_iterator rend() { return Recipes.rend(); }
941 inline const_reverse_iterator rend() const { return Recipes.rend(); }
942
943 inline size_t size() const { return Recipes.size(); }
944 inline bool empty() const { return Recipes.empty(); }
945 inline const VPRecipeBase &front() const { return Recipes.front(); }
946 inline VPRecipeBase &front() { return Recipes.front(); }
947 inline const VPRecipeBase &back() const { return Recipes.back(); }
948 inline VPRecipeBase &back() { return Recipes.back(); }
949
Florian Hahn7591e4e2018-06-18 11:34:17 +0000950 /// Returns a reference to the list of recipes.
951 RecipeListTy &getRecipeList() { return Recipes; }
952
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000953 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000954 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
955 return &VPBasicBlock::Recipes;
956 }
957
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000958 /// Method to support type inquiry through isa, cast, and dyn_cast.
959 static inline bool classof(const VPBlockBase *V) {
960 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
961 }
962
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000963 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000964 assert(Recipe && "No recipe to append.");
965 assert(!Recipe->Parent && "Recipe already in VPlan");
966 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000967 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000968 }
969
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000970 /// Augment the existing recipes of a VPBasicBlock with an additional
971 /// \p Recipe as the last recipe.
972 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
973
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000974 /// The method which generates the output IR instructions that correspond to
975 /// this VPBasicBlock, thereby "executing" the VPlan.
976 void execute(struct VPTransformState *State) override;
977
978private:
979 /// Create an IR BasicBlock to hold the output instructions generated by this
980 /// VPBasicBlock, and return it. Update the CFGState accordingly.
981 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
982};
983
984/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
985/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
986/// A VPRegionBlock may indicate that its contents are to be replicated several
987/// times. This is designed to support predicated scalarization, in which a
988/// scalar if-then code structure needs to be generated VF * UF times. Having
989/// this replication indicator helps to keep a single model for multiple
990/// candidate VF's. The actual replication takes place only once the desired VF
991/// and UF have been determined.
992class VPRegionBlock : public VPBlockBase {
993private:
994 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
995 VPBlockBase *Entry;
996
997 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
998 VPBlockBase *Exit;
999
1000 /// An indicator whether this region is to generate multiple replicated
1001 /// instances of output IR corresponding to its VPBlockBases.
1002 bool IsReplicator;
1003
1004public:
1005 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1006 const std::string &Name = "", bool IsReplicator = false)
1007 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1008 IsReplicator(IsReplicator) {
1009 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1010 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1011 Entry->setParent(this);
1012 Exit->setParent(this);
1013 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001014 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1015 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1016 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001017
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001018 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001019 if (Entry)
1020 deleteCFG(Entry);
1021 }
1022
1023 /// Method to support type inquiry through isa, cast, and dyn_cast.
1024 static inline bool classof(const VPBlockBase *V) {
1025 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1026 }
1027
1028 const VPBlockBase *getEntry() const { return Entry; }
1029 VPBlockBase *getEntry() { return Entry; }
1030
Diego Caballero168d04d2018-05-21 18:14:23 +00001031 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1032 /// EntryBlock must have no predecessors.
1033 void setEntry(VPBlockBase *EntryBlock) {
1034 assert(EntryBlock->getPredecessors().empty() &&
1035 "Entry block cannot have predecessors.");
1036 Entry = EntryBlock;
1037 EntryBlock->setParent(this);
1038 }
1039
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001040 const VPBlockBase *getExit() const { return Exit; }
1041 VPBlockBase *getExit() { return Exit; }
1042
Diego Caballero168d04d2018-05-21 18:14:23 +00001043 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1044 /// ExitBlock must have no successors.
1045 void setExit(VPBlockBase *ExitBlock) {
1046 assert(ExitBlock->getSuccessors().empty() &&
1047 "Exit block cannot have successors.");
1048 Exit = ExitBlock;
1049 ExitBlock->setParent(this);
1050 }
1051
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001052 /// An indicator whether this region is to generate multiple replicated
1053 /// instances of output IR corresponding to its VPBlockBases.
1054 bool isReplicator() const { return IsReplicator; }
1055
1056 /// The method which generates the output IR instructions that correspond to
1057 /// this VPRegionBlock, thereby "executing" the VPlan.
1058 void execute(struct VPTransformState *State) override;
1059};
1060
1061/// VPlan models a candidate for vectorization, encoding various decisions take
1062/// to produce efficient output IR, including which branches, basic-blocks and
1063/// output IR instructions to generate, and their cost. VPlan holds a
1064/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1065/// VPBlock.
1066class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001067 friend class VPlanPrinter;
1068
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001069private:
1070 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1071 VPBlockBase *Entry;
1072
1073 /// Holds the VFs applicable to this VPlan.
1074 SmallSet<unsigned, 2> VFs;
1075
1076 /// Holds the name of the VPlan, for printing.
1077 std::string Name;
1078
Diego Caballero168d04d2018-05-21 18:14:23 +00001079 /// Holds all the external definitions created for this VPlan.
1080 // TODO: Introduce a specific representation for external definitions in
1081 // VPlan. External definitions must be immutable and hold a pointer to its
1082 // underlying IR that will be used to implement its structural comparison
1083 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001084 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001085
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001086 /// Holds a mapping between Values and their corresponding VPValue inside
1087 /// VPlan.
1088 Value2VPValueTy Value2VPValue;
1089
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001090public:
1091 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1092
1093 ~VPlan() {
1094 if (Entry)
1095 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001096 for (auto &MapEntry : Value2VPValue)
1097 delete MapEntry.second;
Diego Caballero168d04d2018-05-21 18:14:23 +00001098 for (VPValue *Def : VPExternalDefs)
1099 delete Def;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001100 }
1101
1102 /// Generate the IR code for this VPlan.
1103 void execute(struct VPTransformState *State);
1104
1105 VPBlockBase *getEntry() { return Entry; }
1106 const VPBlockBase *getEntry() const { return Entry; }
1107
1108 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1109
1110 void addVF(unsigned VF) { VFs.insert(VF); }
1111
1112 bool hasVF(unsigned VF) { return VFs.count(VF); }
1113
1114 const std::string &getName() const { return Name; }
1115
1116 void setName(const Twine &newName) { Name = newName.str(); }
1117
Diego Caballero168d04d2018-05-21 18:14:23 +00001118 /// Add \p VPVal to the pool of external definitions if it's not already
1119 /// in the pool.
1120 void addExternalDef(VPValue *VPVal) {
1121 VPExternalDefs.insert(VPVal);
1122 }
1123
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001124 void addVPValue(Value *V) {
1125 assert(V && "Trying to add a null Value to VPlan");
1126 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1127 Value2VPValue[V] = new VPValue();
1128 }
1129
1130 VPValue *getVPValue(Value *V) {
1131 assert(V && "Trying to get the VPValue of a null Value");
1132 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1133 return Value2VPValue[V];
1134 }
1135
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001136private:
1137 /// Add to the given dominator tree the header block and every new basic block
1138 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001139 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001140 BasicBlock *LoopPreHeaderBB,
1141 BasicBlock *LoopLatchBB);
1142};
1143
1144/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1145/// indented and follows the dot format.
1146class VPlanPrinter {
1147 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1148 friend inline raw_ostream &operator<<(raw_ostream &OS,
1149 const struct VPlanIngredient &I);
1150
1151private:
1152 raw_ostream &OS;
1153 VPlan &Plan;
1154 unsigned Depth;
1155 unsigned TabWidth = 2;
1156 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001157 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001158 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1159
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001160 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1161
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001162 /// Handle indentation.
1163 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1164
1165 /// Print a given \p Block of the Plan.
1166 void dumpBlock(const VPBlockBase *Block);
1167
1168 /// Print the information related to the CFG edges going out of a given
1169 /// \p Block, followed by printing the successor blocks themselves.
1170 void dumpEdges(const VPBlockBase *Block);
1171
1172 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1173 /// its successor blocks.
1174 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1175
1176 /// Print a given \p Region of the Plan.
1177 void dumpRegion(const VPRegionBlock *Region);
1178
1179 unsigned getOrCreateBID(const VPBlockBase *Block) {
1180 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1181 }
1182
1183 const Twine getOrCreateName(const VPBlockBase *Block);
1184
1185 const Twine getUID(const VPBlockBase *Block);
1186
1187 /// Print the information related to a CFG edge between two VPBlockBases.
1188 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1189 const Twine &Label);
1190
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001191 void dump();
1192
1193 static void printAsIngredient(raw_ostream &O, Value *V);
1194};
1195
1196struct VPlanIngredient {
1197 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001198
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001199 VPlanIngredient(Value *V) : V(V) {}
1200};
1201
1202inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1203 VPlanPrinter::printAsIngredient(OS, I.V);
1204 return OS;
1205}
1206
1207inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1208 VPlanPrinter Printer(OS, Plan);
1209 Printer.dump();
1210 return OS;
1211}
1212
1213//===--------------------------------------------------------------------===//
1214// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
1215//===--------------------------------------------------------------------===//
1216
1217// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1218// graph of VPBlockBase nodes...
1219
1220template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001221 using NodeRef = VPBlockBase *;
1222 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001223
1224 static NodeRef getEntryNode(NodeRef N) { return N; }
1225
1226 static inline ChildIteratorType child_begin(NodeRef N) {
1227 return N->getSuccessors().begin();
1228 }
1229
1230 static inline ChildIteratorType child_end(NodeRef N) {
1231 return N->getSuccessors().end();
1232 }
1233};
1234
1235template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001236 using NodeRef = const VPBlockBase *;
1237 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001238
1239 static NodeRef getEntryNode(NodeRef N) { return N; }
1240
1241 static inline ChildIteratorType child_begin(NodeRef N) {
1242 return N->getSuccessors().begin();
1243 }
1244
1245 static inline ChildIteratorType child_end(NodeRef N) {
1246 return N->getSuccessors().end();
1247 }
1248};
1249
1250// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1251// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1252// for a VPBlockBase is considered to be when traversing the predecessors of a
1253// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001254template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001255 using NodeRef = VPBlockBase *;
1256 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001257
1258 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1259 return B;
1260 }
1261
1262 static inline ChildIteratorType child_begin(NodeRef N) {
1263 return N->getPredecessors().begin();
1264 }
1265
1266 static inline ChildIteratorType child_end(NodeRef N) {
1267 return N->getPredecessors().end();
1268 }
1269};
1270
Diego Caballero168d04d2018-05-21 18:14:23 +00001271//===----------------------------------------------------------------------===//
1272// VPlan Utilities
1273//===----------------------------------------------------------------------===//
1274
1275/// Class that provides utilities for VPBlockBases in VPlan.
1276class VPBlockUtils {
1277public:
1278 VPBlockUtils() = delete;
1279
1280 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
Diego Caballerod0953012018-07-09 15:57:09 +00001281 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1282 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1283 /// has more than one successor, its conditional bit is propagated to \p
1284 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001285 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1286 assert(NewBlock->getSuccessors().empty() &&
1287 "Can't insert new block with successors.");
1288 // TODO: move successors from BlockPtr to NewBlock when this functionality
1289 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1290 // already has successors.
1291 BlockPtr->setOneSuccessor(NewBlock);
1292 NewBlock->setPredecessors({BlockPtr});
1293 NewBlock->setParent(BlockPtr->getParent());
1294 }
1295
1296 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1297 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1298 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
Diego Caballerod0953012018-07-09 15:57:09 +00001299 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1300 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1301 /// must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001302 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
Diego Caballerod0953012018-07-09 15:57:09 +00001303 VPValue *Condition, VPBlockBase *BlockPtr) {
Diego Caballero168d04d2018-05-21 18:14:23 +00001304 assert(IfTrue->getSuccessors().empty() &&
1305 "Can't insert IfTrue with successors.");
1306 assert(IfFalse->getSuccessors().empty() &&
1307 "Can't insert IfFalse with successors.");
Diego Caballerod0953012018-07-09 15:57:09 +00001308 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
Diego Caballero168d04d2018-05-21 18:14:23 +00001309 IfTrue->setPredecessors({BlockPtr});
1310 IfFalse->setPredecessors({BlockPtr});
1311 IfTrue->setParent(BlockPtr->getParent());
1312 IfFalse->setParent(BlockPtr->getParent());
1313 }
1314
1315 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1316 /// the successors of \p From and \p From to the predecessors of \p To. Both
1317 /// VPBlockBases must have the same parent, which can be null. Both
1318 /// VPBlockBases can be already connected to other VPBlockBases.
1319 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1320 assert((From->getParent() == To->getParent()) &&
1321 "Can't connect two block with different parents");
1322 assert(From->getNumSuccessors() < 2 &&
1323 "Blocks can't have more than two successors.");
1324 From->appendSuccessor(To);
1325 To->appendPredecessor(From);
1326 }
1327
1328 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1329 /// from the successors of \p From and \p From from the predecessors of \p To.
1330 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1331 assert(To && "Successor to disconnect is null.");
1332 From->removeSuccessor(To);
1333 To->removePredecessor(From);
1334 }
1335};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001336
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001337} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001338
1339#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H