blob: 6633322097129129b3cedf1e8d4eb9557aaf7bb6 [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
Diego Caballero35871502018-07-31 01:57:29 +000029#include "VPlanLoopInfo.h"
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000030#include "VPlanValue.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000031#include "llvm/ADT/DenseMap.h"
Diego Caballero2a34ac82018-07-30 21:33:31 +000032#include "llvm/ADT/DepthFirstIterator.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000033#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000034#include "llvm/ADT/Optional.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000035#include "llvm/ADT/SmallPtrSet.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000036#include "llvm/ADT/SmallSet.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/Twine.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000039#include "llvm/ADT/ilist.h"
40#include "llvm/ADT/ilist_node.h"
Florian Hahna4dc7fe2018-11-13 15:58:18 +000041#include "llvm/Analysis/VectorUtils.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000042#include "llvm/IR/IRBuilder.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000043#include <algorithm>
44#include <cassert>
45#include <cstddef>
46#include <map>
47#include <string>
Ayal Zaks1f58dda2017-08-27 12:55:46 +000048
49namespace llvm {
50
Hal Finkel0f1314c2018-01-07 16:02:58 +000051class LoopVectorizationLegality;
52class LoopVectorizationCostModel;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000053class BasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000054class DominatorTree;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000055class InnerLoopVectorizer;
Florian Hahna4dc7fe2018-11-13 15:58:18 +000056template <class T> class InterleaveGroup;
57class LoopInfo;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000058class raw_ostream;
59class Value;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000060class VPBasicBlock;
Eugene Zelenko6cadde72017-10-17 21:27:42 +000061class VPRegionBlock;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000062class VPlan;
63
64/// A range of powers-of-2 vectorization factors with fixed start and
65/// adjustable end. The range includes start and excludes end, e.g.,:
66/// [1, 9) = {1, 2, 4, 8}
67struct VFRange {
68 // A power of 2.
69 const unsigned Start;
70
71 // Need not be a power of 2. If End <= Start range is empty.
72 unsigned End;
73};
74
75using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000076
77/// In what follows, the term "input IR" refers to code that is fed into the
78/// vectorizer whereas the term "output IR" refers to code that is generated by
79/// the vectorizer.
80
81/// VPIteration represents a single point in the iteration space of the output
82/// (vectorized and/or unrolled) IR loop.
83struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000084 /// in [0..UF)
85 unsigned Part;
86
87 /// in [0..VF)
88 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000089};
90
91/// This is a helper struct for maintaining vectorization state. It's used for
92/// mapping values from the original loop to their corresponding values in
93/// the new loop. Two mappings are maintained: one for vectorized values and
94/// one for scalarized values. Vectorized values are represented with UF
95/// vector values in the new loop, and scalarized values are represented with
96/// UF x VF scalar values in the new loop. UF and VF are the unroll and
97/// vectorization factors, respectively.
98///
99/// Entries can be added to either map with setVectorValue and setScalarValue,
100/// which assert that an entry was not already added before. If an entry is to
101/// replace an existing one, call resetVectorValue and resetScalarValue. This is
102/// currently needed to modify the mapped values during "fix-up" operations that
103/// occur once the first phase of widening is complete. These operations include
104/// type truncation and the second phase of recurrence widening.
105///
106/// Entries from either map can be retrieved using the getVectorValue and
107/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000108struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000109 friend struct VPTransformState;
110
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000111private:
112 /// The unroll factor. Each entry in the vector map contains UF vector values.
113 unsigned UF;
114
115 /// The vectorization factor. Each entry in the scalar map contains UF x VF
116 /// scalar values.
117 unsigned VF;
118
119 /// The vector and scalar map storage. We use std::map and not DenseMap
120 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000121 using VectorParts = SmallVector<Value *, 2>;
122 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000123 std::map<Value *, VectorParts> VectorMapStorage;
124 std::map<Value *, ScalarParts> ScalarMapStorage;
125
126public:
127 /// Construct an empty map with the given unroll and vectorization factors.
128 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
129
130 /// \return True if the map has any vector entry for \p Key.
131 bool hasAnyVectorValue(Value *Key) const {
132 return VectorMapStorage.count(Key);
133 }
134
135 /// \return True if the map has a vector entry for \p Key and \p Part.
136 bool hasVectorValue(Value *Key, unsigned Part) const {
137 assert(Part < UF && "Queried Vector Part is too large.");
138 if (!hasAnyVectorValue(Key))
139 return false;
140 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
141 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
142 return Entry[Part] != nullptr;
143 }
144
145 /// \return True if the map has any scalar entry for \p Key.
146 bool hasAnyScalarValue(Value *Key) const {
147 return ScalarMapStorage.count(Key);
148 }
149
150 /// \return True if the map has a scalar entry for \p Key and \p Instance.
151 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
152 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
153 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
154 if (!hasAnyScalarValue(Key))
155 return false;
156 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
157 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
158 assert(Entry[Instance.Part].size() == VF &&
159 "ScalarParts has wrong dimensions.");
160 return Entry[Instance.Part][Instance.Lane] != nullptr;
161 }
162
163 /// Retrieve the existing vector value that corresponds to \p Key and
164 /// \p Part.
165 Value *getVectorValue(Value *Key, unsigned Part) {
166 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
167 return VectorMapStorage[Key][Part];
168 }
169
170 /// Retrieve the existing scalar value that corresponds to \p Key and
171 /// \p Instance.
172 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
173 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
174 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
175 }
176
177 /// Set a vector value associated with \p Key and \p Part. Assumes such a
178 /// value is not already set. If it is, use resetVectorValue() instead.
179 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
180 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
181 if (!VectorMapStorage.count(Key)) {
182 VectorParts Entry(UF);
183 VectorMapStorage[Key] = Entry;
184 }
185 VectorMapStorage[Key][Part] = Vector;
186 }
187
188 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
189 /// value is not already set.
190 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
191 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
192 if (!ScalarMapStorage.count(Key)) {
193 ScalarParts Entry(UF);
194 // TODO: Consider storing uniform values only per-part, as they occupy
195 // lane 0 only, keeping the other VF-1 redundant entries null.
196 for (unsigned Part = 0; Part < UF; ++Part)
197 Entry[Part].resize(VF, nullptr);
198 ScalarMapStorage[Key] = Entry;
199 }
200 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
201 }
202
203 /// Reset the vector value associated with \p Key for the given \p Part.
204 /// This function can be used to update values that have already been
205 /// vectorized. This is the case for "fix-up" operations including type
206 /// truncation and the second phase of recurrence vectorization.
207 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
208 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
209 VectorMapStorage[Key][Part] = Vector;
210 }
211
212 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
213 /// This function can be used to update values that have already been
214 /// scalarized. This is the case for "fix-up" operations including scalar phi
215 /// nodes for scalarized and predicated instructions.
216 void resetScalarValue(Value *Key, const VPIteration &Instance,
217 Value *Scalar) {
218 assert(hasScalarValue(Key, Instance) &&
219 "Scalar value not set for part and lane");
220 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
221 }
222};
223
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000224/// This class is used to enable the VPlan to invoke a method of ILV. This is
225/// needed until the method is refactored out of ILV and becomes reusable.
226struct VPCallback {
227 virtual ~VPCallback() {}
228 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
229};
230
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000231/// VPTransformState holds information passed down when "executing" a VPlan,
232/// needed for generating the output IR.
233struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000234 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
235 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000236 InnerLoopVectorizer *ILV, VPCallback &Callback)
237 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
238 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000239
240 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
241 unsigned VF;
242 unsigned UF;
243
244 /// Hold the indices to generate specific scalar instructions. Null indicates
245 /// that all instances are to be generated, using either scalar or vector
246 /// instructions.
247 Optional<VPIteration> Instance;
248
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000249 struct DataState {
250 /// A type for vectorized values in the new loop. Each value from the
251 /// original loop, when vectorized, is represented by UF vector values in
252 /// the new unrolled loop, where UF is the unroll factor.
253 typedef SmallVector<Value *, 2> PerPartValuesTy;
254
255 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
256 } Data;
257
258 /// Get the generated Value for a given VPValue and a given Part. Note that
259 /// as some Defs are still created by ILV and managed in its ValueMap, this
260 /// method will delegate the call to ILV in such cases in order to provide
261 /// callers a consistent API.
262 /// \see set.
263 Value *get(VPValue *Def, unsigned Part) {
264 // If Values have been set for this Def return the one relevant for \p Part.
265 if (Data.PerPartOutput.count(Def))
266 return Data.PerPartOutput[Def][Part];
267 // Def is managed by ILV: bring the Values from ValueMap.
268 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
269 }
270
271 /// Set the generated Value for a given VPValue and a given Part.
272 void set(VPValue *Def, Value *V, unsigned Part) {
273 if (!Data.PerPartOutput.count(Def)) {
274 DataState::PerPartValuesTy Entry(UF);
275 Data.PerPartOutput[Def] = Entry;
276 }
277 Data.PerPartOutput[Def][Part] = V;
278 }
279
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000280 /// Hold state information used when constructing the CFG of the output IR,
281 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
282 struct CFGState {
283 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000284 VPBasicBlock *PrevVPBB = nullptr;
285
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000286 /// The previous IR BasicBlock created or used. Initially set to the new
287 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000288 BasicBlock *PrevBB = nullptr;
289
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000290 /// The last IR BasicBlock in the output IR. Set to the new latch
291 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000292 BasicBlock *LastBB = nullptr;
293
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000294 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
295 /// of replication, maps the BasicBlock of the last replica created.
296 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
297
Hideki Saitoea7f3032018-09-14 00:36:00 +0000298 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
299 /// up at the end of vector code generation.
300 SmallVector<VPBasicBlock *, 8> VPBBsToFix;
301
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000302 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000303 } CFG;
304
305 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000306 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000307
308 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000309 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000310
311 /// Hold a reference to the IRBuilder used to generate output IR code.
312 IRBuilder<> &Builder;
313
314 /// Hold a reference to the Value state information used when generating the
315 /// Values of the output IR.
316 VectorizerValueMap &ValueMap;
317
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000318 /// Hold a reference to a mapping between VPValues in VPlan and original
319 /// Values they correspond to.
320 VPValue2ValueTy VPValue2Value;
321
Ayal Zaksb0b53122018-10-18 15:03:15 +0000322 /// Hold the trip count of the scalar loop.
323 Value *TripCount = nullptr;
324
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000325 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000326 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000327
328 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000329};
330
331/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
332/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
333class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000334 friend class VPBlockUtils;
335
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000336private:
337 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
338
339 /// An optional name for the block.
340 std::string Name;
341
342 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
343 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000344 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000345
346 /// List of predecessor blocks.
347 SmallVector<VPBlockBase *, 1> Predecessors;
348
349 /// List of successor blocks.
350 SmallVector<VPBlockBase *, 1> Successors;
351
Diego Caballerod0953012018-07-09 15:57:09 +0000352 /// Successor selector, null for zero or single successor blocks.
353 VPValue *CondBit = nullptr;
354
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000355 /// Add \p Successor as the last successor to this block.
356 void appendSuccessor(VPBlockBase *Successor) {
357 assert(Successor && "Cannot add nullptr successor!");
358 Successors.push_back(Successor);
359 }
360
361 /// Add \p Predecessor as the last predecessor to this block.
362 void appendPredecessor(VPBlockBase *Predecessor) {
363 assert(Predecessor && "Cannot add nullptr predecessor!");
364 Predecessors.push_back(Predecessor);
365 }
366
367 /// Remove \p Predecessor from the predecessors of this block.
368 void removePredecessor(VPBlockBase *Predecessor) {
369 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
370 assert(Pos && "Predecessor does not exist");
371 Predecessors.erase(Pos);
372 }
373
374 /// Remove \p Successor from the successors of this block.
375 void removeSuccessor(VPBlockBase *Successor) {
376 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
377 assert(Pos && "Successor does not exist");
378 Successors.erase(Pos);
379 }
380
381protected:
382 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000383 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000384
385public:
386 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
387 /// that are actually instantiated. Values of this enumeration are kept in the
388 /// SubclassID field of the VPBlockBase objects. They are used for concrete
389 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000390 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000391
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000392 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000393
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000394 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000395
396 const std::string &getName() const { return Name; }
397
398 void setName(const Twine &newName) { Name = newName.str(); }
399
400 /// \return an ID for the concrete type of this object.
401 /// This is used to implement the classof checks. This should not be used
402 /// for any other purpose, as the values may change as LLVM evolves.
403 unsigned getVPBlockID() const { return SubclassID; }
404
Diego Caballero168d04d2018-05-21 18:14:23 +0000405 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000406 const VPRegionBlock *getParent() const { return Parent; }
407
408 void setParent(VPRegionBlock *P) { Parent = P; }
409
410 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
411 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
412 /// VPBlockBase is a VPBasicBlock, it is returned.
413 const VPBasicBlock *getEntryBasicBlock() const;
414 VPBasicBlock *getEntryBasicBlock();
415
416 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
417 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
418 /// VPBlockBase is a VPBasicBlock, it is returned.
419 const VPBasicBlock *getExitBasicBlock() const;
420 VPBasicBlock *getExitBasicBlock();
421
422 const VPBlocksTy &getSuccessors() const { return Successors; }
423 VPBlocksTy &getSuccessors() { return Successors; }
424
425 const VPBlocksTy &getPredecessors() const { return Predecessors; }
426 VPBlocksTy &getPredecessors() { return Predecessors; }
427
428 /// \return the successor of this VPBlockBase if it has a single successor.
429 /// Otherwise return a null pointer.
430 VPBlockBase *getSingleSuccessor() const {
431 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
432 }
433
434 /// \return the predecessor of this VPBlockBase if it has a single
435 /// predecessor. Otherwise return a null pointer.
436 VPBlockBase *getSinglePredecessor() const {
437 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
438 }
439
Diego Caballero168d04d2018-05-21 18:14:23 +0000440 size_t getNumSuccessors() const { return Successors.size(); }
441 size_t getNumPredecessors() const { return Predecessors.size(); }
442
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000443 /// An Enclosing Block of a block B is any block containing B, including B
444 /// itself. \return the closest enclosing block starting from "this", which
445 /// has successors. \return the root enclosing block if all enclosing blocks
446 /// have no successors.
447 VPBlockBase *getEnclosingBlockWithSuccessors();
448
449 /// \return the closest enclosing block starting from "this", which has
450 /// predecessors. \return the root enclosing block if all enclosing blocks
451 /// have no predecessors.
452 VPBlockBase *getEnclosingBlockWithPredecessors();
453
454 /// \return the successors either attached directly to this VPBlockBase or, if
455 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
456 /// successors of its own, search recursively for the first enclosing
457 /// VPRegionBlock that has successors and return them. If no such
458 /// VPRegionBlock exists, return the (empty) successors of the topmost
459 /// VPBlockBase reached.
460 const VPBlocksTy &getHierarchicalSuccessors() {
461 return getEnclosingBlockWithSuccessors()->getSuccessors();
462 }
463
464 /// \return the hierarchical successor of this VPBlockBase if it has a single
465 /// hierarchical successor. Otherwise return a null pointer.
466 VPBlockBase *getSingleHierarchicalSuccessor() {
467 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
468 }
469
470 /// \return the predecessors either attached directly to this VPBlockBase or,
471 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
472 /// predecessors of its own, search recursively for the first enclosing
473 /// VPRegionBlock that has predecessors and return them. If no such
474 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
475 /// VPBlockBase reached.
476 const VPBlocksTy &getHierarchicalPredecessors() {
477 return getEnclosingBlockWithPredecessors()->getPredecessors();
478 }
479
480 /// \return the hierarchical predecessor of this VPBlockBase if it has a
481 /// single hierarchical predecessor. Otherwise return a null pointer.
482 VPBlockBase *getSingleHierarchicalPredecessor() {
483 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
484 }
485
Diego Caballerod0953012018-07-09 15:57:09 +0000486 /// \return the condition bit selecting the successor.
487 VPValue *getCondBit() { return CondBit; }
488
489 const VPValue *getCondBit() const { return CondBit; }
490
491 void setCondBit(VPValue *CV) { CondBit = CV; }
492
Diego Caballero168d04d2018-05-21 18:14:23 +0000493 /// Set a given VPBlockBase \p Successor as the single successor of this
494 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
495 /// This VPBlockBase must have no successors.
496 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000497 assert(Successors.empty() && "Setting one successor when others exist.");
498 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000499 }
500
Diego Caballero168d04d2018-05-21 18:14:23 +0000501 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
Diego Caballerod0953012018-07-09 15:57:09 +0000502 /// successors of this VPBlockBase. \p Condition is set as the successor
503 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
504 /// IfFalse. This VPBlockBase must have no successors.
505 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
506 VPValue *Condition) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000507 assert(Successors.empty() && "Setting two successors when others exist.");
Diego Caballerod0953012018-07-09 15:57:09 +0000508 assert(Condition && "Setting two successors without condition!");
509 CondBit = Condition;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000510 appendSuccessor(IfTrue);
511 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000512 }
513
Diego Caballero168d04d2018-05-21 18:14:23 +0000514 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
515 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
516 /// as successor of any VPBasicBlock in \p NewPreds.
517 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
518 assert(Predecessors.empty() && "Block predecessors already set.");
519 for (auto *Pred : NewPreds)
520 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000521 }
522
523 /// The method which generates the output IR that correspond to this
524 /// VPBlockBase, thereby "executing" the VPlan.
525 virtual void execute(struct VPTransformState *State) = 0;
526
527 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
528 static void deleteCFG(VPBlockBase *Entry);
Diego Caballero2a34ac82018-07-30 21:33:31 +0000529
530 void printAsOperand(raw_ostream &OS, bool PrintType) const {
531 OS << getName();
532 }
533
534 void print(raw_ostream &OS) const {
535 // TODO: Only printing VPBB name for now since we only have dot printing
536 // support for VPInstructions/Recipes.
537 printAsOperand(OS, false);
538 }
Diego Caballero35871502018-07-31 01:57:29 +0000539
540 /// Return true if it is legal to hoist instructions into this block.
541 bool isLegalToHoistInto() {
542 // There are currently no constraints that prevent an instruction to be
543 // hoisted into a VPBlockBase.
544 return true;
545 }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000546};
547
548/// VPRecipeBase is a base class modeling a sequence of one or more output IR
549/// instructions.
550class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
551 friend VPBasicBlock;
552
553private:
554 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
555
556 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000557 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000558
559public:
560 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
561 /// that is actually instantiated. Values of this enumeration are kept in the
562 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
563 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000564 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000565 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000566 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000567 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000568 VPInterleaveSC,
569 VPPredInstPHISC,
570 VPReplicateSC,
571 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000572 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000573 VPWidenPHISC,
574 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000575 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000576
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000577 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
578 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000579
580 /// \return an ID for the concrete type of this object.
581 /// This is used to implement the classof checks. This should not be used
582 /// for any other purpose, as the values may change as LLVM evolves.
583 unsigned getVPRecipeID() const { return SubclassID; }
584
585 /// \return the VPBasicBlock which this VPRecipe belongs to.
586 VPBasicBlock *getParent() { return Parent; }
587 const VPBasicBlock *getParent() const { return Parent; }
588
589 /// The method which generates the output IR instructions that correspond to
590 /// this VPRecipe, thereby "executing" the VPlan.
591 virtual void execute(struct VPTransformState &State) = 0;
592
593 /// Each recipe prints itself.
594 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
Florian Hahn7591e4e2018-06-18 11:34:17 +0000595
596 /// Insert an unlinked recipe into a basic block immediately before
597 /// the specified recipe.
598 void insertBefore(VPRecipeBase *InsertPos);
Florian Hahn63cbcf92018-06-18 15:18:48 +0000599
600 /// This method unlinks 'this' from the containing basic block and deletes it.
601 ///
602 /// \returns an iterator pointing to the element after the erased one
603 iplist<VPRecipeBase>::iterator eraseFromParent();
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000604};
605
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000606/// This is a concrete Recipe that models a single VPlan-level instruction.
607/// While as any Recipe it may generate a sequence of IR instructions when
608/// executed, these instructions would always form a single-def expression as
609/// the VPInstruction is also a single def-use vertex.
610class VPInstruction : public VPUser, public VPRecipeBase {
Florian Hahn3385caa2018-06-18 18:28:49 +0000611 friend class VPlanHCFGTransforms;
612
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000613public:
614 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
Ayal Zaksb0b53122018-10-18 15:03:15 +0000615 enum { Not = Instruction::OtherOpsEnd + 1, ICmpULE };
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000616
617private:
618 typedef unsigned char OpcodeTy;
619 OpcodeTy Opcode;
620
621 /// Utility method serving execute(): generates a single instance of the
622 /// modeled instruction.
623 void generateInstruction(VPTransformState &State, unsigned Part);
624
625public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000626 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000627 : VPUser(VPValue::VPInstructionSC, Operands),
628 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
629
Diego Caballero168d04d2018-05-21 18:14:23 +0000630 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
631 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
632
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000633 /// Method to support type inquiry through isa, cast, and dyn_cast.
634 static inline bool classof(const VPValue *V) {
635 return V->getVPValueID() == VPValue::VPInstructionSC;
636 }
637
638 /// Method to support type inquiry through isa, cast, and dyn_cast.
639 static inline bool classof(const VPRecipeBase *R) {
640 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
641 }
642
643 unsigned getOpcode() const { return Opcode; }
644
645 /// Generate the instruction.
646 /// TODO: We currently execute only per-part unless a specific instance is
647 /// provided.
648 void execute(VPTransformState &State) override;
649
650 /// Print the Recipe.
651 void print(raw_ostream &O, const Twine &Indent) const override;
652
653 /// Print the VPInstruction.
654 void print(raw_ostream &O) const;
655};
656
Hal Finkel7333aa92017-12-16 01:12:50 +0000657/// VPWidenRecipe is a recipe for producing a copy of vector type for each
658/// Instruction in its ingredients independently, in order. This recipe covers
659/// most of the traditional vectorization cases where each ingredient transforms
660/// into a vectorized version of itself.
661class VPWidenRecipe : public VPRecipeBase {
662private:
663 /// Hold the ingredients by pointing to their original BasicBlock location.
664 BasicBlock::iterator Begin;
665 BasicBlock::iterator End;
666
667public:
668 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
669 End = I->getIterator();
670 Begin = End++;
671 }
672
673 ~VPWidenRecipe() override = default;
674
675 /// Method to support type inquiry through isa, cast, and dyn_cast.
676 static inline bool classof(const VPRecipeBase *V) {
677 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
678 }
679
680 /// Produce widened copies of all Ingredients.
681 void execute(VPTransformState &State) override;
682
683 /// Augment the recipe to include Instr, if it lies at its End.
684 bool appendInstruction(Instruction *Instr) {
685 if (End != Instr->getIterator())
686 return false;
687 End++;
688 return true;
689 }
690
691 /// Print the recipe.
692 void print(raw_ostream &O, const Twine &Indent) const override;
693};
694
695/// A recipe for handling phi nodes of integer and floating-point inductions,
696/// producing their vector and scalar values.
697class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
698private:
699 PHINode *IV;
700 TruncInst *Trunc;
701
702public:
703 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
704 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
705 ~VPWidenIntOrFpInductionRecipe() override = default;
706
707 /// Method to support type inquiry through isa, cast, and dyn_cast.
708 static inline bool classof(const VPRecipeBase *V) {
709 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
710 }
711
712 /// Generate the vectorized and scalarized versions of the phi node as
713 /// needed by their users.
714 void execute(VPTransformState &State) override;
715
716 /// Print the recipe.
717 void print(raw_ostream &O, const Twine &Indent) const override;
718};
719
720/// A recipe for handling all phi nodes except for integer and FP inductions.
721class VPWidenPHIRecipe : public VPRecipeBase {
722private:
723 PHINode *Phi;
724
725public:
726 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
727 ~VPWidenPHIRecipe() override = default;
728
729 /// Method to support type inquiry through isa, cast, and dyn_cast.
730 static inline bool classof(const VPRecipeBase *V) {
731 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
732 }
733
734 /// Generate the phi/select nodes.
735 void execute(VPTransformState &State) override;
736
737 /// Print the recipe.
738 void print(raw_ostream &O, const Twine &Indent) const override;
739};
740
741/// A recipe for vectorizing a phi-node as a sequence of mask-based select
742/// instructions.
743class VPBlendRecipe : public VPRecipeBase {
744private:
745 PHINode *Phi;
746
747 /// The blend operation is a User of a mask, if not null.
748 std::unique_ptr<VPUser> User;
749
750public:
751 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
752 : VPRecipeBase(VPBlendSC), Phi(Phi) {
753 assert((Phi->getNumIncomingValues() == 1 ||
754 Phi->getNumIncomingValues() == Masks.size()) &&
755 "Expected the same number of incoming values and masks");
756 if (!Masks.empty())
757 User.reset(new VPUser(Masks));
758 }
759
760 /// Method to support type inquiry through isa, cast, and dyn_cast.
761 static inline bool classof(const VPRecipeBase *V) {
762 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
763 }
764
765 /// Generate the phi/select nodes.
766 void execute(VPTransformState &State) override;
767
768 /// Print the recipe.
769 void print(raw_ostream &O, const Twine &Indent) const override;
770};
771
772/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
773/// or stores into one wide load/store and shuffles.
774class VPInterleaveRecipe : public VPRecipeBase {
775private:
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000776 const InterleaveGroup<Instruction> *IG;
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000777 std::unique_ptr<VPUser> User;
Hal Finkel7333aa92017-12-16 01:12:50 +0000778
779public:
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000780 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Mask)
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000781 : VPRecipeBase(VPInterleaveSC), IG(IG) {
782 if (Mask) // Create a VPInstruction to register as a user of the mask.
783 User.reset(new VPUser({Mask}));
784 }
Hal Finkel7333aa92017-12-16 01:12:50 +0000785 ~VPInterleaveRecipe() override = default;
786
787 /// Method to support type inquiry through isa, cast, and dyn_cast.
788 static inline bool classof(const VPRecipeBase *V) {
789 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
790 }
791
792 /// Generate the wide load or store, and shuffles.
793 void execute(VPTransformState &State) override;
794
795 /// Print the recipe.
796 void print(raw_ostream &O, const Twine &Indent) const override;
797
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000798 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
Hal Finkel7333aa92017-12-16 01:12:50 +0000799};
800
801/// VPReplicateRecipe replicates a given instruction producing multiple scalar
802/// copies of the original scalar type, one per lane, instead of producing a
803/// single copy of widened type for all lanes. If the instruction is known to be
804/// uniform only one copy, per lane zero, will be generated.
805class VPReplicateRecipe : public VPRecipeBase {
806private:
807 /// The instruction being replicated.
808 Instruction *Ingredient;
809
810 /// Indicator if only a single replica per lane is needed.
811 bool IsUniform;
812
813 /// Indicator if the replicas are also predicated.
814 bool IsPredicated;
815
816 /// Indicator if the scalar values should also be packed into a vector.
817 bool AlsoPack;
818
819public:
820 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
821 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
822 IsPredicated(IsPredicated) {
823 // Retain the previous behavior of predicateInstructions(), where an
824 // insert-element of a predicated instruction got hoisted into the
825 // predicated basic block iff it was its only user. This is achieved by
826 // having predicated instructions also pack their values into a vector by
827 // default unless they have a replicated user which uses their scalar value.
828 AlsoPack = IsPredicated && !I->use_empty();
829 }
830
831 ~VPReplicateRecipe() override = default;
832
833 /// Method to support type inquiry through isa, cast, and dyn_cast.
834 static inline bool classof(const VPRecipeBase *V) {
835 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
836 }
837
838 /// Generate replicas of the desired Ingredient. Replicas will be generated
839 /// for all parts and lanes unless a specific part and lane are specified in
840 /// the \p State.
841 void execute(VPTransformState &State) override;
842
843 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
844
845 /// Print the recipe.
846 void print(raw_ostream &O, const Twine &Indent) const override;
847};
848
849/// A recipe for generating conditional branches on the bits of a mask.
850class VPBranchOnMaskRecipe : public VPRecipeBase {
851private:
852 std::unique_ptr<VPUser> User;
853
854public:
855 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
856 if (BlockInMask) // nullptr means all-one mask.
857 User.reset(new VPUser({BlockInMask}));
858 }
859
860 /// Method to support type inquiry through isa, cast, and dyn_cast.
861 static inline bool classof(const VPRecipeBase *V) {
862 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
863 }
864
865 /// Generate the extraction of the appropriate bit from the block mask and the
866 /// conditional branch.
867 void execute(VPTransformState &State) override;
868
869 /// Print the recipe.
870 void print(raw_ostream &O, const Twine &Indent) const override {
871 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
872 if (User)
873 O << *User->getOperand(0);
874 else
875 O << " All-One";
876 O << "\\l\"";
877 }
878};
879
880/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
881/// control converges back from a Branch-on-Mask. The phi nodes are needed in
882/// order to merge values that are set under such a branch and feed their uses.
883/// The phi nodes can be scalar or vector depending on the users of the value.
884/// This recipe works in concert with VPBranchOnMaskRecipe.
885class VPPredInstPHIRecipe : public VPRecipeBase {
886private:
887 Instruction *PredInst;
888
889public:
890 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
891 /// nodes after merging back from a Branch-on-Mask.
892 VPPredInstPHIRecipe(Instruction *PredInst)
893 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
894 ~VPPredInstPHIRecipe() override = default;
895
896 /// Method to support type inquiry through isa, cast, and dyn_cast.
897 static inline bool classof(const VPRecipeBase *V) {
898 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
899 }
900
901 /// Generates phi nodes for live-outs as needed to retain SSA form.
902 void execute(VPTransformState &State) override;
903
904 /// Print the recipe.
905 void print(raw_ostream &O, const Twine &Indent) const override;
906};
907
908/// A Recipe for widening load/store operations.
909/// TODO: We currently execute only per-part unless a specific instance is
910/// provided.
911class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
912private:
913 Instruction &Instr;
914 std::unique_ptr<VPUser> User;
915
916public:
917 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
918 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
919 if (Mask) // Create a VPInstruction to register as a user of the mask.
920 User.reset(new VPUser({Mask}));
921 }
922
923 /// Method to support type inquiry through isa, cast, and dyn_cast.
924 static inline bool classof(const VPRecipeBase *V) {
925 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
926 }
927
928 /// Generate the wide load/store.
929 void execute(VPTransformState &State) override;
930
931 /// Print the recipe.
932 void print(raw_ostream &O, const Twine &Indent) const override;
933};
934
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000935/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
936/// holds a sequence of zero or more VPRecipe's each representing a sequence of
937/// output IR instructions.
938class VPBasicBlock : public VPBlockBase {
939public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000940 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000941
942private:
943 /// The VPRecipes held in the order of output instructions to generate.
944 RecipeListTy Recipes;
945
946public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000947 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
948 : VPBlockBase(VPBasicBlockSC, Name.str()) {
949 if (Recipe)
950 appendRecipe(Recipe);
951 }
952
953 ~VPBasicBlock() override { Recipes.clear(); }
954
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000955 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000956 using iterator = RecipeListTy::iterator;
957 using const_iterator = RecipeListTy::const_iterator;
958 using reverse_iterator = RecipeListTy::reverse_iterator;
959 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000960
961 //===--------------------------------------------------------------------===//
962 /// Recipe iterator methods
963 ///
964 inline iterator begin() { return Recipes.begin(); }
965 inline const_iterator begin() const { return Recipes.begin(); }
966 inline iterator end() { return Recipes.end(); }
967 inline const_iterator end() const { return Recipes.end(); }
968
969 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
970 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
971 inline reverse_iterator rend() { return Recipes.rend(); }
972 inline const_reverse_iterator rend() const { return Recipes.rend(); }
973
974 inline size_t size() const { return Recipes.size(); }
975 inline bool empty() const { return Recipes.empty(); }
976 inline const VPRecipeBase &front() const { return Recipes.front(); }
977 inline VPRecipeBase &front() { return Recipes.front(); }
978 inline const VPRecipeBase &back() const { return Recipes.back(); }
979 inline VPRecipeBase &back() { return Recipes.back(); }
980
Florian Hahn7591e4e2018-06-18 11:34:17 +0000981 /// Returns a reference to the list of recipes.
982 RecipeListTy &getRecipeList() { return Recipes; }
983
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000984 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000985 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
986 return &VPBasicBlock::Recipes;
987 }
988
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000989 /// Method to support type inquiry through isa, cast, and dyn_cast.
990 static inline bool classof(const VPBlockBase *V) {
991 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
992 }
993
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000994 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000995 assert(Recipe && "No recipe to append.");
996 assert(!Recipe->Parent && "Recipe already in VPlan");
997 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000998 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000999 }
1000
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001001 /// Augment the existing recipes of a VPBasicBlock with an additional
1002 /// \p Recipe as the last recipe.
1003 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1004
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001005 /// The method which generates the output IR instructions that correspond to
1006 /// this VPBasicBlock, thereby "executing" the VPlan.
1007 void execute(struct VPTransformState *State) override;
1008
1009private:
1010 /// Create an IR BasicBlock to hold the output instructions generated by this
1011 /// VPBasicBlock, and return it. Update the CFGState accordingly.
1012 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1013};
1014
1015/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1016/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1017/// A VPRegionBlock may indicate that its contents are to be replicated several
1018/// times. This is designed to support predicated scalarization, in which a
1019/// scalar if-then code structure needs to be generated VF * UF times. Having
1020/// this replication indicator helps to keep a single model for multiple
1021/// candidate VF's. The actual replication takes place only once the desired VF
1022/// and UF have been determined.
1023class VPRegionBlock : public VPBlockBase {
1024private:
1025 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1026 VPBlockBase *Entry;
1027
1028 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1029 VPBlockBase *Exit;
1030
1031 /// An indicator whether this region is to generate multiple replicated
1032 /// instances of output IR corresponding to its VPBlockBases.
1033 bool IsReplicator;
1034
1035public:
1036 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1037 const std::string &Name = "", bool IsReplicator = false)
1038 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1039 IsReplicator(IsReplicator) {
1040 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1041 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1042 Entry->setParent(this);
1043 Exit->setParent(this);
1044 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001045 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1046 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1047 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001048
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001049 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001050 if (Entry)
1051 deleteCFG(Entry);
1052 }
1053
1054 /// Method to support type inquiry through isa, cast, and dyn_cast.
1055 static inline bool classof(const VPBlockBase *V) {
1056 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1057 }
1058
1059 const VPBlockBase *getEntry() const { return Entry; }
1060 VPBlockBase *getEntry() { return Entry; }
1061
Diego Caballero168d04d2018-05-21 18:14:23 +00001062 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1063 /// EntryBlock must have no predecessors.
1064 void setEntry(VPBlockBase *EntryBlock) {
1065 assert(EntryBlock->getPredecessors().empty() &&
1066 "Entry block cannot have predecessors.");
1067 Entry = EntryBlock;
1068 EntryBlock->setParent(this);
1069 }
1070
Diego Caballero2a34ac82018-07-30 21:33:31 +00001071 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1072 // specific interface of llvm::Function, instead of using
1073 // GraphTraints::getEntryNode. We should add a new template parameter to
1074 // DominatorTreeBase representing the Graph type.
1075 VPBlockBase &front() const { return *Entry; }
1076
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001077 const VPBlockBase *getExit() const { return Exit; }
1078 VPBlockBase *getExit() { return Exit; }
1079
Diego Caballero168d04d2018-05-21 18:14:23 +00001080 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1081 /// ExitBlock must have no successors.
1082 void setExit(VPBlockBase *ExitBlock) {
1083 assert(ExitBlock->getSuccessors().empty() &&
1084 "Exit block cannot have successors.");
1085 Exit = ExitBlock;
1086 ExitBlock->setParent(this);
1087 }
1088
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001089 /// An indicator whether this region is to generate multiple replicated
1090 /// instances of output IR corresponding to its VPBlockBases.
1091 bool isReplicator() const { return IsReplicator; }
1092
1093 /// The method which generates the output IR instructions that correspond to
1094 /// this VPRegionBlock, thereby "executing" the VPlan.
1095 void execute(struct VPTransformState *State) override;
1096};
1097
1098/// VPlan models a candidate for vectorization, encoding various decisions take
1099/// to produce efficient output IR, including which branches, basic-blocks and
1100/// output IR instructions to generate, and their cost. VPlan holds a
1101/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1102/// VPBlock.
1103class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001104 friend class VPlanPrinter;
1105
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001106private:
1107 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1108 VPBlockBase *Entry;
1109
1110 /// Holds the VFs applicable to this VPlan.
1111 SmallSet<unsigned, 2> VFs;
1112
1113 /// Holds the name of the VPlan, for printing.
1114 std::string Name;
1115
Diego Caballero168d04d2018-05-21 18:14:23 +00001116 /// Holds all the external definitions created for this VPlan.
1117 // TODO: Introduce a specific representation for external definitions in
1118 // VPlan. External definitions must be immutable and hold a pointer to its
1119 // underlying IR that will be used to implement its structural comparison
1120 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001121 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001122
Ayal Zaksb0b53122018-10-18 15:03:15 +00001123 /// Represents the backedge taken count of the original loop, for folding
1124 /// the tail.
1125 VPValue *BackedgeTakenCount = nullptr;
1126
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001127 /// Holds a mapping between Values and their corresponding VPValue inside
1128 /// VPlan.
1129 Value2VPValueTy Value2VPValue;
1130
Diego Caballero35871502018-07-31 01:57:29 +00001131 /// Holds the VPLoopInfo analysis for this VPlan.
1132 VPLoopInfo VPLInfo;
1133
Hideki Saitod19851a2018-09-14 02:02:57 +00001134 /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1135 SmallVector<VPValue *, 4> VPCBVs;
1136
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001137public:
1138 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1139
1140 ~VPlan() {
1141 if (Entry)
1142 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001143 for (auto &MapEntry : Value2VPValue)
Ayal Zaksb0b53122018-10-18 15:03:15 +00001144 if (MapEntry.second != BackedgeTakenCount)
1145 delete MapEntry.second;
1146 if (BackedgeTakenCount)
1147 delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not.
Diego Caballero168d04d2018-05-21 18:14:23 +00001148 for (VPValue *Def : VPExternalDefs)
1149 delete Def;
Hideki Saitod19851a2018-09-14 02:02:57 +00001150 for (VPValue *CBV : VPCBVs)
1151 delete CBV;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001152 }
1153
1154 /// Generate the IR code for this VPlan.
1155 void execute(struct VPTransformState *State);
1156
1157 VPBlockBase *getEntry() { return Entry; }
1158 const VPBlockBase *getEntry() const { return Entry; }
1159
1160 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1161
Ayal Zaksb0b53122018-10-18 15:03:15 +00001162 /// The backedge taken count of the original loop.
1163 VPValue *getOrCreateBackedgeTakenCount() {
1164 if (!BackedgeTakenCount)
1165 BackedgeTakenCount = new VPValue();
1166 return BackedgeTakenCount;
1167 }
1168
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001169 void addVF(unsigned VF) { VFs.insert(VF); }
1170
1171 bool hasVF(unsigned VF) { return VFs.count(VF); }
1172
1173 const std::string &getName() const { return Name; }
1174
1175 void setName(const Twine &newName) { Name = newName.str(); }
1176
Diego Caballero168d04d2018-05-21 18:14:23 +00001177 /// Add \p VPVal to the pool of external definitions if it's not already
1178 /// in the pool.
1179 void addExternalDef(VPValue *VPVal) {
1180 VPExternalDefs.insert(VPVal);
1181 }
1182
Hideki Saitod19851a2018-09-14 02:02:57 +00001183 /// Add \p CBV to the vector of condition bit values.
1184 void addCBV(VPValue *CBV) {
1185 VPCBVs.push_back(CBV);
1186 }
1187
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001188 void addVPValue(Value *V) {
1189 assert(V && "Trying to add a null Value to VPlan");
1190 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1191 Value2VPValue[V] = new VPValue();
1192 }
1193
1194 VPValue *getVPValue(Value *V) {
1195 assert(V && "Trying to get the VPValue of a null Value");
1196 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1197 return Value2VPValue[V];
1198 }
1199
Diego Caballero35871502018-07-31 01:57:29 +00001200 /// Return the VPLoopInfo analysis for this VPlan.
1201 VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1202 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1203
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001204private:
1205 /// Add to the given dominator tree the header block and every new basic block
1206 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001207 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001208 BasicBlock *LoopPreHeaderBB,
1209 BasicBlock *LoopLatchBB);
1210};
1211
1212/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1213/// indented and follows the dot format.
1214class VPlanPrinter {
1215 friend inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan);
1216 friend inline raw_ostream &operator<<(raw_ostream &OS,
1217 const struct VPlanIngredient &I);
1218
1219private:
1220 raw_ostream &OS;
1221 VPlan &Plan;
1222 unsigned Depth;
1223 unsigned TabWidth = 2;
1224 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001225 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001226 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1227
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001228 VPlanPrinter(raw_ostream &O, VPlan &P) : OS(O), Plan(P) {}
1229
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001230 /// Handle indentation.
1231 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1232
1233 /// Print a given \p Block of the Plan.
1234 void dumpBlock(const VPBlockBase *Block);
1235
1236 /// Print the information related to the CFG edges going out of a given
1237 /// \p Block, followed by printing the successor blocks themselves.
1238 void dumpEdges(const VPBlockBase *Block);
1239
1240 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1241 /// its successor blocks.
1242 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1243
1244 /// Print a given \p Region of the Plan.
1245 void dumpRegion(const VPRegionBlock *Region);
1246
1247 unsigned getOrCreateBID(const VPBlockBase *Block) {
1248 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1249 }
1250
1251 const Twine getOrCreateName(const VPBlockBase *Block);
1252
1253 const Twine getUID(const VPBlockBase *Block);
1254
1255 /// Print the information related to a CFG edge between two VPBlockBases.
1256 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1257 const Twine &Label);
1258
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001259 void dump();
1260
1261 static void printAsIngredient(raw_ostream &O, Value *V);
1262};
1263
1264struct VPlanIngredient {
1265 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001266
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001267 VPlanIngredient(Value *V) : V(V) {}
1268};
1269
1270inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1271 VPlanPrinter::printAsIngredient(OS, I.V);
1272 return OS;
1273}
1274
1275inline raw_ostream &operator<<(raw_ostream &OS, VPlan &Plan) {
1276 VPlanPrinter Printer(OS, Plan);
1277 Printer.dump();
1278 return OS;
1279}
1280
Diego Caballero2a34ac82018-07-30 21:33:31 +00001281//===----------------------------------------------------------------------===//
1282// GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs //
1283//===----------------------------------------------------------------------===//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001284
Diego Caballero2a34ac82018-07-30 21:33:31 +00001285// The following set of template specializations implement GraphTraits to treat
1286// any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1287// that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1288// VPBlockBase is a VPRegionBlock, this specialization provides access to its
1289// successors/predecessors but not to the blocks inside the region.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001290
1291template <> struct GraphTraits<VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001292 using NodeRef = VPBlockBase *;
1293 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001294
1295 static NodeRef getEntryNode(NodeRef N) { return N; }
1296
1297 static inline ChildIteratorType child_begin(NodeRef N) {
1298 return N->getSuccessors().begin();
1299 }
1300
1301 static inline ChildIteratorType child_end(NodeRef N) {
1302 return N->getSuccessors().end();
1303 }
1304};
1305
1306template <> struct GraphTraits<const VPBlockBase *> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001307 using NodeRef = const VPBlockBase *;
1308 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001309
1310 static NodeRef getEntryNode(NodeRef N) { return N; }
1311
1312 static inline ChildIteratorType child_begin(NodeRef N) {
1313 return N->getSuccessors().begin();
1314 }
1315
1316 static inline ChildIteratorType child_end(NodeRef N) {
1317 return N->getSuccessors().end();
1318 }
1319};
1320
Diego Caballero2a34ac82018-07-30 21:33:31 +00001321// Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1322// of successors for the inverse traversal.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001323template <> struct GraphTraits<Inverse<VPBlockBase *>> {
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001324 using NodeRef = VPBlockBase *;
1325 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001326
Diego Caballero2a34ac82018-07-30 21:33:31 +00001327 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001328
1329 static inline ChildIteratorType child_begin(NodeRef N) {
1330 return N->getPredecessors().begin();
1331 }
1332
1333 static inline ChildIteratorType child_end(NodeRef N) {
1334 return N->getPredecessors().end();
1335 }
1336};
1337
Diego Caballero2a34ac82018-07-30 21:33:31 +00001338// The following set of template specializations implement GraphTraits to
1339// treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1340// to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1341// (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1342// there won't be automatic recursion into other VPBlockBases that turn to be
1343// VPRegionBlocks.
1344
1345template <>
1346struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1347 using GraphRef = VPRegionBlock *;
1348 using nodes_iterator = df_iterator<NodeRef>;
1349
1350 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1351
1352 static nodes_iterator nodes_begin(GraphRef N) {
1353 return nodes_iterator::begin(N->getEntry());
1354 }
1355
1356 static nodes_iterator nodes_end(GraphRef N) {
1357 // df_iterator::end() returns an empty iterator so the node used doesn't
1358 // matter.
1359 return nodes_iterator::end(N);
1360 }
1361};
1362
1363template <>
1364struct GraphTraits<const VPRegionBlock *>
1365 : public GraphTraits<const VPBlockBase *> {
1366 using GraphRef = const VPRegionBlock *;
1367 using nodes_iterator = df_iterator<NodeRef>;
1368
1369 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1370
1371 static nodes_iterator nodes_begin(GraphRef N) {
1372 return nodes_iterator::begin(N->getEntry());
1373 }
1374
1375 static nodes_iterator nodes_end(GraphRef N) {
1376 // df_iterator::end() returns an empty iterator so the node used doesn't
1377 // matter.
1378 return nodes_iterator::end(N);
1379 }
1380};
1381
1382template <>
1383struct GraphTraits<Inverse<VPRegionBlock *>>
1384 : public GraphTraits<Inverse<VPBlockBase *>> {
1385 using GraphRef = VPRegionBlock *;
1386 using nodes_iterator = df_iterator<NodeRef>;
1387
1388 static NodeRef getEntryNode(Inverse<GraphRef> N) {
1389 return N.Graph->getExit();
1390 }
1391
1392 static nodes_iterator nodes_begin(GraphRef N) {
1393 return nodes_iterator::begin(N->getExit());
1394 }
1395
1396 static nodes_iterator nodes_end(GraphRef N) {
1397 // df_iterator::end() returns an empty iterator so the node used doesn't
1398 // matter.
1399 return nodes_iterator::end(N);
1400 }
1401};
1402
Diego Caballero168d04d2018-05-21 18:14:23 +00001403//===----------------------------------------------------------------------===//
1404// VPlan Utilities
1405//===----------------------------------------------------------------------===//
1406
1407/// Class that provides utilities for VPBlockBases in VPlan.
1408class VPBlockUtils {
1409public:
1410 VPBlockUtils() = delete;
1411
1412 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
Diego Caballerod0953012018-07-09 15:57:09 +00001413 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1414 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1415 /// has more than one successor, its conditional bit is propagated to \p
1416 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001417 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1418 assert(NewBlock->getSuccessors().empty() &&
1419 "Can't insert new block with successors.");
1420 // TODO: move successors from BlockPtr to NewBlock when this functionality
1421 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1422 // already has successors.
1423 BlockPtr->setOneSuccessor(NewBlock);
1424 NewBlock->setPredecessors({BlockPtr});
1425 NewBlock->setParent(BlockPtr->getParent());
1426 }
1427
1428 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1429 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1430 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
Diego Caballerod0953012018-07-09 15:57:09 +00001431 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1432 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1433 /// must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001434 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
Diego Caballerod0953012018-07-09 15:57:09 +00001435 VPValue *Condition, VPBlockBase *BlockPtr) {
Diego Caballero168d04d2018-05-21 18:14:23 +00001436 assert(IfTrue->getSuccessors().empty() &&
1437 "Can't insert IfTrue with successors.");
1438 assert(IfFalse->getSuccessors().empty() &&
1439 "Can't insert IfFalse with successors.");
Diego Caballerod0953012018-07-09 15:57:09 +00001440 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
Diego Caballero168d04d2018-05-21 18:14:23 +00001441 IfTrue->setPredecessors({BlockPtr});
1442 IfFalse->setPredecessors({BlockPtr});
1443 IfTrue->setParent(BlockPtr->getParent());
1444 IfFalse->setParent(BlockPtr->getParent());
1445 }
1446
1447 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1448 /// the successors of \p From and \p From to the predecessors of \p To. Both
1449 /// VPBlockBases must have the same parent, which can be null. Both
1450 /// VPBlockBases can be already connected to other VPBlockBases.
1451 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1452 assert((From->getParent() == To->getParent()) &&
1453 "Can't connect two block with different parents");
1454 assert(From->getNumSuccessors() < 2 &&
1455 "Blocks can't have more than two successors.");
1456 From->appendSuccessor(To);
1457 To->appendPredecessor(From);
1458 }
1459
1460 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1461 /// from the successors of \p From and \p From from the predecessors of \p To.
1462 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1463 assert(To && "Successor to disconnect is null.");
1464 From->removeSuccessor(To);
1465 To->removePredecessor(From);
1466 }
1467};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001468
Florian Hahna4dc7fe2018-11-13 15:58:18 +00001469class VPInterleavedAccessInfo {
1470private:
1471 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1472 InterleaveGroupMap;
1473
1474 /// Type for mapping of instruction based interleave groups to VPInstruction
1475 /// interleave groups
1476 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1477 InterleaveGroup<VPInstruction> *>;
1478
1479 /// Recursively \p Region and populate VPlan based interleave groups based on
1480 /// \p IAI.
1481 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1482 InterleavedAccessInfo &IAI);
1483 /// Recursively traverse \p Block and populate VPlan based interleave groups
1484 /// based on \p IAI.
1485 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1486 InterleavedAccessInfo &IAI);
1487
1488public:
1489 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1490
1491 ~VPInterleavedAccessInfo() {
1492 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1493 // Avoid releasing a pointer twice.
1494 for (auto &I : InterleaveGroupMap)
1495 DelSet.insert(I.second);
1496 for (auto *Ptr : DelSet)
1497 delete Ptr;
1498 }
1499
1500 /// Get the interleave group that \p Instr belongs to.
1501 ///
1502 /// \returns nullptr if doesn't have such group.
1503 InterleaveGroup<VPInstruction> *
1504 getInterleaveGroup(VPInstruction *Instr) const {
1505 if (InterleaveGroupMap.count(Instr))
1506 return InterleaveGroupMap.find(Instr)->second;
1507 return nullptr;
1508 }
1509};
1510
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001511} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001512
1513#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H