blob: a1c10f07e84c5815c65a04b99dae3ff58486c51a [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ayal Zaks1f58dda2017-08-27 12:55:46 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko6cadde72017-10-17 21:27:42 +00008//
Ayal Zaks1f58dda2017-08-27 12:55:46 +00009/// \file
10/// This file contains the declarations of the Vectorization Plan base classes:
11/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12/// VPBlockBase, together implementing a Hierarchical CFG;
13/// 2. Specializations of GraphTraits that allow VPBlockBase graphs to be
14/// treated as proper graphs for generic algorithms;
15/// 3. Pure virtual VPRecipeBase serving as the base class for recipes contained
16/// within VPBasicBlocks;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000017/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18/// instruction;
19/// 5. The VPlan class holding a candidate for vectorization;
20/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000021/// These are documented in docs/VectorizationPlan.rst.
Eugene Zelenko6cadde72017-10-17 21:27:42 +000022//
Ayal Zaks1f58dda2017-08-27 12:55:46 +000023//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27
Diego Caballero35871502018-07-31 01:57:29 +000028#include "VPlanLoopInfo.h"
Gil Rapaport8b9d1f32017-11-20 12:01:47 +000029#include "VPlanValue.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000030#include "llvm/ADT/DenseMap.h"
Diego Caballero2a34ac82018-07-30 21:33:31 +000031#include "llvm/ADT/DepthFirstIterator.h"
Ayal Zaks1f58dda2017-08-27 12:55:46 +000032#include "llvm/ADT/GraphTraits.h"
Eugene Zelenko6cadde72017-10-17 21:27:42 +000033#include "llvm/ADT/Optional.h"
Gil Rapaport39ccc092019-10-16 21:39:53 +030034#include "llvm/ADT/SmallBitVector.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;
Florian Hahn09e516c2018-11-14 13:11:49 +000063class VPlanSlp;
Florian Hahn45e5d5b2018-06-08 17:30:45 +000064
65/// A range of powers-of-2 vectorization factors with fixed start and
66/// adjustable end. The range includes start and excludes end, e.g.,:
67/// [1, 9) = {1, 2, 4, 8}
68struct VFRange {
69 // A power of 2.
70 const unsigned Start;
71
72 // Need not be a power of 2. If End <= Start range is empty.
73 unsigned End;
74};
75
76using VPlanPtr = std::unique_ptr<VPlan>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000077
78/// In what follows, the term "input IR" refers to code that is fed into the
79/// vectorizer whereas the term "output IR" refers to code that is generated by
80/// the vectorizer.
81
82/// VPIteration represents a single point in the iteration space of the output
83/// (vectorized and/or unrolled) IR loop.
84struct VPIteration {
Eugene Zelenko6cadde72017-10-17 21:27:42 +000085 /// in [0..UF)
86 unsigned Part;
87
88 /// in [0..VF)
89 unsigned Lane;
Ayal Zaks1f58dda2017-08-27 12:55:46 +000090};
91
92/// This is a helper struct for maintaining vectorization state. It's used for
93/// mapping values from the original loop to their corresponding values in
94/// the new loop. Two mappings are maintained: one for vectorized values and
95/// one for scalarized values. Vectorized values are represented with UF
96/// vector values in the new loop, and scalarized values are represented with
97/// UF x VF scalar values in the new loop. UF and VF are the unroll and
98/// vectorization factors, respectively.
99///
100/// Entries can be added to either map with setVectorValue and setScalarValue,
101/// which assert that an entry was not already added before. If an entry is to
102/// replace an existing one, call resetVectorValue and resetScalarValue. This is
103/// currently needed to modify the mapped values during "fix-up" operations that
104/// occur once the first phase of widening is complete. These operations include
105/// type truncation and the second phase of recurrence widening.
106///
107/// Entries from either map can be retrieved using the getVectorValue and
108/// getScalarValue functions, which assert that the desired value exists.
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000109struct VectorizerValueMap {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000110 friend struct VPTransformState;
111
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000112private:
113 /// The unroll factor. Each entry in the vector map contains UF vector values.
114 unsigned UF;
115
116 /// The vectorization factor. Each entry in the scalar map contains UF x VF
117 /// scalar values.
118 unsigned VF;
119
120 /// The vector and scalar map storage. We use std::map and not DenseMap
121 /// because insertions to DenseMap invalidate its iterators.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000122 using VectorParts = SmallVector<Value *, 2>;
123 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000124 std::map<Value *, VectorParts> VectorMapStorage;
125 std::map<Value *, ScalarParts> ScalarMapStorage;
126
127public:
128 /// Construct an empty map with the given unroll and vectorization factors.
129 VectorizerValueMap(unsigned UF, unsigned VF) : UF(UF), VF(VF) {}
130
131 /// \return True if the map has any vector entry for \p Key.
132 bool hasAnyVectorValue(Value *Key) const {
133 return VectorMapStorage.count(Key);
134 }
135
136 /// \return True if the map has a vector entry for \p Key and \p Part.
137 bool hasVectorValue(Value *Key, unsigned Part) const {
138 assert(Part < UF && "Queried Vector Part is too large.");
139 if (!hasAnyVectorValue(Key))
140 return false;
141 const VectorParts &Entry = VectorMapStorage.find(Key)->second;
142 assert(Entry.size() == UF && "VectorParts has wrong dimensions.");
143 return Entry[Part] != nullptr;
144 }
145
146 /// \return True if the map has any scalar entry for \p Key.
147 bool hasAnyScalarValue(Value *Key) const {
148 return ScalarMapStorage.count(Key);
149 }
150
151 /// \return True if the map has a scalar entry for \p Key and \p Instance.
152 bool hasScalarValue(Value *Key, const VPIteration &Instance) const {
153 assert(Instance.Part < UF && "Queried Scalar Part is too large.");
154 assert(Instance.Lane < VF && "Queried Scalar Lane is too large.");
155 if (!hasAnyScalarValue(Key))
156 return false;
157 const ScalarParts &Entry = ScalarMapStorage.find(Key)->second;
158 assert(Entry.size() == UF && "ScalarParts has wrong dimensions.");
159 assert(Entry[Instance.Part].size() == VF &&
160 "ScalarParts has wrong dimensions.");
161 return Entry[Instance.Part][Instance.Lane] != nullptr;
162 }
163
164 /// Retrieve the existing vector value that corresponds to \p Key and
165 /// \p Part.
166 Value *getVectorValue(Value *Key, unsigned Part) {
167 assert(hasVectorValue(Key, Part) && "Getting non-existent value.");
168 return VectorMapStorage[Key][Part];
169 }
170
171 /// Retrieve the existing scalar value that corresponds to \p Key and
172 /// \p Instance.
173 Value *getScalarValue(Value *Key, const VPIteration &Instance) {
174 assert(hasScalarValue(Key, Instance) && "Getting non-existent value.");
175 return ScalarMapStorage[Key][Instance.Part][Instance.Lane];
176 }
177
178 /// Set a vector value associated with \p Key and \p Part. Assumes such a
179 /// value is not already set. If it is, use resetVectorValue() instead.
180 void setVectorValue(Value *Key, unsigned Part, Value *Vector) {
181 assert(!hasVectorValue(Key, Part) && "Vector value already set for part");
182 if (!VectorMapStorage.count(Key)) {
183 VectorParts Entry(UF);
184 VectorMapStorage[Key] = Entry;
185 }
186 VectorMapStorage[Key][Part] = Vector;
187 }
188
189 /// Set a scalar value associated with \p Key and \p Instance. Assumes such a
190 /// value is not already set.
191 void setScalarValue(Value *Key, const VPIteration &Instance, Value *Scalar) {
192 assert(!hasScalarValue(Key, Instance) && "Scalar value already set");
193 if (!ScalarMapStorage.count(Key)) {
194 ScalarParts Entry(UF);
195 // TODO: Consider storing uniform values only per-part, as they occupy
196 // lane 0 only, keeping the other VF-1 redundant entries null.
197 for (unsigned Part = 0; Part < UF; ++Part)
198 Entry[Part].resize(VF, nullptr);
199 ScalarMapStorage[Key] = Entry;
200 }
201 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
202 }
203
204 /// Reset the vector value associated with \p Key for the given \p Part.
205 /// This function can be used to update values that have already been
206 /// vectorized. This is the case for "fix-up" operations including type
207 /// truncation and the second phase of recurrence vectorization.
208 void resetVectorValue(Value *Key, unsigned Part, Value *Vector) {
209 assert(hasVectorValue(Key, Part) && "Vector value not set for part");
210 VectorMapStorage[Key][Part] = Vector;
211 }
212
213 /// Reset the scalar value associated with \p Key for \p Part and \p Lane.
214 /// This function can be used to update values that have already been
215 /// scalarized. This is the case for "fix-up" operations including scalar phi
216 /// nodes for scalarized and predicated instructions.
217 void resetScalarValue(Value *Key, const VPIteration &Instance,
218 Value *Scalar) {
219 assert(hasScalarValue(Key, Instance) &&
220 "Scalar value not set for part and lane");
221 ScalarMapStorage[Key][Instance.Part][Instance.Lane] = Scalar;
222 }
223};
224
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000225/// This class is used to enable the VPlan to invoke a method of ILV. This is
226/// needed until the method is refactored out of ILV and becomes reusable.
227struct VPCallback {
228 virtual ~VPCallback() {}
229 virtual Value *getOrCreateVectorValues(Value *V, unsigned Part) = 0;
230};
231
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000232/// VPTransformState holds information passed down when "executing" a VPlan,
233/// needed for generating the output IR.
234struct VPTransformState {
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000235 VPTransformState(unsigned VF, unsigned UF, LoopInfo *LI, DominatorTree *DT,
236 IRBuilder<> &Builder, VectorizerValueMap &ValueMap,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000237 InnerLoopVectorizer *ILV, VPCallback &Callback)
238 : VF(VF), UF(UF), Instance(), LI(LI), DT(DT), Builder(Builder),
239 ValueMap(ValueMap), ILV(ILV), Callback(Callback) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000240
241 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
242 unsigned VF;
243 unsigned UF;
244
245 /// Hold the indices to generate specific scalar instructions. Null indicates
246 /// that all instances are to be generated, using either scalar or vector
247 /// instructions.
248 Optional<VPIteration> Instance;
249
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000250 struct DataState {
251 /// A type for vectorized values in the new loop. Each value from the
252 /// original loop, when vectorized, is represented by UF vector values in
253 /// the new unrolled loop, where UF is the unroll factor.
254 typedef SmallVector<Value *, 2> PerPartValuesTy;
255
256 DenseMap<VPValue *, PerPartValuesTy> PerPartOutput;
257 } Data;
258
259 /// Get the generated Value for a given VPValue and a given Part. Note that
260 /// as some Defs are still created by ILV and managed in its ValueMap, this
261 /// method will delegate the call to ILV in such cases in order to provide
262 /// callers a consistent API.
263 /// \see set.
264 Value *get(VPValue *Def, unsigned Part) {
265 // If Values have been set for this Def return the one relevant for \p Part.
266 if (Data.PerPartOutput.count(Def))
267 return Data.PerPartOutput[Def][Part];
268 // Def is managed by ILV: bring the Values from ValueMap.
269 return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
270 }
271
272 /// Set the generated Value for a given VPValue and a given Part.
273 void set(VPValue *Def, Value *V, unsigned Part) {
274 if (!Data.PerPartOutput.count(Def)) {
275 DataState::PerPartValuesTy Entry(UF);
276 Data.PerPartOutput[Def] = Entry;
277 }
278 Data.PerPartOutput[Def][Part] = V;
279 }
280
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000281 /// Hold state information used when constructing the CFG of the output IR,
282 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
283 struct CFGState {
284 /// The previous VPBasicBlock visited. Initially set to null.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000285 VPBasicBlock *PrevVPBB = nullptr;
286
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000287 /// The previous IR BasicBlock created or used. Initially set to the new
288 /// header BasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000289 BasicBlock *PrevBB = nullptr;
290
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000291 /// The last IR BasicBlock in the output IR. Set to the new latch
292 /// BasicBlock, used for placing the newly created BasicBlocks.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000293 BasicBlock *LastBB = nullptr;
294
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000295 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
296 /// of replication, maps the BasicBlock of the last replica created.
297 SmallDenseMap<VPBasicBlock *, BasicBlock *> VPBB2IRBB;
298
Hideki Saitoea7f3032018-09-14 00:36:00 +0000299 /// Vector of VPBasicBlocks whose terminator instruction needs to be fixed
300 /// up at the end of vector code generation.
301 SmallVector<VPBasicBlock *, 8> VPBBsToFix;
302
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000303 CFGState() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000304 } CFG;
305
306 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000307 LoopInfo *LI;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000308
309 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000310 DominatorTree *DT;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000311
312 /// Hold a reference to the IRBuilder used to generate output IR code.
313 IRBuilder<> &Builder;
314
315 /// Hold a reference to the Value state information used when generating the
316 /// Values of the output IR.
317 VectorizerValueMap &ValueMap;
318
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000319 /// Hold a reference to a mapping between VPValues in VPlan and original
320 /// Values they correspond to.
321 VPValue2ValueTy VPValue2Value;
322
Ayal Zaksb0b53122018-10-18 15:03:15 +0000323 /// Hold the trip count of the scalar loop.
324 Value *TripCount = nullptr;
325
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000326 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000327 InnerLoopVectorizer *ILV;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000328
329 VPCallback &Callback;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000330};
331
332/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
333/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
334class VPBlockBase {
Diego Caballero168d04d2018-05-21 18:14:23 +0000335 friend class VPBlockUtils;
336
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000337private:
338 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
339
340 /// An optional name for the block.
341 std::string Name;
342
343 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
344 /// it is a topmost VPBlockBase.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000345 VPRegionBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000346
347 /// List of predecessor blocks.
348 SmallVector<VPBlockBase *, 1> Predecessors;
349
350 /// List of successor blocks.
351 SmallVector<VPBlockBase *, 1> Successors;
352
Diego Caballerod0953012018-07-09 15:57:09 +0000353 /// Successor selector, null for zero or single successor blocks.
354 VPValue *CondBit = nullptr;
355
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000356 /// Current block predicate - null if the block does not need a predicate.
357 VPValue *Predicate = nullptr;
358
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000359 /// Add \p Successor as the last successor to this block.
360 void appendSuccessor(VPBlockBase *Successor) {
361 assert(Successor && "Cannot add nullptr successor!");
362 Successors.push_back(Successor);
363 }
364
365 /// Add \p Predecessor as the last predecessor to this block.
366 void appendPredecessor(VPBlockBase *Predecessor) {
367 assert(Predecessor && "Cannot add nullptr predecessor!");
368 Predecessors.push_back(Predecessor);
369 }
370
371 /// Remove \p Predecessor from the predecessors of this block.
372 void removePredecessor(VPBlockBase *Predecessor) {
373 auto Pos = std::find(Predecessors.begin(), Predecessors.end(), Predecessor);
374 assert(Pos && "Predecessor does not exist");
375 Predecessors.erase(Pos);
376 }
377
378 /// Remove \p Successor from the successors of this block.
379 void removeSuccessor(VPBlockBase *Successor) {
380 auto Pos = std::find(Successors.begin(), Successors.end(), Successor);
381 assert(Pos && "Successor does not exist");
382 Successors.erase(Pos);
383 }
384
385protected:
386 VPBlockBase(const unsigned char SC, const std::string &N)
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000387 : SubclassID(SC), Name(N) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000388
389public:
390 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
391 /// that are actually instantiated. Values of this enumeration are kept in the
392 /// SubclassID field of the VPBlockBase objects. They are used for concrete
393 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000394 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000395
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000396 using VPBlocksTy = SmallVectorImpl<VPBlockBase *>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000397
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000398 virtual ~VPBlockBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000399
400 const std::string &getName() const { return Name; }
401
402 void setName(const Twine &newName) { Name = newName.str(); }
403
404 /// \return an ID for the concrete type of this object.
405 /// This is used to implement the classof checks. This should not be used
406 /// for any other purpose, as the values may change as LLVM evolves.
407 unsigned getVPBlockID() const { return SubclassID; }
408
Diego Caballero168d04d2018-05-21 18:14:23 +0000409 VPRegionBlock *getParent() { return Parent; }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000410 const VPRegionBlock *getParent() const { return Parent; }
411
412 void setParent(VPRegionBlock *P) { Parent = P; }
413
414 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
415 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
416 /// VPBlockBase is a VPBasicBlock, it is returned.
417 const VPBasicBlock *getEntryBasicBlock() const;
418 VPBasicBlock *getEntryBasicBlock();
419
420 /// \return the VPBasicBlock that is the exit of this VPBlockBase,
421 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
422 /// VPBlockBase is a VPBasicBlock, it is returned.
423 const VPBasicBlock *getExitBasicBlock() const;
424 VPBasicBlock *getExitBasicBlock();
425
426 const VPBlocksTy &getSuccessors() const { return Successors; }
427 VPBlocksTy &getSuccessors() { return Successors; }
428
429 const VPBlocksTy &getPredecessors() const { return Predecessors; }
430 VPBlocksTy &getPredecessors() { return Predecessors; }
431
432 /// \return the successor of this VPBlockBase if it has a single successor.
433 /// Otherwise return a null pointer.
434 VPBlockBase *getSingleSuccessor() const {
435 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
436 }
437
438 /// \return the predecessor of this VPBlockBase if it has a single
439 /// predecessor. Otherwise return a null pointer.
440 VPBlockBase *getSinglePredecessor() const {
441 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
442 }
443
Diego Caballero168d04d2018-05-21 18:14:23 +0000444 size_t getNumSuccessors() const { return Successors.size(); }
445 size_t getNumPredecessors() const { return Predecessors.size(); }
446
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000447 /// An Enclosing Block of a block B is any block containing B, including B
448 /// itself. \return the closest enclosing block starting from "this", which
449 /// has successors. \return the root enclosing block if all enclosing blocks
450 /// have no successors.
451 VPBlockBase *getEnclosingBlockWithSuccessors();
452
453 /// \return the closest enclosing block starting from "this", which has
454 /// predecessors. \return the root enclosing block if all enclosing blocks
455 /// have no predecessors.
456 VPBlockBase *getEnclosingBlockWithPredecessors();
457
458 /// \return the successors either attached directly to this VPBlockBase or, if
459 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
460 /// successors of its own, search recursively for the first enclosing
461 /// VPRegionBlock that has successors and return them. If no such
462 /// VPRegionBlock exists, return the (empty) successors of the topmost
463 /// VPBlockBase reached.
464 const VPBlocksTy &getHierarchicalSuccessors() {
465 return getEnclosingBlockWithSuccessors()->getSuccessors();
466 }
467
468 /// \return the hierarchical successor of this VPBlockBase if it has a single
469 /// hierarchical successor. Otherwise return a null pointer.
470 VPBlockBase *getSingleHierarchicalSuccessor() {
471 return getEnclosingBlockWithSuccessors()->getSingleSuccessor();
472 }
473
474 /// \return the predecessors either attached directly to this VPBlockBase or,
475 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
476 /// predecessors of its own, search recursively for the first enclosing
477 /// VPRegionBlock that has predecessors and return them. If no such
478 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
479 /// VPBlockBase reached.
480 const VPBlocksTy &getHierarchicalPredecessors() {
481 return getEnclosingBlockWithPredecessors()->getPredecessors();
482 }
483
484 /// \return the hierarchical predecessor of this VPBlockBase if it has a
485 /// single hierarchical predecessor. Otherwise return a null pointer.
486 VPBlockBase *getSingleHierarchicalPredecessor() {
487 return getEnclosingBlockWithPredecessors()->getSinglePredecessor();
488 }
489
Diego Caballerod0953012018-07-09 15:57:09 +0000490 /// \return the condition bit selecting the successor.
491 VPValue *getCondBit() { return CondBit; }
492
493 const VPValue *getCondBit() const { return CondBit; }
494
495 void setCondBit(VPValue *CV) { CondBit = CV; }
496
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000497 VPValue *getPredicate() { return Predicate; }
498
499 const VPValue *getPredicate() const { return Predicate; }
500
501 void setPredicate(VPValue *Pred) { Predicate = Pred; }
502
Diego Caballero168d04d2018-05-21 18:14:23 +0000503 /// Set a given VPBlockBase \p Successor as the single successor of this
504 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
505 /// This VPBlockBase must have no successors.
506 void setOneSuccessor(VPBlockBase *Successor) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000507 assert(Successors.empty() && "Setting one successor when others exist.");
508 appendSuccessor(Successor);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000509 }
510
Diego Caballero168d04d2018-05-21 18:14:23 +0000511 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
Diego Caballerod0953012018-07-09 15:57:09 +0000512 /// successors of this VPBlockBase. \p Condition is set as the successor
513 /// selector. This VPBlockBase is not added as predecessor of \p IfTrue or \p
514 /// IfFalse. This VPBlockBase must have no successors.
515 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
516 VPValue *Condition) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000517 assert(Successors.empty() && "Setting two successors when others exist.");
Diego Caballerod0953012018-07-09 15:57:09 +0000518 assert(Condition && "Setting two successors without condition!");
519 CondBit = Condition;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000520 appendSuccessor(IfTrue);
521 appendSuccessor(IfFalse);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000522 }
523
Diego Caballero168d04d2018-05-21 18:14:23 +0000524 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
525 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
526 /// as successor of any VPBasicBlock in \p NewPreds.
527 void setPredecessors(ArrayRef<VPBlockBase *> NewPreds) {
528 assert(Predecessors.empty() && "Block predecessors already set.");
529 for (auto *Pred : NewPreds)
530 appendPredecessor(Pred);
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000531 }
532
Hideki Saito4e4ecae2019-01-23 22:43:12 +0000533 /// Remove all the predecessor of this block.
534 void clearPredecessors() { Predecessors.clear(); }
535
536 /// Remove all the successors of this block and set to null its condition bit
537 void clearSuccessors() {
538 Successors.clear();
539 CondBit = nullptr;
540 }
541
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000542 /// The method which generates the output IR that correspond to this
543 /// VPBlockBase, thereby "executing" the VPlan.
544 virtual void execute(struct VPTransformState *State) = 0;
545
546 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
547 static void deleteCFG(VPBlockBase *Entry);
Diego Caballero2a34ac82018-07-30 21:33:31 +0000548
549 void printAsOperand(raw_ostream &OS, bool PrintType) const {
550 OS << getName();
551 }
552
553 void print(raw_ostream &OS) const {
554 // TODO: Only printing VPBB name for now since we only have dot printing
555 // support for VPInstructions/Recipes.
556 printAsOperand(OS, false);
557 }
Diego Caballero35871502018-07-31 01:57:29 +0000558
559 /// Return true if it is legal to hoist instructions into this block.
560 bool isLegalToHoistInto() {
561 // There are currently no constraints that prevent an instruction to be
562 // hoisted into a VPBlockBase.
563 return true;
564 }
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000565};
566
567/// VPRecipeBase is a base class modeling a sequence of one or more output IR
568/// instructions.
569class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock> {
570 friend VPBasicBlock;
Gil Rapaport7f152542019-10-07 17:24:33 +0300571 friend class VPBlockUtils;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000572
573private:
574 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
575
576 /// Each VPRecipe belongs to a single VPBasicBlock.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000577 VPBasicBlock *Parent = nullptr;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000578
579public:
580 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
581 /// that is actually instantiated. Values of this enumeration are kept in the
582 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
583 /// type identification.
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000584 using VPRecipeTy = enum {
Gil Rapaport848581c2017-11-14 12:09:30 +0000585 VPBlendSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000586 VPBranchOnMaskSC,
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000587 VPInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000588 VPInterleaveSC,
589 VPPredInstPHISC,
590 VPReplicateSC,
Gil Rapaport39ccc092019-10-16 21:39:53 +0300591 VPWidenGEPSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000592 VPWidenIntOrFpInductionSC,
Gil Rapaport848581c2017-11-14 12:09:30 +0000593 VPWidenMemoryInstructionSC,
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000594 VPWidenPHISC,
595 VPWidenSC,
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000596 };
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000597
Eugene Zelenko6cadde72017-10-17 21:27:42 +0000598 VPRecipeBase(const unsigned char SC) : SubclassID(SC) {}
599 virtual ~VPRecipeBase() = default;
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000600
601 /// \return an ID for the concrete type of this object.
602 /// This is used to implement the classof checks. This should not be used
603 /// for any other purpose, as the values may change as LLVM evolves.
604 unsigned getVPRecipeID() const { return SubclassID; }
605
606 /// \return the VPBasicBlock which this VPRecipe belongs to.
607 VPBasicBlock *getParent() { return Parent; }
608 const VPBasicBlock *getParent() const { return Parent; }
609
610 /// The method which generates the output IR instructions that correspond to
611 /// this VPRecipe, thereby "executing" the VPlan.
612 virtual void execute(struct VPTransformState &State) = 0;
613
614 /// Each recipe prints itself.
615 virtual void print(raw_ostream &O, const Twine &Indent) const = 0;
Florian Hahn7591e4e2018-06-18 11:34:17 +0000616
617 /// Insert an unlinked recipe into a basic block immediately before
618 /// the specified recipe.
619 void insertBefore(VPRecipeBase *InsertPos);
Florian Hahn63cbcf92018-06-18 15:18:48 +0000620
Gil Rapaport7f152542019-10-07 17:24:33 +0300621 /// Insert an unlinked Recipe into a basic block immediately after
622 /// the specified Recipe.
623 void insertAfter(VPRecipeBase *InsertPos);
624
Florian Hahn39d4c9f2019-10-11 15:36:55 +0000625 /// Unlink this recipe from its current VPBasicBlock and insert it into
626 /// the VPBasicBlock that MovePos lives in, right after MovePos.
627 void moveAfter(VPRecipeBase *MovePos);
628
Gil Rapaport7f152542019-10-07 17:24:33 +0300629 /// This method unlinks 'this' from the containing basic block, but does not
630 /// delete it.
631 void removeFromParent();
632
Florian Hahn63cbcf92018-06-18 15:18:48 +0000633 /// This method unlinks 'this' from the containing basic block and deletes it.
634 ///
635 /// \returns an iterator pointing to the element after the erased one
636 iplist<VPRecipeBase>::iterator eraseFromParent();
Ayal Zaks1f58dda2017-08-27 12:55:46 +0000637};
638
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000639/// This is a concrete Recipe that models a single VPlan-level instruction.
640/// While as any Recipe it may generate a sequence of IR instructions when
641/// executed, these instructions would always form a single-def expression as
642/// the VPInstruction is also a single def-use vertex.
643class VPInstruction : public VPUser, public VPRecipeBase {
Florian Hahn3385caa2018-06-18 18:28:49 +0000644 friend class VPlanHCFGTransforms;
Florian Hahn09e516c2018-11-14 13:11:49 +0000645 friend class VPlanSlp;
Florian Hahn3385caa2018-06-18 18:28:49 +0000646
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000647public:
648 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
Florian Hahn09e516c2018-11-14 13:11:49 +0000649 enum {
650 Not = Instruction::OtherOpsEnd + 1,
651 ICmpULE,
652 SLPLoad,
653 SLPStore,
654 };
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000655
656private:
657 typedef unsigned char OpcodeTy;
658 OpcodeTy Opcode;
659
660 /// Utility method serving execute(): generates a single instance of the
661 /// modeled instruction.
662 void generateInstruction(VPTransformState &State, unsigned Part);
663
Florian Hahn09e516c2018-11-14 13:11:49 +0000664protected:
665 Instruction *getUnderlyingInstr() {
666 return cast_or_null<Instruction>(getUnderlyingValue());
667 }
668
669 void setUnderlyingInstr(Instruction *I) { setUnderlyingValue(I); }
670
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000671public:
Diego Caballero168d04d2018-05-21 18:14:23 +0000672 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands)
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000673 : VPUser(VPValue::VPInstructionSC, Operands),
674 VPRecipeBase(VPRecipeBase::VPInstructionSC), Opcode(Opcode) {}
675
Diego Caballero168d04d2018-05-21 18:14:23 +0000676 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands)
677 : VPInstruction(Opcode, ArrayRef<VPValue *>(Operands)) {}
678
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000679 /// Method to support type inquiry through isa, cast, and dyn_cast.
680 static inline bool classof(const VPValue *V) {
681 return V->getVPValueID() == VPValue::VPInstructionSC;
682 }
683
Florian Hahn09e516c2018-11-14 13:11:49 +0000684 VPInstruction *clone() const {
685 SmallVector<VPValue *, 2> Operands(operands());
686 return new VPInstruction(Opcode, Operands);
687 }
688
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000689 /// Method to support type inquiry through isa, cast, and dyn_cast.
690 static inline bool classof(const VPRecipeBase *R) {
691 return R->getVPRecipeID() == VPRecipeBase::VPInstructionSC;
692 }
693
694 unsigned getOpcode() const { return Opcode; }
695
696 /// Generate the instruction.
697 /// TODO: We currently execute only per-part unless a specific instance is
698 /// provided.
699 void execute(VPTransformState &State) override;
700
701 /// Print the Recipe.
702 void print(raw_ostream &O, const Twine &Indent) const override;
703
704 /// Print the VPInstruction.
705 void print(raw_ostream &O) const;
Florian Hahn09e516c2018-11-14 13:11:49 +0000706
707 /// Return true if this instruction may modify memory.
708 bool mayWriteToMemory() const {
709 // TODO: we can use attributes of the called function to rule out memory
710 // modifications.
711 return Opcode == Instruction::Store || Opcode == Instruction::Call ||
712 Opcode == Instruction::Invoke || Opcode == SLPStore;
713 }
Gil Rapaport8b9d1f32017-11-20 12:01:47 +0000714};
715
Hal Finkel7333aa92017-12-16 01:12:50 +0000716/// VPWidenRecipe is a recipe for producing a copy of vector type for each
717/// Instruction in its ingredients independently, in order. This recipe covers
718/// most of the traditional vectorization cases where each ingredient transforms
719/// into a vectorized version of itself.
720class VPWidenRecipe : public VPRecipeBase {
721private:
722 /// Hold the ingredients by pointing to their original BasicBlock location.
723 BasicBlock::iterator Begin;
724 BasicBlock::iterator End;
725
726public:
727 VPWidenRecipe(Instruction *I) : VPRecipeBase(VPWidenSC) {
728 End = I->getIterator();
729 Begin = End++;
730 }
731
732 ~VPWidenRecipe() override = default;
733
734 /// Method to support type inquiry through isa, cast, and dyn_cast.
735 static inline bool classof(const VPRecipeBase *V) {
736 return V->getVPRecipeID() == VPRecipeBase::VPWidenSC;
737 }
738
739 /// Produce widened copies of all Ingredients.
740 void execute(VPTransformState &State) override;
741
742 /// Augment the recipe to include Instr, if it lies at its End.
743 bool appendInstruction(Instruction *Instr) {
744 if (End != Instr->getIterator())
745 return false;
746 End++;
747 return true;
748 }
749
750 /// Print the recipe.
751 void print(raw_ostream &O, const Twine &Indent) const override;
752};
753
Gil Rapaport39ccc092019-10-16 21:39:53 +0300754/// A recipe for handling GEP instructions.
755class VPWidenGEPRecipe : public VPRecipeBase {
756private:
757 GetElementPtrInst *GEP;
758 bool IsPtrLoopInvariant;
759 SmallBitVector IsIndexLoopInvariant;
760
761public:
762 VPWidenGEPRecipe(GetElementPtrInst *GEP, Loop *OrigLoop)
763 : VPRecipeBase(VPWidenGEPSC), GEP(GEP),
764 IsIndexLoopInvariant(GEP->getNumIndices(), false) {
765 IsPtrLoopInvariant = OrigLoop->isLoopInvariant(GEP->getPointerOperand());
766 for (auto Index : enumerate(GEP->indices()))
767 IsIndexLoopInvariant[Index.index()] =
768 OrigLoop->isLoopInvariant(Index.value().get());
769 }
770 ~VPWidenGEPRecipe() override = default;
771
772 /// Method to support type inquiry through isa, cast, and dyn_cast.
773 static inline bool classof(const VPRecipeBase *V) {
774 return V->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC;
775 }
776
777 /// Generate the gep nodes.
778 void execute(VPTransformState &State) override;
779
780 /// Print the recipe.
781 void print(raw_ostream &O, const Twine &Indent) const override;
782};
783
Hal Finkel7333aa92017-12-16 01:12:50 +0000784/// A recipe for handling phi nodes of integer and floating-point inductions,
785/// producing their vector and scalar values.
786class VPWidenIntOrFpInductionRecipe : public VPRecipeBase {
787private:
788 PHINode *IV;
789 TruncInst *Trunc;
790
791public:
792 VPWidenIntOrFpInductionRecipe(PHINode *IV, TruncInst *Trunc = nullptr)
793 : VPRecipeBase(VPWidenIntOrFpInductionSC), IV(IV), Trunc(Trunc) {}
794 ~VPWidenIntOrFpInductionRecipe() override = default;
795
796 /// Method to support type inquiry through isa, cast, and dyn_cast.
797 static inline bool classof(const VPRecipeBase *V) {
798 return V->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC;
799 }
800
801 /// Generate the vectorized and scalarized versions of the phi node as
802 /// needed by their users.
803 void execute(VPTransformState &State) override;
804
805 /// Print the recipe.
806 void print(raw_ostream &O, const Twine &Indent) const override;
807};
808
809/// A recipe for handling all phi nodes except for integer and FP inductions.
810class VPWidenPHIRecipe : public VPRecipeBase {
811private:
812 PHINode *Phi;
813
814public:
815 VPWidenPHIRecipe(PHINode *Phi) : VPRecipeBase(VPWidenPHISC), Phi(Phi) {}
816 ~VPWidenPHIRecipe() override = default;
817
818 /// Method to support type inquiry through isa, cast, and dyn_cast.
819 static inline bool classof(const VPRecipeBase *V) {
820 return V->getVPRecipeID() == VPRecipeBase::VPWidenPHISC;
821 }
822
823 /// Generate the phi/select nodes.
824 void execute(VPTransformState &State) override;
825
826 /// Print the recipe.
827 void print(raw_ostream &O, const Twine &Indent) const override;
828};
829
830/// A recipe for vectorizing a phi-node as a sequence of mask-based select
831/// instructions.
832class VPBlendRecipe : public VPRecipeBase {
833private:
834 PHINode *Phi;
835
836 /// The blend operation is a User of a mask, if not null.
837 std::unique_ptr<VPUser> User;
838
839public:
840 VPBlendRecipe(PHINode *Phi, ArrayRef<VPValue *> Masks)
841 : VPRecipeBase(VPBlendSC), Phi(Phi) {
842 assert((Phi->getNumIncomingValues() == 1 ||
843 Phi->getNumIncomingValues() == Masks.size()) &&
844 "Expected the same number of incoming values and masks");
845 if (!Masks.empty())
846 User.reset(new VPUser(Masks));
847 }
848
849 /// Method to support type inquiry through isa, cast, and dyn_cast.
850 static inline bool classof(const VPRecipeBase *V) {
851 return V->getVPRecipeID() == VPRecipeBase::VPBlendSC;
852 }
853
854 /// Generate the phi/select nodes.
855 void execute(VPTransformState &State) override;
856
857 /// Print the recipe.
858 void print(raw_ostream &O, const Twine &Indent) const override;
859};
860
861/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
862/// or stores into one wide load/store and shuffles.
863class VPInterleaveRecipe : public VPRecipeBase {
864private:
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000865 const InterleaveGroup<Instruction> *IG;
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000866 std::unique_ptr<VPUser> User;
Hal Finkel7333aa92017-12-16 01:12:50 +0000867
868public:
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000869 VPInterleaveRecipe(const InterleaveGroup<Instruction> *IG, VPValue *Mask)
Dorit Nuzman38bbf812018-10-14 08:50:06 +0000870 : VPRecipeBase(VPInterleaveSC), IG(IG) {
871 if (Mask) // Create a VPInstruction to register as a user of the mask.
872 User.reset(new VPUser({Mask}));
873 }
Hal Finkel7333aa92017-12-16 01:12:50 +0000874 ~VPInterleaveRecipe() override = default;
875
876 /// Method to support type inquiry through isa, cast, and dyn_cast.
877 static inline bool classof(const VPRecipeBase *V) {
878 return V->getVPRecipeID() == VPRecipeBase::VPInterleaveSC;
879 }
880
881 /// Generate the wide load or store, and shuffles.
882 void execute(VPTransformState &State) override;
883
884 /// Print the recipe.
885 void print(raw_ostream &O, const Twine &Indent) const override;
886
Florian Hahna4dc7fe2018-11-13 15:58:18 +0000887 const InterleaveGroup<Instruction> *getInterleaveGroup() { return IG; }
Hal Finkel7333aa92017-12-16 01:12:50 +0000888};
889
890/// VPReplicateRecipe replicates a given instruction producing multiple scalar
891/// copies of the original scalar type, one per lane, instead of producing a
892/// single copy of widened type for all lanes. If the instruction is known to be
893/// uniform only one copy, per lane zero, will be generated.
894class VPReplicateRecipe : public VPRecipeBase {
895private:
896 /// The instruction being replicated.
897 Instruction *Ingredient;
898
899 /// Indicator if only a single replica per lane is needed.
900 bool IsUniform;
901
902 /// Indicator if the replicas are also predicated.
903 bool IsPredicated;
904
905 /// Indicator if the scalar values should also be packed into a vector.
906 bool AlsoPack;
907
908public:
909 VPReplicateRecipe(Instruction *I, bool IsUniform, bool IsPredicated = false)
910 : VPRecipeBase(VPReplicateSC), Ingredient(I), IsUniform(IsUniform),
911 IsPredicated(IsPredicated) {
912 // Retain the previous behavior of predicateInstructions(), where an
913 // insert-element of a predicated instruction got hoisted into the
914 // predicated basic block iff it was its only user. This is achieved by
915 // having predicated instructions also pack their values into a vector by
916 // default unless they have a replicated user which uses their scalar value.
917 AlsoPack = IsPredicated && !I->use_empty();
918 }
919
920 ~VPReplicateRecipe() override = default;
921
922 /// Method to support type inquiry through isa, cast, and dyn_cast.
923 static inline bool classof(const VPRecipeBase *V) {
924 return V->getVPRecipeID() == VPRecipeBase::VPReplicateSC;
925 }
926
927 /// Generate replicas of the desired Ingredient. Replicas will be generated
928 /// for all parts and lanes unless a specific part and lane are specified in
929 /// the \p State.
930 void execute(VPTransformState &State) override;
931
932 void setAlsoPack(bool Pack) { AlsoPack = Pack; }
933
934 /// Print the recipe.
935 void print(raw_ostream &O, const Twine &Indent) const override;
936};
937
938/// A recipe for generating conditional branches on the bits of a mask.
939class VPBranchOnMaskRecipe : public VPRecipeBase {
940private:
941 std::unique_ptr<VPUser> User;
942
943public:
944 VPBranchOnMaskRecipe(VPValue *BlockInMask) : VPRecipeBase(VPBranchOnMaskSC) {
945 if (BlockInMask) // nullptr means all-one mask.
946 User.reset(new VPUser({BlockInMask}));
947 }
948
949 /// Method to support type inquiry through isa, cast, and dyn_cast.
950 static inline bool classof(const VPRecipeBase *V) {
951 return V->getVPRecipeID() == VPRecipeBase::VPBranchOnMaskSC;
952 }
953
954 /// Generate the extraction of the appropriate bit from the block mask and the
955 /// conditional branch.
956 void execute(VPTransformState &State) override;
957
958 /// Print the recipe.
959 void print(raw_ostream &O, const Twine &Indent) const override {
960 O << " +\n" << Indent << "\"BRANCH-ON-MASK ";
961 if (User)
962 O << *User->getOperand(0);
963 else
964 O << " All-One";
965 O << "\\l\"";
966 }
967};
968
969/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
970/// control converges back from a Branch-on-Mask. The phi nodes are needed in
971/// order to merge values that are set under such a branch and feed their uses.
972/// The phi nodes can be scalar or vector depending on the users of the value.
973/// This recipe works in concert with VPBranchOnMaskRecipe.
974class VPPredInstPHIRecipe : public VPRecipeBase {
975private:
976 Instruction *PredInst;
977
978public:
979 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
980 /// nodes after merging back from a Branch-on-Mask.
981 VPPredInstPHIRecipe(Instruction *PredInst)
982 : VPRecipeBase(VPPredInstPHISC), PredInst(PredInst) {}
983 ~VPPredInstPHIRecipe() override = default;
984
985 /// Method to support type inquiry through isa, cast, and dyn_cast.
986 static inline bool classof(const VPRecipeBase *V) {
987 return V->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC;
988 }
989
990 /// Generates phi nodes for live-outs as needed to retain SSA form.
991 void execute(VPTransformState &State) override;
992
993 /// Print the recipe.
994 void print(raw_ostream &O, const Twine &Indent) const override;
995};
996
997/// A Recipe for widening load/store operations.
998/// TODO: We currently execute only per-part unless a specific instance is
999/// provided.
1000class VPWidenMemoryInstructionRecipe : public VPRecipeBase {
1001private:
1002 Instruction &Instr;
1003 std::unique_ptr<VPUser> User;
1004
1005public:
1006 VPWidenMemoryInstructionRecipe(Instruction &Instr, VPValue *Mask)
1007 : VPRecipeBase(VPWidenMemoryInstructionSC), Instr(Instr) {
1008 if (Mask) // Create a VPInstruction to register as a user of the mask.
1009 User.reset(new VPUser({Mask}));
1010 }
1011
1012 /// Method to support type inquiry through isa, cast, and dyn_cast.
1013 static inline bool classof(const VPRecipeBase *V) {
1014 return V->getVPRecipeID() == VPRecipeBase::VPWidenMemoryInstructionSC;
1015 }
1016
Gil Rapaport7f152542019-10-07 17:24:33 +03001017 /// Return the mask used by this recipe. Note that a full mask is represented
1018 /// by a nullptr.
1019 VPValue *getMask() {
1020 // Mask is the last operand.
1021 return User ? User->getOperand(User->getNumOperands() - 1) : nullptr;
1022 }
1023
Hal Finkel7333aa92017-12-16 01:12:50 +00001024 /// Generate the wide load/store.
1025 void execute(VPTransformState &State) override;
1026
1027 /// Print the recipe.
1028 void print(raw_ostream &O, const Twine &Indent) const override;
1029};
1030
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001031/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
1032/// holds a sequence of zero or more VPRecipe's each representing a sequence of
1033/// output IR instructions.
1034class VPBasicBlock : public VPBlockBase {
1035public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001036 using RecipeListTy = iplist<VPRecipeBase>;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001037
1038private:
1039 /// The VPRecipes held in the order of output instructions to generate.
1040 RecipeListTy Recipes;
1041
1042public:
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001043 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
1044 : VPBlockBase(VPBasicBlockSC, Name.str()) {
1045 if (Recipe)
1046 appendRecipe(Recipe);
1047 }
1048
1049 ~VPBasicBlock() override { Recipes.clear(); }
1050
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001051 /// Instruction iterators...
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001052 using iterator = RecipeListTy::iterator;
1053 using const_iterator = RecipeListTy::const_iterator;
1054 using reverse_iterator = RecipeListTy::reverse_iterator;
1055 using const_reverse_iterator = RecipeListTy::const_reverse_iterator;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001056
1057 //===--------------------------------------------------------------------===//
1058 /// Recipe iterator methods
1059 ///
1060 inline iterator begin() { return Recipes.begin(); }
1061 inline const_iterator begin() const { return Recipes.begin(); }
1062 inline iterator end() { return Recipes.end(); }
1063 inline const_iterator end() const { return Recipes.end(); }
1064
1065 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
1066 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
1067 inline reverse_iterator rend() { return Recipes.rend(); }
1068 inline const_reverse_iterator rend() const { return Recipes.rend(); }
1069
1070 inline size_t size() const { return Recipes.size(); }
1071 inline bool empty() const { return Recipes.empty(); }
1072 inline const VPRecipeBase &front() const { return Recipes.front(); }
1073 inline VPRecipeBase &front() { return Recipes.front(); }
1074 inline const VPRecipeBase &back() const { return Recipes.back(); }
1075 inline VPRecipeBase &back() { return Recipes.back(); }
1076
Florian Hahn7591e4e2018-06-18 11:34:17 +00001077 /// Returns a reference to the list of recipes.
1078 RecipeListTy &getRecipeList() { return Recipes; }
1079
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001080 /// Returns a pointer to a member of the recipe list.
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001081 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
1082 return &VPBasicBlock::Recipes;
1083 }
1084
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001085 /// Method to support type inquiry through isa, cast, and dyn_cast.
1086 static inline bool classof(const VPBlockBase *V) {
1087 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
1088 }
1089
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001090 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001091 assert(Recipe && "No recipe to append.");
1092 assert(!Recipe->Parent && "Recipe already in VPlan");
1093 Recipe->Parent = this;
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001094 Recipes.insert(InsertPt, Recipe);
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001095 }
1096
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001097 /// Augment the existing recipes of a VPBasicBlock with an additional
1098 /// \p Recipe as the last recipe.
1099 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
1100
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001101 /// The method which generates the output IR instructions that correspond to
1102 /// this VPBasicBlock, thereby "executing" the VPlan.
1103 void execute(struct VPTransformState *State) override;
1104
1105private:
1106 /// Create an IR BasicBlock to hold the output instructions generated by this
1107 /// VPBasicBlock, and return it. Update the CFGState accordingly.
1108 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
1109};
1110
1111/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
1112/// which form a Single-Entry-Single-Exit subgraph of the output IR CFG.
1113/// A VPRegionBlock may indicate that its contents are to be replicated several
1114/// times. This is designed to support predicated scalarization, in which a
1115/// scalar if-then code structure needs to be generated VF * UF times. Having
1116/// this replication indicator helps to keep a single model for multiple
1117/// candidate VF's. The actual replication takes place only once the desired VF
1118/// and UF have been determined.
1119class VPRegionBlock : public VPBlockBase {
1120private:
1121 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
1122 VPBlockBase *Entry;
1123
1124 /// Hold the Single Exit of the SESE region modelled by the VPRegionBlock.
1125 VPBlockBase *Exit;
1126
1127 /// An indicator whether this region is to generate multiple replicated
1128 /// instances of output IR corresponding to its VPBlockBases.
1129 bool IsReplicator;
1130
1131public:
1132 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exit,
1133 const std::string &Name = "", bool IsReplicator = false)
1134 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exit(Exit),
1135 IsReplicator(IsReplicator) {
1136 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
1137 assert(Exit->getSuccessors().empty() && "Exit block has successors.");
1138 Entry->setParent(this);
1139 Exit->setParent(this);
1140 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001141 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
1142 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exit(nullptr),
1143 IsReplicator(IsReplicator) {}
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001144
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001145 ~VPRegionBlock() override {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001146 if (Entry)
1147 deleteCFG(Entry);
1148 }
1149
1150 /// Method to support type inquiry through isa, cast, and dyn_cast.
1151 static inline bool classof(const VPBlockBase *V) {
1152 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
1153 }
1154
1155 const VPBlockBase *getEntry() const { return Entry; }
1156 VPBlockBase *getEntry() { return Entry; }
1157
Diego Caballero168d04d2018-05-21 18:14:23 +00001158 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
1159 /// EntryBlock must have no predecessors.
1160 void setEntry(VPBlockBase *EntryBlock) {
1161 assert(EntryBlock->getPredecessors().empty() &&
1162 "Entry block cannot have predecessors.");
1163 Entry = EntryBlock;
1164 EntryBlock->setParent(this);
1165 }
1166
Diego Caballero2a34ac82018-07-30 21:33:31 +00001167 // FIXME: DominatorTreeBase is doing 'A->getParent()->front()'. 'front' is a
1168 // specific interface of llvm::Function, instead of using
1169 // GraphTraints::getEntryNode. We should add a new template parameter to
1170 // DominatorTreeBase representing the Graph type.
1171 VPBlockBase &front() const { return *Entry; }
1172
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001173 const VPBlockBase *getExit() const { return Exit; }
1174 VPBlockBase *getExit() { return Exit; }
1175
Diego Caballero168d04d2018-05-21 18:14:23 +00001176 /// Set \p ExitBlock as the exit VPBlockBase of this VPRegionBlock. \p
1177 /// ExitBlock must have no successors.
1178 void setExit(VPBlockBase *ExitBlock) {
1179 assert(ExitBlock->getSuccessors().empty() &&
1180 "Exit block cannot have successors.");
1181 Exit = ExitBlock;
1182 ExitBlock->setParent(this);
1183 }
1184
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001185 /// An indicator whether this region is to generate multiple replicated
1186 /// instances of output IR corresponding to its VPBlockBases.
1187 bool isReplicator() const { return IsReplicator; }
1188
1189 /// The method which generates the output IR instructions that correspond to
1190 /// this VPRegionBlock, thereby "executing" the VPlan.
1191 void execute(struct VPTransformState *State) override;
1192};
1193
Florian Hahnfe459ce2019-12-02 18:21:07 +00001194//===----------------------------------------------------------------------===//
1195// GraphTraits specializations for VPlan Hierarchical Control-Flow Graphs //
1196//===----------------------------------------------------------------------===//
1197
1198// The following set of template specializations implement GraphTraits to treat
1199// any VPBlockBase as a node in a graph of VPBlockBases. It's important to note
1200// that VPBlockBase traits don't recurse into VPRegioBlocks, i.e., if the
1201// VPBlockBase is a VPRegionBlock, this specialization provides access to its
1202// successors/predecessors but not to the blocks inside the region.
1203
1204template <> struct GraphTraits<VPBlockBase *> {
1205 using NodeRef = VPBlockBase *;
1206 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1207
1208 static NodeRef getEntryNode(NodeRef N) { return N; }
1209
1210 static inline ChildIteratorType child_begin(NodeRef N) {
1211 return N->getSuccessors().begin();
1212 }
1213
1214 static inline ChildIteratorType child_end(NodeRef N) {
1215 return N->getSuccessors().end();
1216 }
1217};
1218
1219template <> struct GraphTraits<const VPBlockBase *> {
1220 using NodeRef = const VPBlockBase *;
1221 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::const_iterator;
1222
1223 static NodeRef getEntryNode(NodeRef N) { return N; }
1224
1225 static inline ChildIteratorType child_begin(NodeRef N) {
1226 return N->getSuccessors().begin();
1227 }
1228
1229 static inline ChildIteratorType child_end(NodeRef N) {
1230 return N->getSuccessors().end();
1231 }
1232};
1233
1234// Inverse order specialization for VPBasicBlocks. Predecessors are used instead
1235// of successors for the inverse traversal.
1236template <> struct GraphTraits<Inverse<VPBlockBase *>> {
1237 using NodeRef = VPBlockBase *;
1238 using ChildIteratorType = SmallVectorImpl<VPBlockBase *>::iterator;
1239
1240 static NodeRef getEntryNode(Inverse<NodeRef> B) { return B.Graph; }
1241
1242 static inline ChildIteratorType child_begin(NodeRef N) {
1243 return N->getPredecessors().begin();
1244 }
1245
1246 static inline ChildIteratorType child_end(NodeRef N) {
1247 return N->getPredecessors().end();
1248 }
1249};
1250
1251// The following set of template specializations implement GraphTraits to
1252// treat VPRegionBlock as a graph and recurse inside its nodes. It's important
1253// to note that the blocks inside the VPRegionBlock are treated as VPBlockBases
1254// (i.e., no dyn_cast is performed, VPBlockBases specialization is used), so
1255// there won't be automatic recursion into other VPBlockBases that turn to be
1256// VPRegionBlocks.
1257
1258template <>
1259struct GraphTraits<VPRegionBlock *> : public GraphTraits<VPBlockBase *> {
1260 using GraphRef = VPRegionBlock *;
1261 using nodes_iterator = df_iterator<NodeRef>;
1262
1263 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1264
1265 static nodes_iterator nodes_begin(GraphRef N) {
1266 return nodes_iterator::begin(N->getEntry());
1267 }
1268
1269 static nodes_iterator nodes_end(GraphRef N) {
1270 // df_iterator::end() returns an empty iterator so the node used doesn't
1271 // matter.
1272 return nodes_iterator::end(N);
1273 }
1274};
1275
1276template <>
1277struct GraphTraits<const VPRegionBlock *>
1278 : public GraphTraits<const VPBlockBase *> {
1279 using GraphRef = const VPRegionBlock *;
1280 using nodes_iterator = df_iterator<NodeRef>;
1281
1282 static NodeRef getEntryNode(GraphRef N) { return N->getEntry(); }
1283
1284 static nodes_iterator nodes_begin(GraphRef N) {
1285 return nodes_iterator::begin(N->getEntry());
1286 }
1287
1288 static nodes_iterator nodes_end(GraphRef N) {
1289 // df_iterator::end() returns an empty iterator so the node used doesn't
1290 // matter.
1291 return nodes_iterator::end(N);
1292 }
1293};
1294
1295template <>
1296struct GraphTraits<Inverse<VPRegionBlock *>>
1297 : public GraphTraits<Inverse<VPBlockBase *>> {
1298 using GraphRef = VPRegionBlock *;
1299 using nodes_iterator = df_iterator<NodeRef>;
1300
1301 static NodeRef getEntryNode(Inverse<GraphRef> N) {
1302 return N.Graph->getExit();
1303 }
1304
1305 static nodes_iterator nodes_begin(GraphRef N) {
1306 return nodes_iterator::begin(N->getExit());
1307 }
1308
1309 static nodes_iterator nodes_end(GraphRef N) {
1310 // df_iterator::end() returns an empty iterator so the node used doesn't
1311 // matter.
1312 return nodes_iterator::end(N);
1313 }
1314};
1315
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001316/// VPlan models a candidate for vectorization, encoding various decisions take
1317/// to produce efficient output IR, including which branches, basic-blocks and
1318/// output IR instructions to generate, and their cost. VPlan holds a
1319/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
1320/// VPBlock.
1321class VPlan {
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001322 friend class VPlanPrinter;
1323
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001324private:
1325 /// Hold the single entry to the Hierarchical CFG of the VPlan.
1326 VPBlockBase *Entry;
1327
1328 /// Holds the VFs applicable to this VPlan.
1329 SmallSet<unsigned, 2> VFs;
1330
1331 /// Holds the name of the VPlan, for printing.
1332 std::string Name;
1333
Diego Caballero168d04d2018-05-21 18:14:23 +00001334 /// Holds all the external definitions created for this VPlan.
1335 // TODO: Introduce a specific representation for external definitions in
1336 // VPlan. External definitions must be immutable and hold a pointer to its
1337 // underlying IR that will be used to implement its structural comparison
1338 // (operators '==' and '<').
Craig Topper61998282018-06-09 05:04:20 +00001339 SmallPtrSet<VPValue *, 16> VPExternalDefs;
Diego Caballero168d04d2018-05-21 18:14:23 +00001340
Ayal Zaksb0b53122018-10-18 15:03:15 +00001341 /// Represents the backedge taken count of the original loop, for folding
1342 /// the tail.
1343 VPValue *BackedgeTakenCount = nullptr;
1344
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001345 /// Holds a mapping between Values and their corresponding VPValue inside
1346 /// VPlan.
1347 Value2VPValueTy Value2VPValue;
1348
Diego Caballero35871502018-07-31 01:57:29 +00001349 /// Holds the VPLoopInfo analysis for this VPlan.
1350 VPLoopInfo VPLInfo;
1351
Hideki Saitod19851a2018-09-14 02:02:57 +00001352 /// Holds the condition bit values built during VPInstruction to VPRecipe transformation.
1353 SmallVector<VPValue *, 4> VPCBVs;
1354
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001355public:
1356 VPlan(VPBlockBase *Entry = nullptr) : Entry(Entry) {}
1357
1358 ~VPlan() {
1359 if (Entry)
1360 VPBlockBase::deleteCFG(Entry);
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001361 for (auto &MapEntry : Value2VPValue)
Ayal Zaksb0b53122018-10-18 15:03:15 +00001362 if (MapEntry.second != BackedgeTakenCount)
1363 delete MapEntry.second;
1364 if (BackedgeTakenCount)
1365 delete BackedgeTakenCount; // Delete once, if in Value2VPValue or not.
Diego Caballero168d04d2018-05-21 18:14:23 +00001366 for (VPValue *Def : VPExternalDefs)
1367 delete Def;
Hideki Saitod19851a2018-09-14 02:02:57 +00001368 for (VPValue *CBV : VPCBVs)
1369 delete CBV;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001370 }
1371
1372 /// Generate the IR code for this VPlan.
1373 void execute(struct VPTransformState *State);
1374
1375 VPBlockBase *getEntry() { return Entry; }
1376 const VPBlockBase *getEntry() const { return Entry; }
1377
1378 VPBlockBase *setEntry(VPBlockBase *Block) { return Entry = Block; }
1379
Ayal Zaksb0b53122018-10-18 15:03:15 +00001380 /// The backedge taken count of the original loop.
1381 VPValue *getOrCreateBackedgeTakenCount() {
1382 if (!BackedgeTakenCount)
1383 BackedgeTakenCount = new VPValue();
1384 return BackedgeTakenCount;
1385 }
1386
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001387 void addVF(unsigned VF) { VFs.insert(VF); }
1388
1389 bool hasVF(unsigned VF) { return VFs.count(VF); }
1390
1391 const std::string &getName() const { return Name; }
1392
1393 void setName(const Twine &newName) { Name = newName.str(); }
1394
Diego Caballero168d04d2018-05-21 18:14:23 +00001395 /// Add \p VPVal to the pool of external definitions if it's not already
1396 /// in the pool.
1397 void addExternalDef(VPValue *VPVal) {
1398 VPExternalDefs.insert(VPVal);
1399 }
1400
Hideki Saitod19851a2018-09-14 02:02:57 +00001401 /// Add \p CBV to the vector of condition bit values.
1402 void addCBV(VPValue *CBV) {
1403 VPCBVs.push_back(CBV);
1404 }
1405
Gil Rapaport8b9d1f32017-11-20 12:01:47 +00001406 void addVPValue(Value *V) {
1407 assert(V && "Trying to add a null Value to VPlan");
1408 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
1409 Value2VPValue[V] = new VPValue();
1410 }
1411
1412 VPValue *getVPValue(Value *V) {
1413 assert(V && "Trying to get the VPValue of a null Value");
1414 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
1415 return Value2VPValue[V];
1416 }
1417
Diego Caballero35871502018-07-31 01:57:29 +00001418 /// Return the VPLoopInfo analysis for this VPlan.
1419 VPLoopInfo &getVPLoopInfo() { return VPLInfo; }
1420 const VPLoopInfo &getVPLoopInfo() const { return VPLInfo; }
1421
Florian Hahne9c68422019-12-03 11:58:31 +00001422 /// Dump the plan to stderr (for debugging).
1423 void dump() const;
1424
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001425private:
1426 /// Add to the given dominator tree the header block and every new basic block
1427 /// that was created between it and the latch block, inclusive.
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001428 static void updateDominatorTree(DominatorTree *DT,
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001429 BasicBlock *LoopPreHeaderBB,
1430 BasicBlock *LoopLatchBB);
1431};
1432
1433/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
1434/// indented and follows the dot format.
1435class VPlanPrinter {
Florian Hahne9c68422019-12-03 11:58:31 +00001436 friend inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan);
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001437 friend inline raw_ostream &operator<<(raw_ostream &OS,
1438 const struct VPlanIngredient &I);
1439
1440private:
1441 raw_ostream &OS;
Florian Hahne9c68422019-12-03 11:58:31 +00001442 const VPlan &Plan;
Simon Pilgrim81ba6112019-11-03 11:17:05 +00001443 unsigned Depth = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001444 unsigned TabWidth = 2;
1445 std::string Indent;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001446 unsigned BID = 0;
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001447 SmallDenseMap<const VPBlockBase *, unsigned> BlockID;
1448
Florian Hahne9c68422019-12-03 11:58:31 +00001449 VPlanPrinter(raw_ostream &O, const VPlan &P) : OS(O), Plan(P) {}
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001450
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001451 /// Handle indentation.
1452 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
1453
1454 /// Print a given \p Block of the Plan.
1455 void dumpBlock(const VPBlockBase *Block);
1456
1457 /// Print the information related to the CFG edges going out of a given
1458 /// \p Block, followed by printing the successor blocks themselves.
1459 void dumpEdges(const VPBlockBase *Block);
1460
1461 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
1462 /// its successor blocks.
1463 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
1464
1465 /// Print a given \p Region of the Plan.
1466 void dumpRegion(const VPRegionBlock *Region);
1467
1468 unsigned getOrCreateBID(const VPBlockBase *Block) {
1469 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
1470 }
1471
1472 const Twine getOrCreateName(const VPBlockBase *Block);
1473
1474 const Twine getUID(const VPBlockBase *Block);
1475
1476 /// Print the information related to a CFG edge between two VPBlockBases.
1477 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
1478 const Twine &Label);
1479
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001480 void dump();
1481
1482 static void printAsIngredient(raw_ostream &O, Value *V);
1483};
1484
1485struct VPlanIngredient {
1486 Value *V;
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001487
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001488 VPlanIngredient(Value *V) : V(V) {}
1489};
1490
1491inline raw_ostream &operator<<(raw_ostream &OS, const VPlanIngredient &I) {
1492 VPlanPrinter::printAsIngredient(OS, I.V);
1493 return OS;
1494}
1495
Florian Hahne9c68422019-12-03 11:58:31 +00001496inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001497 VPlanPrinter Printer(OS, Plan);
1498 Printer.dump();
1499 return OS;
1500}
1501
Diego Caballero168d04d2018-05-21 18:14:23 +00001502//===----------------------------------------------------------------------===//
1503// VPlan Utilities
1504//===----------------------------------------------------------------------===//
1505
1506/// Class that provides utilities for VPBlockBases in VPlan.
1507class VPBlockUtils {
1508public:
1509 VPBlockUtils() = delete;
1510
1511 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
Diego Caballerod0953012018-07-09 15:57:09 +00001512 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
1513 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. If \p BlockPtr
1514 /// has more than one successor, its conditional bit is propagated to \p
1515 /// NewBlock. \p NewBlock must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001516 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
1517 assert(NewBlock->getSuccessors().empty() &&
1518 "Can't insert new block with successors.");
1519 // TODO: move successors from BlockPtr to NewBlock when this functionality
1520 // is necessary. For now, setBlockSingleSuccessor will assert if BlockPtr
1521 // already has successors.
1522 BlockPtr->setOneSuccessor(NewBlock);
1523 NewBlock->setPredecessors({BlockPtr});
1524 NewBlock->setParent(BlockPtr->getParent());
1525 }
1526
1527 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
1528 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
1529 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
Diego Caballerod0953012018-07-09 15:57:09 +00001530 /// parent to \p IfTrue and \p IfFalse. \p Condition is set as the successor
1531 /// selector. \p BlockPtr must have no successors and \p IfTrue and \p IfFalse
1532 /// must have neither successors nor predecessors.
Diego Caballero168d04d2018-05-21 18:14:23 +00001533 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
Diego Caballerod0953012018-07-09 15:57:09 +00001534 VPValue *Condition, VPBlockBase *BlockPtr) {
Diego Caballero168d04d2018-05-21 18:14:23 +00001535 assert(IfTrue->getSuccessors().empty() &&
1536 "Can't insert IfTrue with successors.");
1537 assert(IfFalse->getSuccessors().empty() &&
1538 "Can't insert IfFalse with successors.");
Diego Caballerod0953012018-07-09 15:57:09 +00001539 BlockPtr->setTwoSuccessors(IfTrue, IfFalse, Condition);
Diego Caballero168d04d2018-05-21 18:14:23 +00001540 IfTrue->setPredecessors({BlockPtr});
1541 IfFalse->setPredecessors({BlockPtr});
1542 IfTrue->setParent(BlockPtr->getParent());
1543 IfFalse->setParent(BlockPtr->getParent());
1544 }
1545
1546 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
1547 /// the successors of \p From and \p From to the predecessors of \p To. Both
1548 /// VPBlockBases must have the same parent, which can be null. Both
1549 /// VPBlockBases can be already connected to other VPBlockBases.
1550 static void connectBlocks(VPBlockBase *From, VPBlockBase *To) {
1551 assert((From->getParent() == To->getParent()) &&
1552 "Can't connect two block with different parents");
1553 assert(From->getNumSuccessors() < 2 &&
1554 "Blocks can't have more than two successors.");
1555 From->appendSuccessor(To);
1556 To->appendPredecessor(From);
1557 }
1558
1559 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
1560 /// from the successors of \p From and \p From from the predecessors of \p To.
1561 static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To) {
1562 assert(To && "Successor to disconnect is null.");
1563 From->removeSuccessor(To);
1564 To->removePredecessor(From);
1565 }
Hideki Saito4e4ecae2019-01-23 22:43:12 +00001566
1567 /// Returns true if the edge \p FromBlock -> \p ToBlock is a back-edge.
1568 static bool isBackEdge(const VPBlockBase *FromBlock,
1569 const VPBlockBase *ToBlock, const VPLoopInfo *VPLI) {
1570 assert(FromBlock->getParent() == ToBlock->getParent() &&
1571 FromBlock->getParent() && "Must be in same region");
1572 const VPLoop *FromLoop = VPLI->getLoopFor(FromBlock);
1573 const VPLoop *ToLoop = VPLI->getLoopFor(ToBlock);
1574 if (!FromLoop || !ToLoop || FromLoop != ToLoop)
1575 return false;
1576
1577 // A back-edge is a branch from the loop latch to its header.
1578 return ToLoop->isLoopLatch(FromBlock) && ToBlock == ToLoop->getHeader();
1579 }
1580
1581 /// Returns true if \p Block is a loop latch
1582 static bool blockIsLoopLatch(const VPBlockBase *Block,
1583 const VPLoopInfo *VPLInfo) {
1584 if (const VPLoop *ParentVPL = VPLInfo->getLoopFor(Block))
1585 return ParentVPL->isLoopLatch(Block);
1586
1587 return false;
1588 }
1589
1590 /// Count and return the number of succesors of \p PredBlock excluding any
1591 /// backedges.
1592 static unsigned countSuccessorsNoBE(VPBlockBase *PredBlock,
1593 VPLoopInfo *VPLI) {
1594 unsigned Count = 0;
1595 for (VPBlockBase *SuccBlock : PredBlock->getSuccessors()) {
1596 if (!VPBlockUtils::isBackEdge(PredBlock, SuccBlock, VPLI))
1597 Count++;
1598 }
1599 return Count;
1600 }
Diego Caballero168d04d2018-05-21 18:14:23 +00001601};
Florian Hahn45e5d5b2018-06-08 17:30:45 +00001602
Florian Hahna4dc7fe2018-11-13 15:58:18 +00001603class VPInterleavedAccessInfo {
1604private:
1605 DenseMap<VPInstruction *, InterleaveGroup<VPInstruction> *>
1606 InterleaveGroupMap;
1607
1608 /// Type for mapping of instruction based interleave groups to VPInstruction
1609 /// interleave groups
1610 using Old2NewTy = DenseMap<InterleaveGroup<Instruction> *,
1611 InterleaveGroup<VPInstruction> *>;
1612
1613 /// Recursively \p Region and populate VPlan based interleave groups based on
1614 /// \p IAI.
1615 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
1616 InterleavedAccessInfo &IAI);
1617 /// Recursively traverse \p Block and populate VPlan based interleave groups
1618 /// based on \p IAI.
1619 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1620 InterleavedAccessInfo &IAI);
1621
1622public:
1623 VPInterleavedAccessInfo(VPlan &Plan, InterleavedAccessInfo &IAI);
1624
1625 ~VPInterleavedAccessInfo() {
1626 SmallPtrSet<InterleaveGroup<VPInstruction> *, 4> DelSet;
1627 // Avoid releasing a pointer twice.
1628 for (auto &I : InterleaveGroupMap)
1629 DelSet.insert(I.second);
1630 for (auto *Ptr : DelSet)
1631 delete Ptr;
1632 }
1633
1634 /// Get the interleave group that \p Instr belongs to.
1635 ///
1636 /// \returns nullptr if doesn't have such group.
1637 InterleaveGroup<VPInstruction> *
1638 getInterleaveGroup(VPInstruction *Instr) const {
1639 if (InterleaveGroupMap.count(Instr))
1640 return InterleaveGroupMap.find(Instr)->second;
1641 return nullptr;
1642 }
1643};
1644
Florian Hahn09e516c2018-11-14 13:11:49 +00001645/// Class that maps (parts of) an existing VPlan to trees of combined
1646/// VPInstructions.
1647class VPlanSlp {
1648private:
1649 enum class OpMode { Failed, Load, Opcode };
1650
1651 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
1652 /// DenseMap keys.
1653 struct BundleDenseMapInfo {
1654 static SmallVector<VPValue *, 4> getEmptyKey() {
1655 return {reinterpret_cast<VPValue *>(-1)};
1656 }
1657
1658 static SmallVector<VPValue *, 4> getTombstoneKey() {
1659 return {reinterpret_cast<VPValue *>(-2)};
1660 }
1661
1662 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
1663 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1664 }
1665
1666 static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
1667 const SmallVector<VPValue *, 4> &RHS) {
1668 return LHS == RHS;
1669 }
1670 };
1671
1672 /// Mapping of values in the original VPlan to a combined VPInstruction.
1673 DenseMap<SmallVector<VPValue *, 4>, VPInstruction *, BundleDenseMapInfo>
1674 BundleToCombined;
1675
1676 VPInterleavedAccessInfo &IAI;
1677
1678 /// Basic block to operate on. For now, only instructions in a single BB are
1679 /// considered.
1680 const VPBasicBlock &BB;
1681
1682 /// Indicates whether we managed to combine all visited instructions or not.
1683 bool CompletelySLP = true;
1684
1685 /// Width of the widest combined bundle in bits.
1686 unsigned WidestBundleBits = 0;
1687
1688 using MultiNodeOpTy =
1689 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
1690
1691 // Input operand bundles for the current multi node. Each multi node operand
1692 // bundle contains values not matching the multi node's opcode. They will
1693 // be reordered in reorderMultiNodeOps, once we completed building a
1694 // multi node.
1695 SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
1696
1697 /// Indicates whether we are building a multi node currently.
1698 bool MultiNodeActive = false;
1699
1700 /// Check if we can vectorize Operands together.
1701 bool areVectorizable(ArrayRef<VPValue *> Operands) const;
1702
1703 /// Add combined instruction \p New for the bundle \p Operands.
1704 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
1705
1706 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
1707 VPInstruction *markFailed();
1708
1709 /// Reorder operands in the multi node to maximize sequential memory access
1710 /// and commutative operations.
1711 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
1712
1713 /// Choose the best candidate to use for the lane after \p Last. The set of
1714 /// candidates to choose from are values with an opcode matching \p Last's
1715 /// or loads consecutive to \p Last.
1716 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
Florian Hahn6df11862018-11-14 15:58:40 +00001717 SmallPtrSetImpl<VPValue *> &Candidates,
Florian Hahn09e516c2018-11-14 13:11:49 +00001718 VPInterleavedAccessInfo &IAI);
1719
1720 /// Print bundle \p Values to dbgs().
1721 void dumpBundle(ArrayRef<VPValue *> Values);
1722
1723public:
1724 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
1725
1726 ~VPlanSlp() {
1727 for (auto &KV : BundleToCombined)
1728 delete KV.second;
1729 }
1730
1731 /// Tries to build an SLP tree rooted at \p Operands and returns a
1732 /// VPInstruction combining \p Operands, if they can be combined.
1733 VPInstruction *buildGraph(ArrayRef<VPValue *> Operands);
1734
1735 /// Return the width of the widest combined bundle in bits.
1736 unsigned getWidestBundleBits() const { return WidestBundleBits; }
1737
1738 /// Return true if all visited instruction can be combined.
1739 bool isCompletelySLP() const { return CompletelySLP; }
1740};
Eugene Zelenko6cadde72017-10-17 21:27:42 +00001741} // end namespace llvm
Ayal Zaks1f58dda2017-08-27 12:55:46 +00001742
1743#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H