blob: 555a31fbb8629a86d379b2364d8c53c31a5c8ae8 [file] [log] [blame]
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001//===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko6cadde72017-10-17 21:27:42 +00009//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000010/// \file
11/// This file contains the declarations of the Vectorization Plan base classes:
12/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
13/// VPBlockBase, together implementing a Hierarchical CFG;
14/// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
15/// treated as proper graphs for generic algorithms;
16/// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
17/// within VPBasicBlocks;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000018/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
19/// instruction;
20/// 5. The VPlan class holding a candidate for vectorization;
21/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000022/// These are documented in docs/VectorizationPlan.rst.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000023//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000024//===----------------------------------------------------------------------===//
25
26#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
28
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000029#include "VPlanValue.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000030#include "llvm/ADT/DenseMap.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000031#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000032#include "llvm/ADT/Optional.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000033#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000036#include "llvm/ADT/ilist.h"
37#include "llvm/ADT/ilist_node.h"
38#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000039#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <map>
43#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000044
45namespace llvm {
46
Hal Finkel0f1314c2018-01-07 16:02:58 +000047class LoopVectorizationLegality;
48class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000049class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000050class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000051class InnerLoopVectorizer;
Hal Finkel7333aa92017-12-16 01:12:50 +000052class InterleaveGroup;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000053class LoopInfo;
54class raw_ostream;
55class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000056class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000057class VPRegionBlock;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000058
59/// In what follows, the term "input IR" refers to code that is fed into the
60/// vectorizer whereas the term "output IR" refers to code that is generated by
61/// the vectorizer.
62
63/// VPIteration represents a single point in the iteration space of the output
64/// (vectorized and/or unrolled) IR loop.
65struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000066 /// in [0..UF)
67 unsigned Part;
68
69 /// in [0..VF)
70 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000071};
72
73/// This is a helper struct for maintaining vectorization state. It's used for
74/// mapping values from the original loop to their corresponding values in
75/// the new loop. Two mappings are maintained: one for vectorized values and
76/// one for scalarized values. Vectorized values are represented with UF
77/// vector values in the new loop, and scalarized values are represented with
78/// UF x VF scalar values in the new loop. UF and VF are the unroll and
79/// vectorization factors, respectively.
80///
81/// Entries can be added to either map with setVectorValue and setScalarValue,
82/// which assert that an entry was not already added before. If an entry is to
83/// replace an existing one, call resetVectorValue and resetScalarValue. This is
84/// currently needed to modify the mapped values during "fix-up" operations that
85/// occur once the first phase of widening is complete. These operations include
86/// type truncation and the second phase of recurrence widening.
87///
88/// Entries from either map can be retrieved using the getVectorValue and
89/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +000090struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000091 friend struct VPTransformState;
92
Ayal Zaks1f58dda2017-08-27 12:55:46 +000093private:
94 /// The unroll factor. Each entry in the vector map contains UF vector values.
95 unsigned UF;
96
97 /// The vectorization factor. Each entry in the scalar map contains UF x VF
98 /// scalar values.
99 unsigned VF;
100
101 /// The vector and scalar map storage. We use std::map and not DenseMap
102 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000103 using VectorParts = SmallVector<Value *, 2>;
104 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000105 std::map<Value *, VectorParts> VectorMapStorage;
106 std::map<Value *, ScalarParts> ScalarMapStorage;
107
108public:
109 /// Construct an empty map with the given unroll and vectorization factors.
110 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
111
112 /// \return True if the map has any vector entry for \p Key.
113 bool hasAnyVectorValue(Value *Key) const {
114 return VectorMapStorage.count(Key);
115 }
116
117 /// \return True if the map has a vector entry for \p Key and \p Part.
118 bool hasVectorValue(Value *Key, unsigned Part) const {
119 assert(Part < UF && "Queried Vector Part is too large.");
120 if (!hasAnyVectorValue(Key))
121 return false;
122 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
123 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
124 return Entry[Part] != nullptr;
125 }
126
127 /// \return True if the map has any scalar entry for \p Key.
128 bool hasAnyScalarValue(Value *Key) const {
129 return ScalarMapStorage.count(Key);
130 }
131
132 /// \return True if the map has a scalar entry for \p Key and \p Instance.
133 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
134 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
135 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
136 if (!hasAnyScalarValue(Key))
137 return false;
138 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
139 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
140 assert(Entry[Instance.Part].size() == VF &&
141 "ScalarParts has wrong dimensions.");
142 return Entry[Instance.Part][Instance.Lane] != nullptr;
143 }
144
145 /// Retrieve the existing vector value that corresponds to \p Key and
146 /// \p Part.
147 Value *getVectorValue(Value *Key, unsigned Part) {
148 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
149 return VectorMapStorage[Key][Part];
150 }
151
152 /// Retrieve the existing scalar value that corresponds to \p Key and
153 /// \p Instance.
154 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
155 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
156 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
157 }
158
159 /// Set a vector value associated with \p Key and \p Part. Assumes such a
160 /// value is not already set. If it is, use resetVectorValue() instead.
161 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
162 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
163 if (!VectorMapStorage.count(Key)) {
164 VectorParts Entry(UF);
165 VectorMapStorage[Key] = Entry;
166 }
167 VectorMapStorage[Key][Part] = Vector;
168 }
169
170 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
171 /// value is not already set.
172 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
173 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
174 if (!ScalarMapStorage.count(Key)) {
175 ScalarParts Entry(UF);
176 // TODO: Consider storing uniform values only per-part, as they occupy
177 // lane 0 only, keeping the other VF-1 redundant entries null.
178 for (unsigned Part = 0; Part < UF; ++Part)
179 Entry[Part].resize(VF, nullptr);
180 ScalarMapStorage[Key] = Entry;
181 }
182 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
183 }
184
185 /// Reset the vector value associated with \p Key for the given \p Part.
186 /// This function can be used to update values that have already been
187 /// vectorized. This is the case for "fix-up" operations including type
188 /// truncation and the second phase of recurrence vectorization.
189 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
190 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
191 VectorMapStorage[Key][Part] = Vector;
192 }
193
194 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
195 /// This function can be used to update values that have already been
196 /// scalarized. This is the case for "fix-up" operations including scalar phi
197 /// nodes for scalarized and predicated instructions.
198 void resetScalarValue(Value *Key, const VPIteration &Instance,
199 Value *Scalar) {
200 assert(hasScalarValue(Key, Instance) &&
201 "Scalar value not set for part and lane");
202 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
203 }
204};
205
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000206/// This class is used to enable the VPlan to invoke a method of ILV. This is
207/// needed until the method is refactored out of ILV and becomes reusable.
208struct VPCallback {
209 virtual ~VPCallback() {}
210 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
211};
212
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000213/// VPTransformState holds information passed down when "executing" a VPlan,
214/// needed for generating the output IR.
215struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000216 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
217 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000218 InnerLoopVectorizer *ILV, VPCallback &Callback)
219 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
220 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000221
222 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
223 unsigned VF;
224 unsigned UF;
225
226 /// Hold the indices to generate specific scalar instructions. Null indicates
227 /// that all instances are to be generated, using either scalar or vector
228 /// instructions.
229 Optional<VPIteration> Instance;
230
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000231 struct DataState {
232 /// A type for vectorized values in the new loop. Each value from the
233 /// original loop, when vectorized, is represented by UF vector values in
234 /// the new unrolled loop, where UF is the unroll factor.
235 typedef SmallVector<Value *, 2> PerPartValuesTy;
236
237 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
238 } Data;
239
240 /// Get the generated Value for a given VPValue and a given Part. Note that
241 /// as some Defs are still created by ILV and managed in its ValueMap, this
242 /// method will delegate the call to ILV in such cases in order to provide
243 /// callers a consistent API.
244 /// \see set.
245 Value *get(VPValue *Def, unsigned Part) {
246 // If Values have been set for this Def return the one relevant for \p Part.
247 if (Data.PerPartOutput.count(Def))
248 return Data.PerPartOutput[Def][Part];
249 // Def is managed by ILV: bring the Values from ValueMap.
250 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
251 }
252
253 /// Set the generated Value for a given VPValue and a given Part.
254 void set(VPValue *Def, Value *V, unsigned Part) {
255 if (!Data.PerPartOutput.count(Def)) {
256 DataState::PerPartValuesTy Entry(UF);
257 Data.PerPartOutput[Def] = Entry;
258 }
259 Data.PerPartOutput[Def][Part] = V;
260 }
261
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000262 /// Hold state information used when constructing the CFG of the output IR,
263 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
264 struct CFGState {
265 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000266 VPBasicBlock *PrevVPBB = nullptr;
267
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000268 /// The previous IR BasicBlock created or used. Initially set to the new
269 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000270 BasicBlock *PrevBB = nullptr;
271
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000272 /// The last IR BasicBlock in the output IR. Set to the new latch
273 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000274 BasicBlock *LastBB = nullptr;
275
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000276 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
277 /// of replication, maps the BasicBlock of the last replica created.
278 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
279
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000280 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000281 } CFG;
282
283 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000284 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000285
286 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000287 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000288
289 /// Hold a reference to the IRBuilder used to generate output IR code.
290 IRBuilder<> &Builder;
291
292 /// Hold a reference to the Value state information used when generating the
293 /// Values of the output IR.
294 VectorizerValueMap &ValueMap;
295
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000296 /// Hold a reference to a mapping between VPValues in VPlan and original
297 /// Values they correspond to.
298 VPValue2ValueTy VPValue2Value;
299
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000300 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000301 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000302
303 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000304};
305
306/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
307/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
308class VPBlockBase {
309private:
310 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
311
312 /// An optional name for the block.
313 std::string Name;
314
315 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
316 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000317 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000318
319 /// List of predecessor blocks.
320 SmallVector<VPBlockBase *, 1> Predecessors;
321
322 /// List of successor blocks.
323 SmallVector<VPBlockBase *, 1> Successors;
324
325 /// Add \p Successor as the last successor to this block.
326 void appendSuccessor(VPBlockBase *Successor) {
327 assert(Successor && "Cannot add nullptr successor!");
328 Successors.push_back(Successor);
329 }
330
331 /// Add \p Predecessor as the last predecessor to this block.
332 void appendPredecessor(VPBlockBase *Predecessor) {
333 assert(Predecessor && "Cannot add nullptr predecessor!");
334 Predecessors.push_back(Predecessor);
335 }
336
337 /// Remove \p Predecessor from the predecessors of this block.
338 void removePredecessor(VPBlockBase *Predecessor) {
339 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
340 assert(Pos && "Predecessor does not exist");
341 Predecessors.erase(Pos);
342 }
343
344 /// Remove \p Successor from the successors of this block.
345 void removeSuccessor(VPBlockBase *Successor) {
346 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
347 assert(Pos && "Successor does not exist");
348 Successors.erase(Pos);
349 }
350
351protected:
352 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000353 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000354
355public:
356 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
357 /// that are actually instantiated. Values of this enumeration are kept in the
358 /// SubclassID field of the VPBlockBase objects. They are used for concrete
359 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000360 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000361
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000362 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000363
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000364 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000365
366 const std::string &getName() const { return Name; }
367
368 void setName(const Twine &newName) { Name = newName.str(); }
369
370 /// \return an ID for the concrete type of this object.
371 /// This is used to implement the classof checks. This should not be used
372 /// for any other purpose, as the values may change as LLVM evolves.
373 unsigned getVPBlockID() const { return SubclassID; }
374
375 const VPRegionBlock *getParent() const { return Parent; }
376
377 void setParent(VPRegionBlock *P) { Parent = P; }
378
379 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
380 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
381 /// VPBlockBase is a VPBasicBlock, it is returned.
382 const VPBasicBlock *getEntryBasicBlock() const;
383 VPBasicBlock *getEntryBasicBlock();
384
385 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
386 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
387 /// VPBlockBase is a VPBasicBlock, it is returned.
388 const VPBasicBlock *getExitBasicBlock() const;
389 VPBasicBlock *getExitBasicBlock();
390
391 const VPBlocksTy &getSuccessors() const { return Successors; }
392 VPBlocksTy &getSuccessors() { return Successors; }
393
394 const VPBlocksTy &getPredecessors() const { return Predecessors; }
395 VPBlocksTy &getPredecessors() { return Predecessors; }
396
397 /// \return the successor of this VPBlockBase if it has a single successor.
398 /// Otherwise return a null pointer.
399 VPBlockBase *getSingleSuccessor() const {
400 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
401 }
402
403 /// \return the predecessor of this VPBlockBase if it has a single
404 /// predecessor. Otherwise return a null pointer.
405 VPBlockBase *getSinglePredecessor() const {
406 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
407 }
408
409 /// An Enclosing Block of a block B is any block containing B, including B
410 /// itself. \return the closest enclosing block starting from "this", which
411 /// has successors. \return the root enclosing block if all enclosing blocks
412 /// have no successors.
413 VPBlockBase *getEnclosingBlockWithSuccessors();
414
415 /// \return the closest enclosing block starting from "this", which has
416 /// predecessors. \return the root enclosing block if all enclosing blocks
417 /// have no predecessors.
418 VPBlockBase *getEnclosingBlockWithPredecessors();
419
420 /// \return the successors either attached directly to this VPBlockBase or, if
421 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
422 /// successors of its own, search recursively for the first enclosing
423 /// VPRegionBlock that has successors and return them. If no such
424 /// VPRegionBlock exists, return the (empty) successors of the topmost
425 /// VPBlockBase reached.
426 const VPBlocksTy &getHierarchicalSuccessors() {
427 return getEnclosingBlockWithSuccessors()->getSuccessors();
428 }
429
430 /// \return the hierarchical successor of this VPBlockBase if it has a single
431 /// hierarchical successor. Otherwise return a null pointer.
432 VPBlockBase *getSingleHierarchicalSuccessor() {
433 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
434 }
435
436 /// \return the predecessors either attached directly to this VPBlockBase or,
437 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
438 /// predecessors of its own, search recursively for the first enclosing
439 /// VPRegionBlock that has predecessors and return them. If no such
440 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
441 /// VPBlockBase reached.
442 const VPBlocksTy &getHierarchicalPredecessors() {
443 return getEnclosingBlockWithPredecessors()->getPredecessors();
444 }
445
446 /// \return the hierarchical predecessor of this VPBlockBase if it has a
447 /// single hierarchical predecessor. Otherwise return a null pointer.
448 VPBlockBase *getSingleHierarchicalPredecessor() {
449 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
450 }
451
452 /// Sets a given VPBlockBase \p Successor as the single successor and \return
453 /// \p Successor. The parent of this Block is copied to be the parent of
454 /// \p Successor.
455 VPBlockBase *setOneSuccessor(VPBlockBase *Successor) {
456 assert(Successors.empty() && "Setting one successor when others exist.");
457 appendSuccessor(Successor);
458 Successor->appendPredecessor(this);
459 Successor->Parent = Parent;
460 return Successor;
461 }
462
463 /// Sets two given VPBlockBases \p IfTrue and \p IfFalse to be the two
464 /// successors. The parent of this Block is copied to be the parent of both
465 /// \p IfTrue and \p IfFalse.
466 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
467 assert(Successors.empty() && "Setting two successors when others exist.");
468 appendSuccessor(IfTrue);
469 appendSuccessor(IfFalse);
470 IfTrue->appendPredecessor(this);
471 IfFalse->appendPredecessor(this);
472 IfTrue->Parent = Parent;
473 IfFalse->Parent = Parent;
474 }
475
476 void disconnectSuccessor(VPBlockBase *Successor) {
477 assert(Successor && "Successor to disconnect is null.");
478 removeSuccessor(Successor);
479 Successor->removePredecessor(this);
480 }
481
482 /// The method which generates the output IR that correspond to this
483 /// VPBlockBase, thereby "executing" the VPlan.
484 virtual void execute(struct VPTransformState *State) = 0;
485
486 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
487 static void deleteCFG(VPBlockBase *Entry);
488};
489
490/// VPRecipeBase is a base class modeling a sequence of one or more output IR
491/// instructions.
492class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
493 friend VPBasicBlock;
494
495private:
496 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
497
498 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000499 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000500
501public:
502 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
503 /// that is actually instantiated. Values of this enumeration are kept in the
504 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
505 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000506 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000507 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000508 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000509 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000510 VPInterleaveSC,
511 VPPredInstPHISC,
512 VPReplicateSC,
513 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000514 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000515 VPWidenPHISC,
516 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000517 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000518
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000519 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
520 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000521
522 /// \return an ID for the concrete type of this object.
523 /// This is used to implement the classof checks. This should not be used
524 /// for any other purpose, as the values may change as LLVM evolves.
525 unsigned getVPRecipeID() const { return SubclassID; }
526
527 /// \return the VPBasicBlock which this VPRecipe belongs to.
528 VPBasicBlock *getParent() { return Parent; }
529 const VPBasicBlock *getParent() const { return Parent; }
530
531 /// The method which generates the output IR instructions that correspond to
532 /// this VPRecipe, thereby "executing" the VPlan.
533 virtual void execute(struct VPTransformState &State) = 0;
534
535 /// Each recipe prints itself.
536 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
537};
538
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000539/// This is a concrete Recipe that models a single VPlan-level instruction.
540/// While as any Recipe it may generate a sequence of IR instructions when
541/// executed, these instructions would always form a single-def expression as
542/// the VPInstruction is also a single def-use vertex.
543class VPInstruction : public VPUser, public VPRecipeBase {
544public:
545 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
546 enum { Not = Instruction::OtherOpsEnd + 1 };
547
548private:
549 typedef unsigned char OpcodeTy;
550 OpcodeTy Opcode;
551
552 /// Utility method serving execute(): generates a single instance of the
553 /// modeled instruction.
554 void generateInstruction(VPTransformState &State, unsigned Part);
555
556public:
557 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
558 : VPUser(VPValue::VPInstructionSC, Operands),
559 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
560
561 /// Method to support type inquiry through isa, cast, and dyn_cast.
562 static inline bool classof(const VPValue *V) {
563 return V->getVPValueID() == VPValue::VPInstructionSC;
564 }
565
566 /// Method to support type inquiry through isa, cast, and dyn_cast.
567 static inline bool classof(const VPRecipeBase *R) {
568 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
569 }
570
571 unsigned getOpcode() const { return Opcode; }
572
573 /// Generate the instruction.
574 /// TODO: We currently execute only per-part unless a specific instance is
575 /// provided.
576 void execute(VPTransformState &State) override;
577
578 /// Print the Recipe.
579 void print(raw_ostream &O, const Twine &Indent) const override;
580
581 /// Print the VPInstruction.
582 void print(raw_ostream &O) const;
583};
584
Hal Finkel7333aa92017-12-16 01:12:50 +0000585/// VPWidenRecipe is a recipe for producing a copy of vector type for each
586/// Instruction in its ingredients independently, in order. This recipe covers
587/// most of the traditional vectorization cases where each ingredient transforms
588/// into a vectorized version of itself.
589class VPWidenRecipe : public VPRecipeBase {
590private:
591 /// Hold the ingredients by pointing to their original BasicBlock location.
592 BasicBlock::iterator Begin;
593 BasicBlock::iterator End;
594
595public:
596 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
597 End = I->getIterator();
598 Begin = End++;
599 }
600
601 ~VPWidenRecipe() override = default;
602
603 /// Method to support type inquiry through isa, cast, and dyn_cast.
604 static inline bool classof(const VPRecipeBase *V) {
605 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
606 }
607
608 /// Produce widened copies of all Ingredients.
609 void execute(VPTransformState &State) override;
610
611 /// Augment the recipe to include Instr, if it lies at its End.
612 bool appendInstruction(Instruction *Instr) {
613 if (End != Instr->getIterator())
614 return false;
615 End++;
616 return true;
617 }
618
619 /// Print the recipe.
620 void print(raw_ostream &O, const Twine &Indent) const override;
621};
622
623/// A recipe for handling phi nodes of integer and floating-point inductions,
624/// producing their vector and scalar values.
625class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
626private:
627 PHINode *IV;
628 TruncInst *Trunc;
629
630public:
631 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
632 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
633 ~VPWidenIntOrFpInductionRecipe() 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::VPWidenIntOrFpInductionSC;
638 }
639
640 /// Generate the vectorized and scalarized versions of the phi node as
641 /// needed by their users.
642 void execute(VPTransformState &State) override;
643
644 /// Print the recipe.
645 void print(raw_ostream &O, const Twine &Indent) const override;
646};
647
648/// A recipe for handling all phi nodes except for integer and FP inductions.
649class VPWidenPHIRecipe : public VPRecipeBase {
650private:
651 PHINode *Phi;
652
653public:
654 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
655 ~VPWidenPHIRecipe() override = default;
656
657 /// Method to support type inquiry through isa, cast, and dyn_cast.
658 static inline bool classof(const VPRecipeBase *V) {
659 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
660 }
661
662 /// Generate the phi/select nodes.
663 void execute(VPTransformState &State) override;
664
665 /// Print the recipe.
666 void print(raw_ostream &O, const Twine &Indent) const override;
667};
668
669/// A recipe for vectorizing a phi-node as a sequence of mask-based select
670/// instructions.
671class VPBlendRecipe : public VPRecipeBase {
672private:
673 PHINode *Phi;
674
675 /// The blend operation is a User of a mask, if not null.
676 std::unique_ptr<VPUser> User;
677
678public:
679 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
680 : VPRecipeBase(VPBlendSC), Phi(Phi) {
681 assert((Phi->getNumIncomingValues() == 1 ||
682 Phi->getNumIncomingValues() == Masks.size()) &&
683 "Expected the same number of incoming values and masks");
684 if (!Masks.empty())
685 User.reset(new VPUser(Masks));
686 }
687
688 /// Method to support type inquiry through isa, cast, and dyn_cast.
689 static inline bool classof(const VPRecipeBase *V) {
690 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
691 }
692
693 /// Generate the phi/select nodes.
694 void execute(VPTransformState &State) override;
695
696 /// Print the recipe.
697 void print(raw_ostream &O, const Twine &Indent) const override;
698};
699
700/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
701/// or stores into one wide load/store and shuffles.
702class VPInterleaveRecipe : public VPRecipeBase {
703private:
704 const InterleaveGroup *IG;
705
706public:
707 VPInterleaveRecipe(const InterleaveGroup *IG)
708 : VPRecipeBase(VPInterleaveSC), IG(IG) {}
709 ~VPInterleaveRecipe() override = default;
710
711 /// Method to support type inquiry through isa, cast, and dyn_cast.
712 static inline bool classof(const VPRecipeBase *V) {
713 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
714 }
715
716 /// Generate the wide load or store, and shuffles.
717 void execute(VPTransformState &State) override;
718
719 /// Print the recipe.
720 void print(raw_ostream &O, const Twine &Indent) const override;
721
722 const InterleaveGroup *getInterleaveGroup() { return IG; }
723};
724
725/// VPReplicateRecipe replicates a given instruction producing multiple scalar
726/// copies of the original scalar type, one per lane, instead of producing a
727/// single copy of widened type for all lanes. If the instruction is known to be
728/// uniform only one copy, per lane zero, will be generated.
729class VPReplicateRecipe : public VPRecipeBase {
730private:
731 /// The instruction being replicated.
732 Instruction *Ingredient;
733
734 /// Indicator if only a single replica per lane is needed.
735 bool IsUniform;
736
737 /// Indicator if the replicas are also predicated.
738 bool IsPredicated;
739
740 /// Indicator if the scalar values should also be packed into a vector.
741 bool AlsoPack;
742
743public:
744 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
745 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
746 IsPredicated(IsPredicated) {
747 // Retain the previous behavior of predicateInstructions(), where an
748 // insert-element of a predicated instruction got hoisted into the
749 // predicated basic block iff it was its only user. This is achieved by
750 // having predicated instructions also pack their values into a vector by
751 // default unless they have a replicated user which uses their scalar value.
752 AlsoPack = IsPredicated && !I->use_empty();
753 }
754
755 ~VPReplicateRecipe() override = default;
756
757 /// Method to support type inquiry through isa, cast, and dyn_cast.
758 static inline bool classof(const VPRecipeBase *V) {
759 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
760 }
761
762 /// Generate replicas of the desired Ingredient. Replicas will be generated
763 /// for all parts and lanes unless a specific part and lane are specified in
764 /// the \p State.
765 void execute(VPTransformState &State) override;
766
767 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
768
769 /// Print the recipe.
770 void print(raw_ostream &O, const Twine &Indent) const override;
771};
772
773/// A recipe for generating conditional branches on the bits of a mask.
774class VPBranchOnMaskRecipe : public VPRecipeBase {
775private:
776 std::unique_ptr<VPUser> User;
777
778public:
779 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
780 if (BlockInMask) // nullptr means all-one mask.
781 User.reset(new VPUser({BlockInMask}));
782 }
783
784 /// Method to support type inquiry through isa, cast, and dyn_cast.
785 static inline bool classof(const VPRecipeBase *V) {
786 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
787 }
788
789 /// Generate the extraction of the appropriate bit from the block mask and the
790 /// conditional branch.
791 void execute(VPTransformState &State) override;
792
793 /// Print the recipe.
794 void print(raw_ostream &O, const Twine &Indent) const override {
795 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
796 if (User)
797 O << *User->getOperand(0);
798 else
799 O << " All-One";
800 O << "\\l\"";
801 }
802};
803
804/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
805/// control converges back from a Branch-on-Mask. The phi nodes are needed in
806/// order to merge values that are set under such a branch and feed their uses.
807/// The phi nodes can be scalar or vector depending on the users of the value.
808/// This recipe works in concert with VPBranchOnMaskRecipe.
809class VPPredInstPHIRecipe : public VPRecipeBase {
810private:
811 Instruction *PredInst;
812
813public:
814 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
815 /// nodes after merging back from a Branch-on-Mask.
816 VPPredInstPHIRecipe(Instruction *PredInst)
817 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
818 ~VPPredInstPHIRecipe() override = default;
819
820 /// Method to support type inquiry through isa, cast, and dyn_cast.
821 static inline bool classof(const VPRecipeBase *V) {
822 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
823 }
824
825 /// Generates phi nodes for live-outs as needed to retain SSA form.
826 void execute(VPTransformState &State) override;
827
828 /// Print the recipe.
829 void print(raw_ostream &O, const Twine &Indent) const override;
830};
831
832/// A Recipe for widening load/store operations.
833/// TODO: We currently execute only per-part unless a specific instance is
834/// provided.
835class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
836private:
837 Instruction &Instr;
838 std::unique_ptr<VPUser> User;
839
840public:
841 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
842 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
843 if (Mask) // Create a VPInstruction to register as a user of the mask.
844 User.reset(new VPUser({Mask}));
845 }
846
847 /// Method to support type inquiry through isa, cast, and dyn_cast.
848 static inline bool classof(const VPRecipeBase *V) {
849 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
850 }
851
852 /// Generate the wide load/store.
853 void execute(VPTransformState &State) override;
854
855 /// Print the recipe.
856 void print(raw_ostream &O, const Twine &Indent) const override;
857};
858
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000859/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
860/// holds a sequence of zero or more VPRecipe's each representing a sequence of
861/// output IR instructions.
862class VPBasicBlock : public VPBlockBase {
863public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000864 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000865
866private:
867 /// The VPRecipes held in the order of output instructions to generate.
868 RecipeListTy Recipes;
869
870public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000871 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
872 : VPBlockBase(VPBasicBlockSC, Name.str()) {
873 if (Recipe)
874 appendRecipe(Recipe);
875 }
876
877 ~VPBasicBlock() override { Recipes.clear(); }
878
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000879 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000880 using iterator = RecipeListTy::iterator;
881 using const_iterator = RecipeListTy::const_iterator;
882 using reverse_iterator = RecipeListTy::reverse_iterator;
883 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000884
885 //===--------------------------------------------------------------------===//
886 /// Recipe iterator methods
887 ///
888 inline iterator begin() { return Recipes.begin(); }
889 inline const_iterator begin() const { return Recipes.begin(); }
890 inline iterator end() { return Recipes.end(); }
891 inline const_iterator end() const { return Recipes.end(); }
892
893 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
894 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
895 inline reverse_iterator rend() { return Recipes.rend(); }
896 inline const_reverse_iterator rend() const { return Recipes.rend(); }
897
898 inline size_t size() const { return Recipes.size(); }
899 inline bool empty() const { return Recipes.empty(); }
900 inline const VPRecipeBase &front() const { return Recipes.front(); }
901 inline VPRecipeBase &front() { return Recipes.front(); }
902 inline const VPRecipeBase &back() const { return Recipes.back(); }
903 inline VPRecipeBase &back() { return Recipes.back(); }
904
905 /// \brief Returns a pointer to a member of the recipe list.
906 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
907 return &VPBasicBlock::Recipes;
908 }
909
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000910 /// Method to support type inquiry through isa, cast, and dyn_cast.
911 static inline bool classof(const VPBlockBase *V) {
912 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
913 }
914
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000915 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000916 assert(Recipe && "No recipe to append.");
917 assert(!Recipe->Parent && "Recipe already in VPlan");
918 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000919 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000920 }
921
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000922 /// Augment the existing recipes of a VPBasicBlock with an additional
923 /// \p Recipe as the last recipe.
924 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
925
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000926 /// The method which generates the output IR instructions that correspond to
927 /// this VPBasicBlock, thereby "executing" the VPlan.
928 void execute(struct VPTransformState *State) override;
929
930private:
931 /// Create an IR BasicBlock to hold the output instructions generated by this
932 /// VPBasicBlock, and return it. Update the CFGState accordingly.
933 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
934};
935
936/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
937/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
938/// A VPRegionBlock may indicate that its contents are to be replicated several
939/// times. This is designed to support predicated scalarization, in which a
940/// scalar if-then code structure needs to be generated VF * UF times. Having
941/// this replication indicator helps to keep a single model for multiple
942/// candidate VF's. The actual replication takes place only once the desired VF
943/// and UF have been determined.
944class VPRegionBlock : public VPBlockBase {
945private:
946 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
947 VPBlockBase *Entry;
948
949 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
950 VPBlockBase *Exit;
951
952 /// An indicator whether this region is to generate multiple replicated
953 /// instances of output IR corresponding to its VPBlockBases.
954 bool IsReplicator;
955
956public:
957 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
958 const std::string &Name = "", bool IsReplicator = false)
959 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
960 IsReplicator(IsReplicator) {
961 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
962 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
963 Entry->setParent(this);
964 Exit->setParent(this);
965 }
966
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000967 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000968 if (Entry)
969 deleteCFG(Entry);
970 }
971
972 /// Method to support type inquiry through isa, cast, and dyn_cast.
973 static inline bool classof(const VPBlockBase *V) {
974 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
975 }
976
977 const VPBlockBase *getEntry() const { return Entry; }
978 VPBlockBase *getEntry() { return Entry; }
979
980 const VPBlockBase *getExit() const { return Exit; }
981 VPBlockBase *getExit() { return Exit; }
982
983 /// An indicator whether this region is to generate multiple replicated
984 /// instances of output IR corresponding to its VPBlockBases.
985 bool isReplicator() const { return IsReplicator; }
986
987 /// The method which generates the output IR instructions that correspond to
988 /// this VPRegionBlock, thereby "executing" the VPlan.
989 void execute(struct VPTransformState *State) override;
990};
991
992/// VPlan models a candidate for vectorization, encoding various decisions take
993/// to produce efficient output IR, including which branches, basic-blocks and
994/// output IR instructions to generate, and their cost. VPlan holds a
995/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
996/// VPBlock.
997class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000998 friend class VPlanPrinter;
999
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001000private:
1001 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1002 VPBlockBase *Entry;
1003
1004 /// Holds the VFs applicable to this VPlan.
1005 SmallSet<unsigned, 2> VFs;
1006
1007 /// Holds the name of the VPlan, for printing.
1008 std::string Name;
1009
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001010 /// Holds a mapping between Values and their corresponding VPValue inside
1011 /// VPlan.
1012 Value2VPValueTy Value2VPValue;
1013
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001014public:
1015 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1016
1017 ~VPlan() {
1018 if (Entry)
1019 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001020 for (auto &MapEntry : Value2VPValue)
1021 delete MapEntry.second;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001022 }
1023
1024 /// Generate the IR code for this VPlan.
1025 void execute(struct VPTransformState *State);
1026
1027 VPBlockBase *getEntry() { return Entry; }
1028 const VPBlockBase *getEntry() const { return Entry; }
1029
1030 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1031
1032 void addVF(unsigned VF) { VFs.insert(VF); }
1033
1034 bool hasVF(unsigned VF) { return VFs.count(VF); }
1035
1036 const std::string &getName() const { return Name; }
1037
1038 void setName(const Twine &newName) { Name = newName.str(); }
1039
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001040 void addVPValue(Value *V) {
1041 assert(V && "Trying to add a null Value to VPlan");
1042 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1043 Value2VPValue[V] = new VPValue();
1044 }
1045
1046 VPValue *getVPValue(Value *V) {
1047 assert(V && "Trying to get the VPValue of a null Value");
1048 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1049 return Value2VPValue[V];
1050 }
1051
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001052private:
1053 /// Add to the given dominator tree the header block and every new basic block
1054 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001055 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001056 BasicBlock *LoopPreHeaderBB,
1057 BasicBlock *LoopLatchBB);
1058};
1059
1060/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1061/// indented and follows the dot format.
1062class VPlanPrinter {
1063 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1064 friend inline raw_ostream &operator<<(raw_ostream &OS,
1065 const struct VPlanIngredient &I);
1066
1067private:
1068 raw_ostream &OS;
1069 VPlan &Plan;
1070 unsigned Depth;
1071 unsigned TabWidth = 2;
1072 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001073 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001074 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1075
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001076 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1077
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001078 /// Handle indentation.
1079 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1080
1081 /// Print a given \p Block of the Plan.
1082 void dumpBlock(const VPBlockBase *Block);
1083
1084 /// Print the information related to the CFG edges going out of a given
1085 /// \p Block, followed by printing the successor blocks themselves.
1086 void dumpEdges(const VPBlockBase *Block);
1087
1088 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1089 /// its successor blocks.
1090 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1091
1092 /// Print a given \p Region of the Plan.
1093 void dumpRegion(const VPRegionBlock *Region);
1094
1095 unsigned getOrCreateBID(const VPBlockBase *Block) {
1096 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1097 }
1098
1099 const Twine getOrCreateName(const VPBlockBase *Block);
1100
1101 const Twine getUID(const VPBlockBase *Block);
1102
1103 /// Print the information related to a CFG edge between two VPBlockBases.
1104 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1105 const Twine &Label);
1106
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001107 void dump();
1108
1109 static void printAsIngredient(raw_ostream &O, Value *V);
1110};
1111
1112struct VPlanIngredient {
1113 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001114
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001115 VPlanIngredient(Value *V) : V(V) {}
1116};
1117
1118inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1119 VPlanPrinter::printAsIngredient(OS, I.V);
1120 return OS;
1121}
1122
1123inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1124 VPlanPrinter Printer(OS, Plan);
1125 Printer.dump();
1126 return OS;
1127}
1128
1129//===--------------------------------------------------------------------===//
1130// GraphTraits specializations for VPlan/VPRegionBlock Control-Flow Graphs //
1131//===--------------------------------------------------------------------===//
1132
1133// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1134// graph of VPBlockBase nodes...
1135
1136template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001137 using NodeRef = VPBlockBase *;
1138 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001139
1140 static NodeRef getEntryNode(NodeRef N) { return N; }
1141
1142 static inline ChildIteratorType child_begin(NodeRef N) {
1143 return N->getSuccessors().begin();
1144 }
1145
1146 static inline ChildIteratorType child_end(NodeRef N) {
1147 return N->getSuccessors().end();
1148 }
1149};
1150
1151template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001152 using NodeRef = const VPBlockBase *;
1153 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001154
1155 static NodeRef getEntryNode(NodeRef N) { return N; }
1156
1157 static inline ChildIteratorType child_begin(NodeRef N) {
1158 return N->getSuccessors().begin();
1159 }
1160
1161 static inline ChildIteratorType child_end(NodeRef N) {
1162 return N->getSuccessors().end();
1163 }
1164};
1165
1166// Provide specializations of GraphTraits to be able to treat a VPBlockBase as a
1167// graph of VPBlockBase nodes... and to walk it in inverse order. Inverse order
1168// for a VPBlockBase is considered to be when traversing the predecessors of a
1169// VPBlockBase instead of its successors.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001170template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001171 using NodeRef = VPBlockBase *;
1172 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001173
1174 static Inverse<VPBlockBase *> getEntryNode(Inverse<VPBlockBase *> B) {
1175 return B;
1176 }
1177
1178 static inline ChildIteratorType child_begin(NodeRef N) {
1179 return N->getPredecessors().begin();
1180 }
1181
1182 static inline ChildIteratorType child_end(NodeRef N) {
1183 return N->getPredecessors().end();
1184 }
1185};
1186
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001187} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001188
1189#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H