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