1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
3 // 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
7 //===----------------------------------------------------------------------===//
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
14 // The pass is inspired by the work described in the paper:
15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/CodeMetrics.h"
37 #include "llvm/Analysis/DemandedBits.h"
38 #include "llvm/Analysis/GlobalsModRef.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryLocation.h"
42 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
43 #include "llvm/Analysis/ScalarEvolution.h"
44 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
45 #include "llvm/Analysis/TargetLibraryInfo.h"
46 #include "llvm/Analysis/TargetTransformInfo.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Analysis/VectorUtils.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/Constant.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/IRBuilder.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/Intrinsics.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/NoFolder.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PassManager.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #include "llvm/IR/Verifier.h"
75 #include "llvm/Pass.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/DOTGraphTraits.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/GraphWriter.h"
83 #include "llvm/Support/KnownBits.h"
84 #include "llvm/Support/MathExtras.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Transforms/Utils/LoopUtils.h"
87 #include "llvm/Transforms/Vectorize.h"
100 using namespace llvm::PatternMatch
;
101 using namespace slpvectorizer
;
103 #define SV_NAME "slp-vectorizer"
104 #define DEBUG_TYPE "SLP"
106 STATISTIC(NumVectorInstructions
, "Number of vector instructions generated");
109 llvm::RunSLPVectorization("vectorize-slp", cl::init(false), cl::Hidden
,
110 cl::desc("Run the SLP vectorization passes"));
113 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden
,
114 cl::desc("Only vectorize if you gain more than this "
118 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden
,
119 cl::desc("Attempt to vectorize horizontal reductions"));
121 static cl::opt
<bool> ShouldStartVectorizeHorAtStore(
122 "slp-vectorize-hor-store", cl::init(false), cl::Hidden
,
124 "Attempt to vectorize horizontal reductions feeding into a store"));
127 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden
,
128 cl::desc("Attempt to vectorize for this register size in bits"));
130 /// Limits the size of scheduling regions in a block.
131 /// It avoid long compile times for _very_ large blocks where vector
132 /// instructions are spread over a wide range.
133 /// This limit is way higher than needed by real-world functions.
135 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden
,
136 cl::desc("Limit the size of the SLP scheduling region per block"));
138 static cl::opt
<int> MinVectorRegSizeOption(
139 "slp-min-reg-size", cl::init(128), cl::Hidden
,
140 cl::desc("Attempt to vectorize for this register size in bits"));
142 static cl::opt
<unsigned> RecursionMaxDepth(
143 "slp-recursion-max-depth", cl::init(12), cl::Hidden
,
144 cl::desc("Limit the recursion depth when building a vectorizable tree"));
146 static cl::opt
<unsigned> MinTreeSize(
147 "slp-min-tree-size", cl::init(3), cl::Hidden
,
148 cl::desc("Only vectorize small trees if they are fully vectorizable"));
151 ViewSLPTree("view-slp-tree", cl::Hidden
,
152 cl::desc("Display the SLP trees with Graphviz"));
154 // Limit the number of alias checks. The limit is chosen so that
155 // it has no negative effect on the llvm benchmarks.
156 static const unsigned AliasedCheckLimit
= 10;
158 // Another limit for the alias checks: The maximum distance between load/store
159 // instructions where alias checks are done.
160 // This limit is useful for very large basic blocks.
161 static const unsigned MaxMemDepDistance
= 160;
163 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
164 /// regions to be handled.
165 static const int MinScheduleRegionSize
= 16;
167 /// Predicate for the element types that the SLP vectorizer supports.
169 /// The most important thing to filter here are types which are invalid in LLVM
170 /// vectors. We also filter target specific types which have absolutely no
171 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
172 /// avoids spending time checking the cost model and realizing that they will
173 /// be inevitably scalarized.
174 static bool isValidElementType(Type
*Ty
) {
175 return VectorType::isValidElementType(Ty
) && !Ty
->isX86_FP80Ty() &&
176 !Ty
->isPPC_FP128Ty();
179 /// \returns true if all of the instructions in \p VL are in the same block or
181 static bool allSameBlock(ArrayRef
<Value
*> VL
) {
182 Instruction
*I0
= dyn_cast
<Instruction
>(VL
[0]);
185 BasicBlock
*BB
= I0
->getParent();
186 for (int i
= 1, e
= VL
.size(); i
< e
; i
++) {
187 Instruction
*I
= dyn_cast
<Instruction
>(VL
[i
]);
191 if (BB
!= I
->getParent())
197 /// \returns True if all of the values in \p VL are constants (but not
198 /// globals/constant expressions).
199 static bool allConstant(ArrayRef
<Value
*> VL
) {
200 // Constant expressions and globals can't be vectorized like normal integer/FP
203 if (!isa
<Constant
>(i
) || isa
<ConstantExpr
>(i
) || isa
<GlobalValue
>(i
))
208 /// \returns True if all of the values in \p VL are identical.
209 static bool isSplat(ArrayRef
<Value
*> VL
) {
210 for (unsigned i
= 1, e
= VL
.size(); i
< e
; ++i
)
216 /// \returns True if \p I is commutative, handles CmpInst as well as Instruction.
217 static bool isCommutative(Instruction
*I
) {
218 if (auto *IC
= dyn_cast
<CmpInst
>(I
))
219 return IC
->isCommutative();
220 return I
->isCommutative();
223 /// Checks if the vector of instructions can be represented as a shuffle, like:
224 /// %x0 = extractelement <4 x i8> %x, i32 0
225 /// %x3 = extractelement <4 x i8> %x, i32 3
226 /// %y1 = extractelement <4 x i8> %y, i32 1
227 /// %y2 = extractelement <4 x i8> %y, i32 2
228 /// %x0x0 = mul i8 %x0, %x0
229 /// %x3x3 = mul i8 %x3, %x3
230 /// %y1y1 = mul i8 %y1, %y1
231 /// %y2y2 = mul i8 %y2, %y2
232 /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
233 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
234 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
235 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
236 /// ret <4 x i8> %ins4
237 /// can be transformed into:
238 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
240 /// %2 = mul <4 x i8> %1, %1
242 /// We convert this initially to something like:
243 /// %x0 = extractelement <4 x i8> %x, i32 0
244 /// %x3 = extractelement <4 x i8> %x, i32 3
245 /// %y1 = extractelement <4 x i8> %y, i32 1
246 /// %y2 = extractelement <4 x i8> %y, i32 2
247 /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
248 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
249 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
250 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
251 /// %5 = mul <4 x i8> %4, %4
252 /// %6 = extractelement <4 x i8> %5, i32 0
253 /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
254 /// %7 = extractelement <4 x i8> %5, i32 1
255 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
256 /// %8 = extractelement <4 x i8> %5, i32 2
257 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
258 /// %9 = extractelement <4 x i8> %5, i32 3
259 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
260 /// ret <4 x i8> %ins4
261 /// InstCombiner transforms this into a shuffle and vector mul
262 /// TODO: Can we split off and reuse the shuffle mask detection from
263 /// TargetTransformInfo::getInstructionThroughput?
264 static Optional
<TargetTransformInfo::ShuffleKind
>
265 isShuffle(ArrayRef
<Value
*> VL
) {
266 auto *EI0
= cast
<ExtractElementInst
>(VL
[0]);
267 unsigned Size
= EI0
->getVectorOperandType()->getVectorNumElements();
268 Value
*Vec1
= nullptr;
269 Value
*Vec2
= nullptr;
270 enum ShuffleMode
{ Unknown
, Select
, Permute
};
271 ShuffleMode CommonShuffleMode
= Unknown
;
272 for (unsigned I
= 0, E
= VL
.size(); I
< E
; ++I
) {
273 auto *EI
= cast
<ExtractElementInst
>(VL
[I
]);
274 auto *Vec
= EI
->getVectorOperand();
275 // All vector operands must have the same number of vector elements.
276 if (Vec
->getType()->getVectorNumElements() != Size
)
278 auto *Idx
= dyn_cast
<ConstantInt
>(EI
->getIndexOperand());
281 // Undefined behavior if Idx is negative or >= Size.
282 if (Idx
->getValue().uge(Size
))
284 unsigned IntIdx
= Idx
->getValue().getZExtValue();
285 // We can extractelement from undef vector.
286 if (isa
<UndefValue
>(Vec
))
288 // For correct shuffling we have to have at most 2 different vector operands
289 // in all extractelement instructions.
290 if (!Vec1
|| Vec1
== Vec
)
292 else if (!Vec2
|| Vec2
== Vec
)
296 if (CommonShuffleMode
== Permute
)
298 // If the extract index is not the same as the operation number, it is a
301 CommonShuffleMode
= Permute
;
304 CommonShuffleMode
= Select
;
306 // If we're not crossing lanes in different vectors, consider it as blending.
307 if (CommonShuffleMode
== Select
&& Vec2
)
308 return TargetTransformInfo::SK_Select
;
309 // If Vec2 was never used, we have a permutation of a single vector, otherwise
310 // we have permutation of 2 vectors.
311 return Vec2
? TargetTransformInfo::SK_PermuteTwoSrc
312 : TargetTransformInfo::SK_PermuteSingleSrc
;
317 /// Main data required for vectorization of instructions.
318 struct InstructionsState
{
319 /// The very first instruction in the list with the main opcode.
320 Value
*OpValue
= nullptr;
322 /// The main/alternate instruction.
323 Instruction
*MainOp
= nullptr;
324 Instruction
*AltOp
= nullptr;
326 /// The main/alternate opcodes for the list of instructions.
327 unsigned getOpcode() const {
328 return MainOp
? MainOp
->getOpcode() : 0;
331 unsigned getAltOpcode() const {
332 return AltOp
? AltOp
->getOpcode() : 0;
335 /// Some of the instructions in the list have alternate opcodes.
336 bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
338 bool isOpcodeOrAlt(Instruction
*I
) const {
339 unsigned CheckedOpcode
= I
->getOpcode();
340 return getOpcode() == CheckedOpcode
|| getAltOpcode() == CheckedOpcode
;
343 InstructionsState() = delete;
344 InstructionsState(Value
*OpValue
, Instruction
*MainOp
, Instruction
*AltOp
)
345 : OpValue(OpValue
), MainOp(MainOp
), AltOp(AltOp
) {}
348 } // end anonymous namespace
350 /// Chooses the correct key for scheduling data. If \p Op has the same (or
351 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
353 static Value
*isOneOf(const InstructionsState
&S
, Value
*Op
) {
354 auto *I
= dyn_cast
<Instruction
>(Op
);
355 if (I
&& S
.isOpcodeOrAlt(I
))
360 /// \returns analysis of the Instructions in \p VL described in
361 /// InstructionsState, the Opcode that we suppose the whole list
362 /// could be vectorized even if its structure is diverse.
363 static InstructionsState
getSameOpcode(ArrayRef
<Value
*> VL
,
364 unsigned BaseIndex
= 0) {
365 // Make sure these are all Instructions.
366 if (llvm::any_of(VL
, [](Value
*V
) { return !isa
<Instruction
>(V
); }))
367 return InstructionsState(VL
[BaseIndex
], nullptr, nullptr);
369 bool IsCastOp
= isa
<CastInst
>(VL
[BaseIndex
]);
370 bool IsBinOp
= isa
<BinaryOperator
>(VL
[BaseIndex
]);
371 unsigned Opcode
= cast
<Instruction
>(VL
[BaseIndex
])->getOpcode();
372 unsigned AltOpcode
= Opcode
;
373 unsigned AltIndex
= BaseIndex
;
375 // Check for one alternate opcode from another BinaryOperator.
376 // TODO - generalize to support all operators (types, calls etc.).
377 for (int Cnt
= 0, E
= VL
.size(); Cnt
< E
; Cnt
++) {
378 unsigned InstOpcode
= cast
<Instruction
>(VL
[Cnt
])->getOpcode();
379 if (IsBinOp
&& isa
<BinaryOperator
>(VL
[Cnt
])) {
380 if (InstOpcode
== Opcode
|| InstOpcode
== AltOpcode
)
382 if (Opcode
== AltOpcode
) {
383 AltOpcode
= InstOpcode
;
387 } else if (IsCastOp
&& isa
<CastInst
>(VL
[Cnt
])) {
388 Type
*Ty0
= cast
<Instruction
>(VL
[BaseIndex
])->getOperand(0)->getType();
389 Type
*Ty1
= cast
<Instruction
>(VL
[Cnt
])->getOperand(0)->getType();
391 if (InstOpcode
== Opcode
|| InstOpcode
== AltOpcode
)
393 if (Opcode
== AltOpcode
) {
394 AltOpcode
= InstOpcode
;
399 } else if (InstOpcode
== Opcode
|| InstOpcode
== AltOpcode
)
401 return InstructionsState(VL
[BaseIndex
], nullptr, nullptr);
404 return InstructionsState(VL
[BaseIndex
], cast
<Instruction
>(VL
[BaseIndex
]),
405 cast
<Instruction
>(VL
[AltIndex
]));
408 /// \returns true if all of the values in \p VL have the same type or false
410 static bool allSameType(ArrayRef
<Value
*> VL
) {
411 Type
*Ty
= VL
[0]->getType();
412 for (int i
= 1, e
= VL
.size(); i
< e
; i
++)
413 if (VL
[i
]->getType() != Ty
)
419 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
420 static Optional
<unsigned> getExtractIndex(Instruction
*E
) {
421 unsigned Opcode
= E
->getOpcode();
422 assert((Opcode
== Instruction::ExtractElement
||
423 Opcode
== Instruction::ExtractValue
) &&
424 "Expected extractelement or extractvalue instruction.");
425 if (Opcode
== Instruction::ExtractElement
) {
426 auto *CI
= dyn_cast
<ConstantInt
>(E
->getOperand(1));
429 return CI
->getZExtValue();
431 ExtractValueInst
*EI
= cast
<ExtractValueInst
>(E
);
432 if (EI
->getNumIndices() != 1)
434 return *EI
->idx_begin();
437 /// \returns True if in-tree use also needs extract. This refers to
438 /// possible scalar operand in vectorized instruction.
439 static bool InTreeUserNeedToExtract(Value
*Scalar
, Instruction
*UserInst
,
440 TargetLibraryInfo
*TLI
) {
441 unsigned Opcode
= UserInst
->getOpcode();
443 case Instruction::Load
: {
444 LoadInst
*LI
= cast
<LoadInst
>(UserInst
);
445 return (LI
->getPointerOperand() == Scalar
);
447 case Instruction::Store
: {
448 StoreInst
*SI
= cast
<StoreInst
>(UserInst
);
449 return (SI
->getPointerOperand() == Scalar
);
451 case Instruction::Call
: {
452 CallInst
*CI
= cast
<CallInst
>(UserInst
);
453 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
454 for (unsigned i
= 0, e
= CI
->getNumArgOperands(); i
!= e
; ++i
) {
455 if (hasVectorInstrinsicScalarOpd(ID
, i
))
456 return (CI
->getArgOperand(i
) == Scalar
);
465 /// \returns the AA location that is being access by the instruction.
466 static MemoryLocation
getLocation(Instruction
*I
, AliasAnalysis
*AA
) {
467 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
))
468 return MemoryLocation::get(SI
);
469 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
))
470 return MemoryLocation::get(LI
);
471 return MemoryLocation();
474 /// \returns True if the instruction is not a volatile or atomic load/store.
475 static bool isSimple(Instruction
*I
) {
476 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(I
))
477 return LI
->isSimple();
478 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(I
))
479 return SI
->isSimple();
480 if (MemIntrinsic
*MI
= dyn_cast
<MemIntrinsic
>(I
))
481 return !MI
->isVolatile();
487 namespace slpvectorizer
{
489 /// Bottom Up SLP Vectorizer.
495 using ValueList
= SmallVector
<Value
*, 8>;
496 using InstrList
= SmallVector
<Instruction
*, 16>;
497 using ValueSet
= SmallPtrSet
<Value
*, 16>;
498 using StoreList
= SmallVector
<StoreInst
*, 8>;
499 using ExtraValueToDebugLocsMap
=
500 MapVector
<Value
*, SmallVector
<Instruction
*, 2>>;
502 BoUpSLP(Function
*Func
, ScalarEvolution
*Se
, TargetTransformInfo
*Tti
,
503 TargetLibraryInfo
*TLi
, AliasAnalysis
*Aa
, LoopInfo
*Li
,
504 DominatorTree
*Dt
, AssumptionCache
*AC
, DemandedBits
*DB
,
505 const DataLayout
*DL
, OptimizationRemarkEmitter
*ORE
)
506 : F(Func
), SE(Se
), TTI(Tti
), TLI(TLi
), AA(Aa
), LI(Li
), DT(Dt
), AC(AC
),
507 DB(DB
), DL(DL
), ORE(ORE
), Builder(Se
->getContext()) {
508 CodeMetrics::collectEphemeralValues(F
, AC
, EphValues
);
509 // Use the vector register size specified by the target unless overridden
510 // by a command-line option.
511 // TODO: It would be better to limit the vectorization factor based on
512 // data type rather than just register size. For example, x86 AVX has
513 // 256-bit registers, but it does not support integer operations
514 // at that width (that requires AVX2).
515 if (MaxVectorRegSizeOption
.getNumOccurrences())
516 MaxVecRegSize
= MaxVectorRegSizeOption
;
518 MaxVecRegSize
= TTI
->getRegisterBitWidth(true);
520 if (MinVectorRegSizeOption
.getNumOccurrences())
521 MinVecRegSize
= MinVectorRegSizeOption
;
523 MinVecRegSize
= TTI
->getMinVectorRegisterBitWidth();
526 /// Vectorize the tree that starts with the elements in \p VL.
527 /// Returns the vectorized root.
528 Value
*vectorizeTree();
530 /// Vectorize the tree but with the list of externally used values \p
531 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
532 /// generated extractvalue instructions.
533 Value
*vectorizeTree(ExtraValueToDebugLocsMap
&ExternallyUsedValues
);
535 /// \returns the cost incurred by unwanted spills and fills, caused by
536 /// holding live values over call sites.
537 int getSpillCost() const;
539 /// \returns the vectorization cost of the subtree that starts at \p VL.
540 /// A negative number means that this is profitable.
543 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
544 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
545 void buildTree(ArrayRef
<Value
*> Roots
,
546 ArrayRef
<Value
*> UserIgnoreLst
= None
);
548 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
549 /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
550 /// into account (anf updating it, if required) list of externally used
551 /// values stored in \p ExternallyUsedValues.
552 void buildTree(ArrayRef
<Value
*> Roots
,
553 ExtraValueToDebugLocsMap
&ExternallyUsedValues
,
554 ArrayRef
<Value
*> UserIgnoreLst
= None
);
556 /// Clear the internal data structures that are created by 'buildTree'.
558 VectorizableTree
.clear();
559 ScalarToTreeEntry
.clear();
561 ExternalUses
.clear();
562 NumOpsWantToKeepOrder
.clear();
563 NumOpsWantToKeepOriginalOrder
= 0;
564 for (auto &Iter
: BlocksSchedules
) {
565 BlockScheduling
*BS
= Iter
.second
.get();
571 unsigned getTreeSize() const { return VectorizableTree
.size(); }
573 /// Perform LICM and CSE on the newly generated gather sequences.
574 void optimizeGatherSequence();
576 /// \returns The best order of instructions for vectorization.
577 Optional
<ArrayRef
<unsigned>> bestOrder() const {
578 auto I
= std::max_element(
579 NumOpsWantToKeepOrder
.begin(), NumOpsWantToKeepOrder
.end(),
580 [](const decltype(NumOpsWantToKeepOrder
)::value_type
&D1
,
581 const decltype(NumOpsWantToKeepOrder
)::value_type
&D2
) {
582 return D1
.second
< D2
.second
;
584 if (I
== NumOpsWantToKeepOrder
.end() ||
585 I
->getSecond() <= NumOpsWantToKeepOriginalOrder
)
588 return makeArrayRef(I
->getFirst());
591 /// \return The vector element size in bits to use when vectorizing the
592 /// expression tree ending at \p V. If V is a store, the size is the width of
593 /// the stored value. Otherwise, the size is the width of the largest loaded
594 /// value reaching V. This method is used by the vectorizer to calculate
595 /// vectorization factors.
596 unsigned getVectorElementSize(Value
*V
) const;
598 /// Compute the minimum type sizes required to represent the entries in a
599 /// vectorizable tree.
600 void computeMinimumValueSizes();
602 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
603 unsigned getMaxVecRegSize() const {
604 return MaxVecRegSize
;
607 // \returns minimum vector register size as set by cl::opt.
608 unsigned getMinVecRegSize() const {
609 return MinVecRegSize
;
612 /// Check if ArrayType or StructType is isomorphic to some VectorType.
614 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
615 unsigned canMapToVector(Type
*T
, const DataLayout
&DL
) const;
617 /// \returns True if the VectorizableTree is both tiny and not fully
618 /// vectorizable. We do not vectorize such trees.
619 bool isTreeTinyAndNotFullyVectorizable() const;
621 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
622 /// can be load combined in the backend. Load combining may not be allowed in
623 /// the IR optimizer, so we do not want to alter the pattern. For example,
624 /// partially transforming a scalar bswap() pattern into vector code is
625 /// effectively impossible for the backend to undo.
626 /// TODO: If load combining is allowed in the IR optimizer, this analysis
627 /// may not be necessary.
628 bool isLoadCombineReductionCandidate(unsigned ReductionOpcode
) const;
630 OptimizationRemarkEmitter
*getORE() { return ORE
; }
632 /// This structure holds any data we need about the edges being traversed
633 /// during buildTree_rec(). We keep track of:
634 /// (i) the user TreeEntry index, and
635 /// (ii) the index of the edge.
637 EdgeInfo() = default;
638 EdgeInfo(TreeEntry
*UserTE
, unsigned EdgeIdx
)
639 : UserTE(UserTE
), EdgeIdx(EdgeIdx
) {}
640 /// The user TreeEntry.
641 TreeEntry
*UserTE
= nullptr;
642 /// The operand index of the use.
643 unsigned EdgeIdx
= UINT_MAX
;
645 friend inline raw_ostream
&operator<<(raw_ostream
&OS
,
646 const BoUpSLP::EdgeInfo
&EI
) {
651 void dump(raw_ostream
&OS
) const {
652 OS
<< "{User:" << (UserTE
? std::to_string(UserTE
->Idx
) : "null")
653 << " EdgeIdx:" << EdgeIdx
<< "}";
655 LLVM_DUMP_METHOD
void dump() const { dump(dbgs()); }
659 /// A helper data structure to hold the operands of a vector of instructions.
660 /// This supports a fixed vector length for all operand vectors.
662 /// For each operand we need (i) the value, and (ii) the opcode that it
663 /// would be attached to if the expression was in a left-linearized form.
664 /// This is required to avoid illegal operand reordering.
669 /// Op1 Op2 Linearized + Op2
670 /// \ / ----------> |/
673 /// Op1 - Op2 (0 + Op1) - Op2
676 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
678 /// Another way to think of this is to track all the operations across the
679 /// path from the operand all the way to the root of the tree and to
680 /// calculate the operation that corresponds to this path. For example, the
681 /// path from Op2 to the root crosses the RHS of the '-', therefore the
682 /// corresponding operation is a '-' (which matches the one in the
683 /// linearized tree, as shown above).
685 /// For lack of a better term, we refer to this operation as Accumulated
686 /// Path Operation (APO).
688 OperandData() = default;
689 OperandData(Value
*V
, bool APO
, bool IsUsed
)
690 : V(V
), APO(APO
), IsUsed(IsUsed
) {}
691 /// The operand value.
693 /// TreeEntries only allow a single opcode, or an alternate sequence of
694 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
695 /// APO. It is set to 'true' if 'V' is attached to an inverse operation
696 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
699 /// Helper data for the reordering function.
703 /// During operand reordering, we are trying to select the operand at lane
704 /// that matches best with the operand at the neighboring lane. Our
705 /// selection is based on the type of value we are looking for. For example,
706 /// if the neighboring lane has a load, we need to look for a load that is
707 /// accessing a consecutive address. These strategies are summarized in the
708 /// 'ReorderingMode' enumerator.
709 enum class ReorderingMode
{
710 Load
, ///< Matching loads to consecutive memory addresses
711 Opcode
, ///< Matching instructions based on opcode (same or alternate)
712 Constant
, ///< Matching constants
713 Splat
, ///< Matching the same instruction multiple times (broadcast)
714 Failed
, ///< We failed to create a vectorizable group
717 using OperandDataVec
= SmallVector
<OperandData
, 2>;
719 /// A vector of operand vectors.
720 SmallVector
<OperandDataVec
, 4> OpsVec
;
722 const DataLayout
&DL
;
725 /// \returns the operand data at \p OpIdx and \p Lane.
726 OperandData
&getData(unsigned OpIdx
, unsigned Lane
) {
727 return OpsVec
[OpIdx
][Lane
];
730 /// \returns the operand data at \p OpIdx and \p Lane. Const version.
731 const OperandData
&getData(unsigned OpIdx
, unsigned Lane
) const {
732 return OpsVec
[OpIdx
][Lane
];
735 /// Clears the used flag for all entries.
737 for (unsigned OpIdx
= 0, NumOperands
= getNumOperands();
738 OpIdx
!= NumOperands
; ++OpIdx
)
739 for (unsigned Lane
= 0, NumLanes
= getNumLanes(); Lane
!= NumLanes
;
741 OpsVec
[OpIdx
][Lane
].IsUsed
= false;
744 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
745 void swap(unsigned OpIdx1
, unsigned OpIdx2
, unsigned Lane
) {
746 std::swap(OpsVec
[OpIdx1
][Lane
], OpsVec
[OpIdx2
][Lane
]);
749 // Search all operands in Ops[*][Lane] for the one that matches best
750 // Ops[OpIdx][LastLane] and return its opreand index.
751 // If no good match can be found, return None.
753 getBestOperand(unsigned OpIdx
, int Lane
, int LastLane
,
754 ArrayRef
<ReorderingMode
> ReorderingModes
) {
755 unsigned NumOperands
= getNumOperands();
757 // The operand of the previous lane at OpIdx.
758 Value
*OpLastLane
= getData(OpIdx
, LastLane
).V
;
760 // Our strategy mode for OpIdx.
761 ReorderingMode RMode
= ReorderingModes
[OpIdx
];
763 // The linearized opcode of the operand at OpIdx, Lane.
764 bool OpIdxAPO
= getData(OpIdx
, Lane
).APO
;
766 const unsigned BestScore
= 2;
767 const unsigned GoodScore
= 1;
769 // The best operand index and its score.
770 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
771 // are using the score to differentiate between the two.
773 Optional
<unsigned> Idx
= None
;
777 // Iterate through all unused operands and look for the best.
778 for (unsigned Idx
= 0; Idx
!= NumOperands
; ++Idx
) {
779 // Get the operand at Idx and Lane.
780 OperandData
&OpData
= getData(Idx
, Lane
);
781 Value
*Op
= OpData
.V
;
782 bool OpAPO
= OpData
.APO
;
784 // Skip already selected operands.
788 // Skip if we are trying to move the operand to a position with a
789 // different opcode in the linearized tree form. This would break the
791 if (OpAPO
!= OpIdxAPO
)
794 // Look for an operand that matches the current mode.
796 case ReorderingMode::Load
:
797 if (isa
<LoadInst
>(Op
)) {
798 // Figure out which is left and right, so that we can check for
800 bool LeftToRight
= Lane
> LastLane
;
801 Value
*OpLeft
= (LeftToRight
) ? OpLastLane
: Op
;
802 Value
*OpRight
= (LeftToRight
) ? Op
: OpLastLane
;
803 if (isConsecutiveAccess(cast
<LoadInst
>(OpLeft
),
804 cast
<LoadInst
>(OpRight
), DL
, SE
))
808 case ReorderingMode::Opcode
:
809 // We accept both Instructions and Undefs, but with different scores.
810 if ((isa
<Instruction
>(Op
) && isa
<Instruction
>(OpLastLane
) &&
811 cast
<Instruction
>(Op
)->getOpcode() ==
812 cast
<Instruction
>(OpLastLane
)->getOpcode()) ||
813 (isa
<UndefValue
>(OpLastLane
) && isa
<Instruction
>(Op
)) ||
814 isa
<UndefValue
>(Op
)) {
815 // An instruction has a higher score than an undef.
816 unsigned Score
= (isa
<UndefValue
>(Op
)) ? GoodScore
: BestScore
;
817 if (Score
> BestOp
.Score
) {
819 BestOp
.Score
= Score
;
823 case ReorderingMode::Constant
:
824 if (isa
<Constant
>(Op
)) {
825 unsigned Score
= (isa
<UndefValue
>(Op
)) ? GoodScore
: BestScore
;
826 if (Score
> BestOp
.Score
) {
828 BestOp
.Score
= Score
;
832 case ReorderingMode::Splat
:
833 if (Op
== OpLastLane
)
836 case ReorderingMode::Failed
:
842 getData(BestOp
.Idx
.getValue(), Lane
).IsUsed
= true;
845 // If we could not find a good match return None.
849 /// Helper for reorderOperandVecs. \Returns the lane that we should start
850 /// reordering from. This is the one which has the least number of operands
851 /// that can freely move about.
852 unsigned getBestLaneToStartReordering() const {
853 unsigned BestLane
= 0;
854 unsigned Min
= UINT_MAX
;
855 for (unsigned Lane
= 0, NumLanes
= getNumLanes(); Lane
!= NumLanes
;
857 unsigned NumFreeOps
= getMaxNumOperandsThatCanBeReordered(Lane
);
858 if (NumFreeOps
< Min
) {
866 /// \Returns the maximum number of operands that are allowed to be reordered
867 /// for \p Lane. This is used as a heuristic for selecting the first lane to
868 /// start operand reordering.
869 unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane
) const {
870 unsigned CntTrue
= 0;
871 unsigned NumOperands
= getNumOperands();
872 // Operands with the same APO can be reordered. We therefore need to count
873 // how many of them we have for each APO, like this: Cnt[APO] = x.
874 // Since we only have two APOs, namely true and false, we can avoid using
875 // a map. Instead we can simply count the number of operands that
876 // correspond to one of them (in this case the 'true' APO), and calculate
877 // the other by subtracting it from the total number of operands.
878 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
)
879 if (getData(OpIdx
, Lane
).APO
)
881 unsigned CntFalse
= NumOperands
- CntTrue
;
882 return std::max(CntTrue
, CntFalse
);
885 /// Go through the instructions in VL and append their operands.
886 void appendOperandsOfVL(ArrayRef
<Value
*> VL
) {
887 assert(!VL
.empty() && "Bad VL");
888 assert((empty() || VL
.size() == getNumLanes()) &&
889 "Expected same number of lanes");
890 assert(isa
<Instruction
>(VL
[0]) && "Expected instruction");
891 unsigned NumOperands
= cast
<Instruction
>(VL
[0])->getNumOperands();
892 OpsVec
.resize(NumOperands
);
893 unsigned NumLanes
= VL
.size();
894 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
) {
895 OpsVec
[OpIdx
].resize(NumLanes
);
896 for (unsigned Lane
= 0; Lane
!= NumLanes
; ++Lane
) {
897 assert(isa
<Instruction
>(VL
[Lane
]) && "Expected instruction");
898 // Our tree has just 3 nodes: the root and two operands.
899 // It is therefore trivial to get the APO. We only need to check the
900 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
901 // RHS operand. The LHS operand of both add and sub is never attached
902 // to an inversese operation in the linearized form, therefore its APO
903 // is false. The RHS is true only if VL[Lane] is an inverse operation.
905 // Since operand reordering is performed on groups of commutative
906 // operations or alternating sequences (e.g., +, -), we can safely
907 // tell the inverse operations by checking commutativity.
908 bool IsInverseOperation
= !isCommutative(cast
<Instruction
>(VL
[Lane
]));
909 bool APO
= (OpIdx
== 0) ? false : IsInverseOperation
;
910 OpsVec
[OpIdx
][Lane
] = {cast
<Instruction
>(VL
[Lane
])->getOperand(OpIdx
),
916 /// \returns the number of operands.
917 unsigned getNumOperands() const { return OpsVec
.size(); }
919 /// \returns the number of lanes.
920 unsigned getNumLanes() const { return OpsVec
[0].size(); }
922 /// \returns the operand value at \p OpIdx and \p Lane.
923 Value
*getValue(unsigned OpIdx
, unsigned Lane
) const {
924 return getData(OpIdx
, Lane
).V
;
927 /// \returns true if the data structure is empty.
928 bool empty() const { return OpsVec
.empty(); }
931 void clear() { OpsVec
.clear(); }
933 /// \Returns true if there are enough operands identical to \p Op to fill
934 /// the whole vector.
935 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
936 bool shouldBroadcast(Value
*Op
, unsigned OpIdx
, unsigned Lane
) {
937 bool OpAPO
= getData(OpIdx
, Lane
).APO
;
938 for (unsigned Ln
= 0, Lns
= getNumLanes(); Ln
!= Lns
; ++Ln
) {
941 // This is set to true if we found a candidate for broadcast at Lane.
942 bool FoundCandidate
= false;
943 for (unsigned OpI
= 0, OpE
= getNumOperands(); OpI
!= OpE
; ++OpI
) {
944 OperandData
&Data
= getData(OpI
, Ln
);
945 if (Data
.APO
!= OpAPO
|| Data
.IsUsed
)
948 FoundCandidate
= true;
960 /// Initialize with all the operands of the instruction vector \p RootVL.
961 VLOperands(ArrayRef
<Value
*> RootVL
, const DataLayout
&DL
,
964 // Append all the operands of RootVL.
965 appendOperandsOfVL(RootVL
);
968 /// \Returns a value vector with the operands across all lanes for the
969 /// opearnd at \p OpIdx.
970 ValueList
getVL(unsigned OpIdx
) const {
971 ValueList
OpVL(OpsVec
[OpIdx
].size());
972 assert(OpsVec
[OpIdx
].size() == getNumLanes() &&
973 "Expected same num of lanes across all operands");
974 for (unsigned Lane
= 0, Lanes
= getNumLanes(); Lane
!= Lanes
; ++Lane
)
975 OpVL
[Lane
] = OpsVec
[OpIdx
][Lane
].V
;
979 // Performs operand reordering for 2 or more operands.
980 // The original operands are in OrigOps[OpIdx][Lane].
981 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
983 unsigned NumOperands
= getNumOperands();
984 unsigned NumLanes
= getNumLanes();
985 // Each operand has its own mode. We are using this mode to help us select
986 // the instructions for each lane, so that they match best with the ones
987 // we have selected so far.
988 SmallVector
<ReorderingMode
, 2> ReorderingModes(NumOperands
);
990 // This is a greedy single-pass algorithm. We are going over each lane
991 // once and deciding on the best order right away with no back-tracking.
992 // However, in order to increase its effectiveness, we start with the lane
993 // that has operands that can move the least. For example, given the
995 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
996 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
997 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
998 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
999 // we will start at Lane 1, since the operands of the subtraction cannot
1000 // be reordered. Then we will visit the rest of the lanes in a circular
1001 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1003 // Find the first lane that we will start our search from.
1004 unsigned FirstLane
= getBestLaneToStartReordering();
1006 // Initialize the modes.
1007 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
) {
1008 Value
*OpLane0
= getValue(OpIdx
, FirstLane
);
1009 // Keep track if we have instructions with all the same opcode on one
1011 if (isa
<LoadInst
>(OpLane0
))
1012 ReorderingModes
[OpIdx
] = ReorderingMode::Load
;
1013 else if (isa
<Instruction
>(OpLane0
)) {
1014 // Check if OpLane0 should be broadcast.
1015 if (shouldBroadcast(OpLane0
, OpIdx
, FirstLane
))
1016 ReorderingModes
[OpIdx
] = ReorderingMode::Splat
;
1018 ReorderingModes
[OpIdx
] = ReorderingMode::Opcode
;
1020 else if (isa
<Constant
>(OpLane0
))
1021 ReorderingModes
[OpIdx
] = ReorderingMode::Constant
;
1022 else if (isa
<Argument
>(OpLane0
))
1023 // Our best hope is a Splat. It may save some cost in some cases.
1024 ReorderingModes
[OpIdx
] = ReorderingMode::Splat
;
1026 // NOTE: This should be unreachable.
1027 ReorderingModes
[OpIdx
] = ReorderingMode::Failed
;
1030 // If the initial strategy fails for any of the operand indexes, then we
1031 // perform reordering again in a second pass. This helps avoid assigning
1032 // high priority to the failed strategy, and should improve reordering for
1033 // the non-failed operand indexes.
1034 for (int Pass
= 0; Pass
!= 2; ++Pass
) {
1035 // Skip the second pass if the first pass did not fail.
1036 bool StrategyFailed
= false;
1037 // Mark all operand data as free to use.
1039 // We keep the original operand order for the FirstLane, so reorder the
1040 // rest of the lanes. We are visiting the nodes in a circular fashion,
1041 // using FirstLane as the center point and increasing the radius
1043 for (unsigned Distance
= 1; Distance
!= NumLanes
; ++Distance
) {
1044 // Visit the lane on the right and then the lane on the left.
1045 for (int Direction
: {+1, -1}) {
1046 int Lane
= FirstLane
+ Direction
* Distance
;
1047 if (Lane
< 0 || Lane
>= (int)NumLanes
)
1049 int LastLane
= Lane
- Direction
;
1050 assert(LastLane
>= 0 && LastLane
< (int)NumLanes
&&
1052 // Look for a good match for each operand.
1053 for (unsigned OpIdx
= 0; OpIdx
!= NumOperands
; ++OpIdx
) {
1054 // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1055 Optional
<unsigned> BestIdx
=
1056 getBestOperand(OpIdx
, Lane
, LastLane
, ReorderingModes
);
1057 // By not selecting a value, we allow the operands that follow to
1058 // select a better matching value. We will get a non-null value in
1059 // the next run of getBestOperand().
1061 // Swap the current operand with the one returned by
1062 // getBestOperand().
1063 swap(OpIdx
, BestIdx
.getValue(), Lane
);
1065 // We failed to find a best operand, set mode to 'Failed'.
1066 ReorderingModes
[OpIdx
] = ReorderingMode::Failed
;
1067 // Enable the second pass.
1068 StrategyFailed
= true;
1073 // Skip second pass if the strategy did not fail.
1074 if (!StrategyFailed
)
1079 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 LLVM_DUMP_METHOD
static StringRef
getModeStr(ReorderingMode RMode
) {
1082 case ReorderingMode::Load
:
1084 case ReorderingMode::Opcode
:
1086 case ReorderingMode::Constant
:
1088 case ReorderingMode::Splat
:
1090 case ReorderingMode::Failed
:
1093 llvm_unreachable("Unimplemented Reordering Type");
1096 LLVM_DUMP_METHOD
static raw_ostream
&printMode(ReorderingMode RMode
,
1098 return OS
<< getModeStr(RMode
);
1102 LLVM_DUMP_METHOD
static void dumpMode(ReorderingMode RMode
) {
1103 printMode(RMode
, dbgs());
1106 friend raw_ostream
&operator<<(raw_ostream
&OS
, ReorderingMode RMode
) {
1107 return printMode(RMode
, OS
);
1110 LLVM_DUMP_METHOD raw_ostream
&print(raw_ostream
&OS
) const {
1111 const unsigned Indent
= 2;
1113 for (const OperandDataVec
&OpDataVec
: OpsVec
) {
1114 OS
<< "Operand " << Cnt
++ << "\n";
1115 for (const OperandData
&OpData
: OpDataVec
) {
1116 OS
.indent(Indent
) << "{";
1117 if (Value
*V
= OpData
.V
)
1121 OS
<< ", APO:" << OpData
.APO
<< "}\n";
1129 LLVM_DUMP_METHOD
void dump() const { print(dbgs()); }
1133 /// Checks if the instruction is marked for deletion.
1134 bool isDeleted(Instruction
*I
) const { return DeletedInstructions
.count(I
); }
1136 /// Marks values operands for later deletion by replacing them with Undefs.
1137 void eraseInstructions(ArrayRef
<Value
*> AV
);
1142 /// Checks if all users of \p I are the part of the vectorization tree.
1143 bool areAllUsersVectorized(Instruction
*I
) const;
1145 /// \returns the cost of the vectorizable entry.
1146 int getEntryCost(TreeEntry
*E
);
1148 /// This is the recursive part of buildTree.
1149 void buildTree_rec(ArrayRef
<Value
*> Roots
, unsigned Depth
,
1150 const EdgeInfo
&EI
);
1152 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1153 /// be vectorized to use the original vector (or aggregate "bitcast" to a
1154 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1155 /// returns false, setting \p CurrentOrder to either an empty vector or a
1156 /// non-identity permutation that allows to reuse extract instructions.
1157 bool canReuseExtract(ArrayRef
<Value
*> VL
, Value
*OpValue
,
1158 SmallVectorImpl
<unsigned> &CurrentOrder
) const;
1160 /// Vectorize a single entry in the tree.
1161 Value
*vectorizeTree(TreeEntry
*E
);
1163 /// Vectorize a single entry in the tree, starting in \p VL.
1164 Value
*vectorizeTree(ArrayRef
<Value
*> VL
);
1166 /// \returns the scalarization cost for this type. Scalarization in this
1167 /// context means the creation of vectors from a group of scalars.
1168 int getGatherCost(Type
*Ty
, const DenseSet
<unsigned> &ShuffledIndices
) const;
1170 /// \returns the scalarization cost for this list of values. Assuming that
1171 /// this subtree gets vectorized, we may need to extract the values from the
1172 /// roots. This method calculates the cost of extracting the values.
1173 int getGatherCost(ArrayRef
<Value
*> VL
) const;
1175 /// Set the Builder insert point to one after the last instruction in
1177 void setInsertPointAfterBundle(TreeEntry
*E
);
1179 /// \returns a vector from a collection of scalars in \p VL.
1180 Value
*Gather(ArrayRef
<Value
*> VL
, VectorType
*Ty
);
1182 /// \returns whether the VectorizableTree is fully vectorizable and will
1183 /// be beneficial even the tree height is tiny.
1184 bool isFullyVectorizableTinyTree() const;
1186 /// Reorder commutative or alt operands to get better probability of
1187 /// generating vectorized code.
1188 static void reorderInputsAccordingToOpcode(ArrayRef
<Value
*> VL
,
1189 SmallVectorImpl
<Value
*> &Left
,
1190 SmallVectorImpl
<Value
*> &Right
,
1191 const DataLayout
&DL
,
1192 ScalarEvolution
&SE
);
1194 using VecTreeTy
= SmallVector
<std::unique_ptr
<TreeEntry
>, 8>;
1195 TreeEntry(VecTreeTy
&Container
) : Container(Container
) {}
1197 /// \returns true if the scalars in VL are equal to this entry.
1198 bool isSame(ArrayRef
<Value
*> VL
) const {
1199 if (VL
.size() == Scalars
.size())
1200 return std::equal(VL
.begin(), VL
.end(), Scalars
.begin());
1201 return VL
.size() == ReuseShuffleIndices
.size() &&
1203 VL
.begin(), VL
.end(), ReuseShuffleIndices
.begin(),
1204 [this](Value
*V
, unsigned Idx
) { return V
== Scalars
[Idx
]; });
1207 /// A vector of scalars.
1210 /// The Scalars are vectorized into this value. It is initialized to Null.
1211 Value
*VectorizedValue
= nullptr;
1213 /// Do we need to gather this sequence ?
1214 bool NeedToGather
= false;
1216 /// Does this sequence require some shuffling?
1217 SmallVector
<unsigned, 4> ReuseShuffleIndices
;
1219 /// Does this entry require reordering?
1220 ArrayRef
<unsigned> ReorderIndices
;
1222 /// Points back to the VectorizableTree.
1224 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
1225 /// to be a pointer and needs to be able to initialize the child iterator.
1226 /// Thus we need a reference back to the container to translate the indices
1228 VecTreeTy
&Container
;
1230 /// The TreeEntry index containing the user of this entry. We can actually
1231 /// have multiple users so the data structure is not truly a tree.
1232 SmallVector
<EdgeInfo
, 1> UserTreeIndices
;
1234 /// The index of this treeEntry in VectorizableTree.
1238 /// The operands of each instruction in each lane Operands[op_index][lane].
1239 /// Note: This helps avoid the replication of the code that performs the
1240 /// reordering of operands during buildTree_rec() and vectorizeTree().
1241 SmallVector
<ValueList
, 2> Operands
;
1243 /// The main/alternate instruction.
1244 Instruction
*MainOp
= nullptr;
1245 Instruction
*AltOp
= nullptr;
1248 /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1249 void setOperand(unsigned OpIdx
, ArrayRef
<Value
*> OpVL
) {
1250 if (Operands
.size() < OpIdx
+ 1)
1251 Operands
.resize(OpIdx
+ 1);
1252 assert(Operands
[OpIdx
].size() == 0 && "Already resized?");
1253 Operands
[OpIdx
].resize(Scalars
.size());
1254 for (unsigned Lane
= 0, E
= Scalars
.size(); Lane
!= E
; ++Lane
)
1255 Operands
[OpIdx
][Lane
] = OpVL
[Lane
];
1258 /// Set the operands of this bundle in their original order.
1259 void setOperandsInOrder() {
1260 assert(Operands
.empty() && "Already initialized?");
1261 auto *I0
= cast
<Instruction
>(Scalars
[0]);
1262 Operands
.resize(I0
->getNumOperands());
1263 unsigned NumLanes
= Scalars
.size();
1264 for (unsigned OpIdx
= 0, NumOperands
= I0
->getNumOperands();
1265 OpIdx
!= NumOperands
; ++OpIdx
) {
1266 Operands
[OpIdx
].resize(NumLanes
);
1267 for (unsigned Lane
= 0; Lane
!= NumLanes
; ++Lane
) {
1268 auto *I
= cast
<Instruction
>(Scalars
[Lane
]);
1269 assert(I
->getNumOperands() == NumOperands
&&
1270 "Expected same number of operands");
1271 Operands
[OpIdx
][Lane
] = I
->getOperand(OpIdx
);
1276 /// \returns the \p OpIdx operand of this TreeEntry.
1277 ValueList
&getOperand(unsigned OpIdx
) {
1278 assert(OpIdx
< Operands
.size() && "Off bounds");
1279 return Operands
[OpIdx
];
1282 /// \returns the number of operands.
1283 unsigned getNumOperands() const { return Operands
.size(); }
1285 /// \return the single \p OpIdx operand.
1286 Value
*getSingleOperand(unsigned OpIdx
) const {
1287 assert(OpIdx
< Operands
.size() && "Off bounds");
1288 assert(!Operands
[OpIdx
].empty() && "No operand available");
1289 return Operands
[OpIdx
][0];
1292 /// Some of the instructions in the list have alternate opcodes.
1293 bool isAltShuffle() const {
1294 return getOpcode() != getAltOpcode();
1297 bool isOpcodeOrAlt(Instruction
*I
) const {
1298 unsigned CheckedOpcode
= I
->getOpcode();
1299 return (getOpcode() == CheckedOpcode
||
1300 getAltOpcode() == CheckedOpcode
);
1303 /// Chooses the correct key for scheduling data. If \p Op has the same (or
1304 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
1306 Value
*isOneOf(Value
*Op
) const {
1307 auto *I
= dyn_cast
<Instruction
>(Op
);
1308 if (I
&& isOpcodeOrAlt(I
))
1313 void setOperations(const InstructionsState
&S
) {
1318 Instruction
*getMainOp() const {
1322 Instruction
*getAltOp() const {
1326 /// The main/alternate opcodes for the list of instructions.
1327 unsigned getOpcode() const {
1328 return MainOp
? MainOp
->getOpcode() : 0;
1331 unsigned getAltOpcode() const {
1332 return AltOp
? AltOp
->getOpcode() : 0;
1335 /// Update operations state of this entry if reorder occurred.
1336 bool updateStateIfReorder() {
1337 if (ReorderIndices
.empty())
1339 InstructionsState S
= getSameOpcode(Scalars
, ReorderIndices
.front());
1346 LLVM_DUMP_METHOD
void dump() const {
1347 dbgs() << Idx
<< ".\n";
1348 for (unsigned OpI
= 0, OpE
= Operands
.size(); OpI
!= OpE
; ++OpI
) {
1349 dbgs() << "Operand " << OpI
<< ":\n";
1350 for (const Value
*V
: Operands
[OpI
])
1351 dbgs().indent(2) << *V
<< "\n";
1353 dbgs() << "Scalars: \n";
1354 for (Value
*V
: Scalars
)
1355 dbgs().indent(2) << *V
<< "\n";
1356 dbgs() << "NeedToGather: " << NeedToGather
<< "\n";
1357 dbgs() << "MainOp: " << *MainOp
<< "\n";
1358 dbgs() << "AltOp: " << *AltOp
<< "\n";
1359 dbgs() << "VectorizedValue: ";
1360 if (VectorizedValue
)
1361 dbgs() << *VectorizedValue
;
1365 dbgs() << "ReuseShuffleIndices: ";
1366 if (ReuseShuffleIndices
.empty())
1369 for (unsigned ReuseIdx
: ReuseShuffleIndices
)
1370 dbgs() << ReuseIdx
<< ", ";
1372 dbgs() << "ReorderIndices: ";
1373 for (unsigned ReorderIdx
: ReorderIndices
)
1374 dbgs() << ReorderIdx
<< ", ";
1376 dbgs() << "UserTreeIndices: ";
1377 for (const auto &EInfo
: UserTreeIndices
)
1378 dbgs() << EInfo
<< ", ";
1384 /// Create a new VectorizableTree entry.
1385 TreeEntry
*newTreeEntry(ArrayRef
<Value
*> VL
, Optional
<ScheduleData
*> Bundle
,
1386 const InstructionsState
&S
,
1387 const EdgeInfo
&UserTreeIdx
,
1388 ArrayRef
<unsigned> ReuseShuffleIndices
= None
,
1389 ArrayRef
<unsigned> ReorderIndices
= None
) {
1390 bool Vectorized
= (bool)Bundle
;
1391 VectorizableTree
.push_back(std::make_unique
<TreeEntry
>(VectorizableTree
));
1392 TreeEntry
*Last
= VectorizableTree
.back().get();
1393 Last
->Idx
= VectorizableTree
.size() - 1;
1394 Last
->Scalars
.insert(Last
->Scalars
.begin(), VL
.begin(), VL
.end());
1395 Last
->NeedToGather
= !Vectorized
;
1396 Last
->ReuseShuffleIndices
.append(ReuseShuffleIndices
.begin(),
1397 ReuseShuffleIndices
.end());
1398 Last
->ReorderIndices
= ReorderIndices
;
1399 Last
->setOperations(S
);
1401 for (int i
= 0, e
= VL
.size(); i
!= e
; ++i
) {
1402 assert(!getTreeEntry(VL
[i
]) && "Scalar already in tree!");
1403 ScalarToTreeEntry
[VL
[i
]] = Last
;
1405 // Update the scheduler bundle to point to this TreeEntry.
1407 for (ScheduleData
*BundleMember
= Bundle
.getValue(); BundleMember
;
1408 BundleMember
= BundleMember
->NextInBundle
) {
1409 BundleMember
->TE
= Last
;
1410 BundleMember
->Lane
= Lane
;
1413 assert((!Bundle
.getValue() || Lane
== VL
.size()) &&
1414 "Bundle and VL out of sync");
1416 MustGather
.insert(VL
.begin(), VL
.end());
1419 if (UserTreeIdx
.UserTE
)
1420 Last
->UserTreeIndices
.push_back(UserTreeIdx
);
1425 /// -- Vectorization State --
1426 /// Holds all of the tree entries.
1427 TreeEntry::VecTreeTy VectorizableTree
;
1431 LLVM_DUMP_METHOD
void dumpVectorizableTree() const {
1432 for (unsigned Id
= 0, IdE
= VectorizableTree
.size(); Id
!= IdE
; ++Id
) {
1433 VectorizableTree
[Id
]->dump();
1439 TreeEntry
*getTreeEntry(Value
*V
) {
1440 auto I
= ScalarToTreeEntry
.find(V
);
1441 if (I
!= ScalarToTreeEntry
.end())
1446 const TreeEntry
*getTreeEntry(Value
*V
) const {
1447 auto I
= ScalarToTreeEntry
.find(V
);
1448 if (I
!= ScalarToTreeEntry
.end())
1453 /// Maps a specific scalar to its tree entry.
1454 SmallDenseMap
<Value
*, TreeEntry
*> ScalarToTreeEntry
;
1456 /// A list of scalars that we found that we need to keep as scalars.
1457 ValueSet MustGather
;
1459 /// This POD struct describes one external user in the vectorized tree.
1460 struct ExternalUser
{
1461 ExternalUser(Value
*S
, llvm::User
*U
, int L
)
1462 : Scalar(S
), User(U
), Lane(L
) {}
1464 // Which scalar in our function.
1467 // Which user that uses the scalar.
1470 // Which lane does the scalar belong to.
1473 using UserList
= SmallVector
<ExternalUser
, 16>;
1475 /// Checks if two instructions may access the same memory.
1477 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
1478 /// is invariant in the calling loop.
1479 bool isAliased(const MemoryLocation
&Loc1
, Instruction
*Inst1
,
1480 Instruction
*Inst2
) {
1481 // First check if the result is already in the cache.
1482 AliasCacheKey key
= std::make_pair(Inst1
, Inst2
);
1483 Optional
<bool> &result
= AliasCache
[key
];
1484 if (result
.hasValue()) {
1485 return result
.getValue();
1487 MemoryLocation Loc2
= getLocation(Inst2
, AA
);
1488 bool aliased
= true;
1489 if (Loc1
.Ptr
&& Loc2
.Ptr
&& isSimple(Inst1
) && isSimple(Inst2
)) {
1490 // Do the alias check.
1491 aliased
= AA
->alias(Loc1
, Loc2
);
1493 // Store the result in the cache.
1498 using AliasCacheKey
= std::pair
<Instruction
*, Instruction
*>;
1500 /// Cache for alias results.
1501 /// TODO: consider moving this to the AliasAnalysis itself.
1502 DenseMap
<AliasCacheKey
, Optional
<bool>> AliasCache
;
1504 /// Removes an instruction from its block and eventually deletes it.
1505 /// It's like Instruction::eraseFromParent() except that the actual deletion
1506 /// is delayed until BoUpSLP is destructed.
1507 /// This is required to ensure that there are no incorrect collisions in the
1508 /// AliasCache, which can happen if a new instruction is allocated at the
1509 /// same address as a previously deleted instruction.
1510 void eraseInstruction(Instruction
*I
, bool ReplaceOpsWithUndef
= false) {
1511 auto It
= DeletedInstructions
.try_emplace(I
, ReplaceOpsWithUndef
).first
;
1512 It
->getSecond() = It
->getSecond() && ReplaceOpsWithUndef
;
1515 /// Temporary store for deleted instructions. Instructions will be deleted
1516 /// eventually when the BoUpSLP is destructed.
1517 DenseMap
<Instruction
*, bool> DeletedInstructions
;
1519 /// A list of values that need to extracted out of the tree.
1520 /// This list holds pairs of (Internal Scalar : External User). External User
1521 /// can be nullptr, it means that this Internal Scalar will be used later,
1522 /// after vectorization.
1523 UserList ExternalUses
;
1525 /// Values used only by @llvm.assume calls.
1526 SmallPtrSet
<const Value
*, 32> EphValues
;
1528 /// Holds all of the instructions that we gathered.
1529 SetVector
<Instruction
*> GatherSeq
;
1531 /// A list of blocks that we are going to CSE.
1532 SetVector
<BasicBlock
*> CSEBlocks
;
1534 /// Contains all scheduling relevant data for an instruction.
1535 /// A ScheduleData either represents a single instruction or a member of an
1536 /// instruction bundle (= a group of instructions which is combined into a
1537 /// vector instruction).
1538 struct ScheduleData
{
1539 // The initial value for the dependency counters. It means that the
1540 // dependencies are not calculated yet.
1541 enum { InvalidDeps
= -1 };
1543 ScheduleData() = default;
1545 void init(int BlockSchedulingRegionID
, Value
*OpVal
) {
1546 FirstInBundle
= this;
1547 NextInBundle
= nullptr;
1548 NextLoadStore
= nullptr;
1549 IsScheduled
= false;
1550 SchedulingRegionID
= BlockSchedulingRegionID
;
1551 UnscheduledDepsInBundle
= UnscheduledDeps
;
1552 clearDependencies();
1558 /// Returns true if the dependency information has been calculated.
1559 bool hasValidDependencies() const { return Dependencies
!= InvalidDeps
; }
1561 /// Returns true for single instructions and for bundle representatives
1562 /// (= the head of a bundle).
1563 bool isSchedulingEntity() const { return FirstInBundle
== this; }
1565 /// Returns true if it represents an instruction bundle and not only a
1566 /// single instruction.
1567 bool isPartOfBundle() const {
1568 return NextInBundle
!= nullptr || FirstInBundle
!= this;
1571 /// Returns true if it is ready for scheduling, i.e. it has no more
1572 /// unscheduled depending instructions/bundles.
1573 bool isReady() const {
1574 assert(isSchedulingEntity() &&
1575 "can't consider non-scheduling entity for ready list");
1576 return UnscheduledDepsInBundle
== 0 && !IsScheduled
;
1579 /// Modifies the number of unscheduled dependencies, also updating it for
1580 /// the whole bundle.
1581 int incrementUnscheduledDeps(int Incr
) {
1582 UnscheduledDeps
+= Incr
;
1583 return FirstInBundle
->UnscheduledDepsInBundle
+= Incr
;
1586 /// Sets the number of unscheduled dependencies to the number of
1588 void resetUnscheduledDeps() {
1589 incrementUnscheduledDeps(Dependencies
- UnscheduledDeps
);
1592 /// Clears all dependency information.
1593 void clearDependencies() {
1594 Dependencies
= InvalidDeps
;
1595 resetUnscheduledDeps();
1596 MemoryDependencies
.clear();
1599 void dump(raw_ostream
&os
) const {
1600 if (!isSchedulingEntity()) {
1601 os
<< "/ " << *Inst
;
1602 } else if (NextInBundle
) {
1604 ScheduleData
*SD
= NextInBundle
;
1606 os
<< ';' << *SD
->Inst
;
1607 SD
= SD
->NextInBundle
;
1615 Instruction
*Inst
= nullptr;
1617 /// Points to the head in an instruction bundle (and always to this for
1618 /// single instructions).
1619 ScheduleData
*FirstInBundle
= nullptr;
1621 /// Single linked list of all instructions in a bundle. Null if it is a
1622 /// single instruction.
1623 ScheduleData
*NextInBundle
= nullptr;
1625 /// Single linked list of all memory instructions (e.g. load, store, call)
1626 /// in the block - until the end of the scheduling region.
1627 ScheduleData
*NextLoadStore
= nullptr;
1629 /// The dependent memory instructions.
1630 /// This list is derived on demand in calculateDependencies().
1631 SmallVector
<ScheduleData
*, 4> MemoryDependencies
;
1633 /// This ScheduleData is in the current scheduling region if this matches
1634 /// the current SchedulingRegionID of BlockScheduling.
1635 int SchedulingRegionID
= 0;
1637 /// Used for getting a "good" final ordering of instructions.
1638 int SchedulingPriority
= 0;
1640 /// The number of dependencies. Constitutes of the number of users of the
1641 /// instruction plus the number of dependent memory instructions (if any).
1642 /// This value is calculated on demand.
1643 /// If InvalidDeps, the number of dependencies is not calculated yet.
1644 int Dependencies
= InvalidDeps
;
1646 /// The number of dependencies minus the number of dependencies of scheduled
1647 /// instructions. As soon as this is zero, the instruction/bundle gets ready
1649 /// Note that this is negative as long as Dependencies is not calculated.
1650 int UnscheduledDeps
= InvalidDeps
;
1652 /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
1653 /// single instructions.
1654 int UnscheduledDepsInBundle
= InvalidDeps
;
1656 /// True if this instruction is scheduled (or considered as scheduled in the
1658 bool IsScheduled
= false;
1660 /// Opcode of the current instruction in the schedule data.
1661 Value
*OpValue
= nullptr;
1663 /// The TreeEntry that this instruction corresponds to.
1664 TreeEntry
*TE
= nullptr;
1666 /// The lane of this node in the TreeEntry.
1671 friend inline raw_ostream
&operator<<(raw_ostream
&os
,
1672 const BoUpSLP::ScheduleData
&SD
) {
1678 friend struct GraphTraits
<BoUpSLP
*>;
1679 friend struct DOTGraphTraits
<BoUpSLP
*>;
1681 /// Contains all scheduling data for a basic block.
1682 struct BlockScheduling
{
1683 BlockScheduling(BasicBlock
*BB
)
1684 : BB(BB
), ChunkSize(BB
->size()), ChunkPos(ChunkSize
) {}
1688 ScheduleStart
= nullptr;
1689 ScheduleEnd
= nullptr;
1690 FirstLoadStoreInRegion
= nullptr;
1691 LastLoadStoreInRegion
= nullptr;
1693 // Reduce the maximum schedule region size by the size of the
1694 // previous scheduling run.
1695 ScheduleRegionSizeLimit
-= ScheduleRegionSize
;
1696 if (ScheduleRegionSizeLimit
< MinScheduleRegionSize
)
1697 ScheduleRegionSizeLimit
= MinScheduleRegionSize
;
1698 ScheduleRegionSize
= 0;
1700 // Make a new scheduling region, i.e. all existing ScheduleData is not
1701 // in the new region yet.
1702 ++SchedulingRegionID
;
1705 ScheduleData
*getScheduleData(Value
*V
) {
1706 ScheduleData
*SD
= ScheduleDataMap
[V
];
1707 if (SD
&& SD
->SchedulingRegionID
== SchedulingRegionID
)
1712 ScheduleData
*getScheduleData(Value
*V
, Value
*Key
) {
1714 return getScheduleData(V
);
1715 auto I
= ExtraScheduleDataMap
.find(V
);
1716 if (I
!= ExtraScheduleDataMap
.end()) {
1717 ScheduleData
*SD
= I
->second
[Key
];
1718 if (SD
&& SD
->SchedulingRegionID
== SchedulingRegionID
)
1724 bool isInSchedulingRegion(ScheduleData
*SD
) {
1725 return SD
->SchedulingRegionID
== SchedulingRegionID
;
1728 /// Marks an instruction as scheduled and puts all dependent ready
1729 /// instructions into the ready-list.
1730 template <typename ReadyListType
>
1731 void schedule(ScheduleData
*SD
, ReadyListType
&ReadyList
) {
1732 SD
->IsScheduled
= true;
1733 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD
<< "\n");
1735 ScheduleData
*BundleMember
= SD
;
1736 while (BundleMember
) {
1737 if (BundleMember
->Inst
!= BundleMember
->OpValue
) {
1738 BundleMember
= BundleMember
->NextInBundle
;
1741 // Handle the def-use chain dependencies.
1743 // Decrement the unscheduled counter and insert to ready list if ready.
1744 auto &&DecrUnsched
= [this, &ReadyList
](Instruction
*I
) {
1745 doForAllOpcodes(I
, [&ReadyList
](ScheduleData
*OpDef
) {
1746 if (OpDef
&& OpDef
->hasValidDependencies() &&
1747 OpDef
->incrementUnscheduledDeps(-1) == 0) {
1748 // There are no more unscheduled dependencies after
1749 // decrementing, so we can put the dependent instruction
1750 // into the ready list.
1751 ScheduleData
*DepBundle
= OpDef
->FirstInBundle
;
1752 assert(!DepBundle
->IsScheduled
&&
1753 "already scheduled bundle gets ready");
1754 ReadyList
.insert(DepBundle
);
1756 << "SLP: gets ready (def): " << *DepBundle
<< "\n");
1761 // If BundleMember is a vector bundle, its operands may have been
1762 // reordered duiring buildTree(). We therefore need to get its operands
1763 // through the TreeEntry.
1764 if (TreeEntry
*TE
= BundleMember
->TE
) {
1765 int Lane
= BundleMember
->Lane
;
1766 assert(Lane
>= 0 && "Lane not set");
1767 for (unsigned OpIdx
= 0, NumOperands
= TE
->getNumOperands();
1768 OpIdx
!= NumOperands
; ++OpIdx
)
1769 if (auto *I
= dyn_cast
<Instruction
>(TE
->getOperand(OpIdx
)[Lane
]))
1772 // If BundleMember is a stand-alone instruction, no operand reordering
1773 // has taken place, so we directly access its operands.
1774 for (Use
&U
: BundleMember
->Inst
->operands())
1775 if (auto *I
= dyn_cast
<Instruction
>(U
.get()))
1778 // Handle the memory dependencies.
1779 for (ScheduleData
*MemoryDepSD
: BundleMember
->MemoryDependencies
) {
1780 if (MemoryDepSD
->incrementUnscheduledDeps(-1) == 0) {
1781 // There are no more unscheduled dependencies after decrementing,
1782 // so we can put the dependent instruction into the ready list.
1783 ScheduleData
*DepBundle
= MemoryDepSD
->FirstInBundle
;
1784 assert(!DepBundle
->IsScheduled
&&
1785 "already scheduled bundle gets ready");
1786 ReadyList
.insert(DepBundle
);
1788 << "SLP: gets ready (mem): " << *DepBundle
<< "\n");
1791 BundleMember
= BundleMember
->NextInBundle
;
1795 void doForAllOpcodes(Value
*V
,
1796 function_ref
<void(ScheduleData
*SD
)> Action
) {
1797 if (ScheduleData
*SD
= getScheduleData(V
))
1799 auto I
= ExtraScheduleDataMap
.find(V
);
1800 if (I
!= ExtraScheduleDataMap
.end())
1801 for (auto &P
: I
->second
)
1802 if (P
.second
->SchedulingRegionID
== SchedulingRegionID
)
1806 /// Put all instructions into the ReadyList which are ready for scheduling.
1807 template <typename ReadyListType
>
1808 void initialFillReadyList(ReadyListType
&ReadyList
) {
1809 for (auto *I
= ScheduleStart
; I
!= ScheduleEnd
; I
= I
->getNextNode()) {
1810 doForAllOpcodes(I
, [&](ScheduleData
*SD
) {
1811 if (SD
->isSchedulingEntity() && SD
->isReady()) {
1812 ReadyList
.insert(SD
);
1814 << "SLP: initially in ready list: " << *I
<< "\n");
1820 /// Checks if a bundle of instructions can be scheduled, i.e. has no
1821 /// cyclic dependencies. This is only a dry-run, no instructions are
1822 /// actually moved at this stage.
1823 /// \returns the scheduling bundle. The returned Optional value is non-None
1824 /// if \p VL is allowed to be scheduled.
1825 Optional
<ScheduleData
*>
1826 tryScheduleBundle(ArrayRef
<Value
*> VL
, BoUpSLP
*SLP
,
1827 const InstructionsState
&S
);
1829 /// Un-bundles a group of instructions.
1830 void cancelScheduling(ArrayRef
<Value
*> VL
, Value
*OpValue
);
1832 /// Allocates schedule data chunk.
1833 ScheduleData
*allocateScheduleDataChunks();
1835 /// Extends the scheduling region so that V is inside the region.
1836 /// \returns true if the region size is within the limit.
1837 bool extendSchedulingRegion(Value
*V
, const InstructionsState
&S
);
1839 /// Initialize the ScheduleData structures for new instructions in the
1840 /// scheduling region.
1841 void initScheduleData(Instruction
*FromI
, Instruction
*ToI
,
1842 ScheduleData
*PrevLoadStore
,
1843 ScheduleData
*NextLoadStore
);
1845 /// Updates the dependency information of a bundle and of all instructions/
1846 /// bundles which depend on the original bundle.
1847 void calculateDependencies(ScheduleData
*SD
, bool InsertInReadyList
,
1850 /// Sets all instruction in the scheduling region to un-scheduled.
1851 void resetSchedule();
1855 /// Simple memory allocation for ScheduleData.
1856 std::vector
<std::unique_ptr
<ScheduleData
[]>> ScheduleDataChunks
;
1858 /// The size of a ScheduleData array in ScheduleDataChunks.
1861 /// The allocator position in the current chunk, which is the last entry
1862 /// of ScheduleDataChunks.
1865 /// Attaches ScheduleData to Instruction.
1866 /// Note that the mapping survives during all vectorization iterations, i.e.
1867 /// ScheduleData structures are recycled.
1868 DenseMap
<Value
*, ScheduleData
*> ScheduleDataMap
;
1870 /// Attaches ScheduleData to Instruction with the leading key.
1871 DenseMap
<Value
*, SmallDenseMap
<Value
*, ScheduleData
*>>
1872 ExtraScheduleDataMap
;
1874 struct ReadyList
: SmallVector
<ScheduleData
*, 8> {
1875 void insert(ScheduleData
*SD
) { push_back(SD
); }
1878 /// The ready-list for scheduling (only used for the dry-run).
1879 ReadyList ReadyInsts
;
1881 /// The first instruction of the scheduling region.
1882 Instruction
*ScheduleStart
= nullptr;
1884 /// The first instruction _after_ the scheduling region.
1885 Instruction
*ScheduleEnd
= nullptr;
1887 /// The first memory accessing instruction in the scheduling region
1889 ScheduleData
*FirstLoadStoreInRegion
= nullptr;
1891 /// The last memory accessing instruction in the scheduling region
1893 ScheduleData
*LastLoadStoreInRegion
= nullptr;
1895 /// The current size of the scheduling region.
1896 int ScheduleRegionSize
= 0;
1898 /// The maximum size allowed for the scheduling region.
1899 int ScheduleRegionSizeLimit
= ScheduleRegionSizeBudget
;
1901 /// The ID of the scheduling region. For a new vectorization iteration this
1902 /// is incremented which "removes" all ScheduleData from the region.
1903 // Make sure that the initial SchedulingRegionID is greater than the
1904 // initial SchedulingRegionID in ScheduleData (which is 0).
1905 int SchedulingRegionID
= 1;
1908 /// Attaches the BlockScheduling structures to basic blocks.
1909 MapVector
<BasicBlock
*, std::unique_ptr
<BlockScheduling
>> BlocksSchedules
;
1911 /// Performs the "real" scheduling. Done before vectorization is actually
1912 /// performed in a basic block.
1913 void scheduleBlock(BlockScheduling
*BS
);
1915 /// List of users to ignore during scheduling and that don't need extracting.
1916 ArrayRef
<Value
*> UserIgnoreList
;
1918 using OrdersType
= SmallVector
<unsigned, 4>;
1919 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
1920 /// sorted SmallVectors of unsigned.
1921 struct OrdersTypeDenseMapInfo
{
1922 static OrdersType
getEmptyKey() {
1928 static OrdersType
getTombstoneKey() {
1934 static unsigned getHashValue(const OrdersType
&V
) {
1935 return static_cast<unsigned>(hash_combine_range(V
.begin(), V
.end()));
1938 static bool isEqual(const OrdersType
&LHS
, const OrdersType
&RHS
) {
1943 /// Contains orders of operations along with the number of bundles that have
1944 /// operations in this order. It stores only those orders that require
1945 /// reordering, if reordering is not required it is counted using \a
1946 /// NumOpsWantToKeepOriginalOrder.
1947 DenseMap
<OrdersType
, unsigned, OrdersTypeDenseMapInfo
> NumOpsWantToKeepOrder
;
1948 /// Number of bundles that do not require reordering.
1949 unsigned NumOpsWantToKeepOriginalOrder
= 0;
1951 // Analysis and block reference.
1953 ScalarEvolution
*SE
;
1954 TargetTransformInfo
*TTI
;
1955 TargetLibraryInfo
*TLI
;
1959 AssumptionCache
*AC
;
1961 const DataLayout
*DL
;
1962 OptimizationRemarkEmitter
*ORE
;
1964 unsigned MaxVecRegSize
; // This is set by TTI or overridden by cl::opt.
1965 unsigned MinVecRegSize
; // Set by cl::opt (default: 128).
1967 /// Instruction builder to construct the vectorized tree.
1968 IRBuilder
<> Builder
;
1970 /// A map of scalar integer values to the smallest bit width with which they
1971 /// can legally be represented. The values map to (width, signed) pairs,
1972 /// where "width" indicates the minimum bit width and "signed" is True if the
1973 /// value must be signed-extended, rather than zero-extended, back to its
1975 MapVector
<Value
*, std::pair
<uint64_t, bool>> MinBWs
;
1978 } // end namespace slpvectorizer
1980 template <> struct GraphTraits
<BoUpSLP
*> {
1981 using TreeEntry
= BoUpSLP::TreeEntry
;
1983 /// NodeRef has to be a pointer per the GraphWriter.
1984 using NodeRef
= TreeEntry
*;
1986 using ContainerTy
= BoUpSLP::TreeEntry::VecTreeTy
;
1988 /// Add the VectorizableTree to the index iterator to be able to return
1989 /// TreeEntry pointers.
1990 struct ChildIteratorType
1991 : public iterator_adaptor_base
<
1992 ChildIteratorType
, SmallVector
<BoUpSLP::EdgeInfo
, 1>::iterator
> {
1993 ContainerTy
&VectorizableTree
;
1995 ChildIteratorType(SmallVector
<BoUpSLP::EdgeInfo
, 1>::iterator W
,
1997 : ChildIteratorType::iterator_adaptor_base(W
), VectorizableTree(VT
) {}
1999 NodeRef
operator*() { return I
->UserTE
; }
2002 static NodeRef
getEntryNode(BoUpSLP
&R
) {
2003 return R
.VectorizableTree
[0].get();
2006 static ChildIteratorType
child_begin(NodeRef N
) {
2007 return {N
->UserTreeIndices
.begin(), N
->Container
};
2010 static ChildIteratorType
child_end(NodeRef N
) {
2011 return {N
->UserTreeIndices
.end(), N
->Container
};
2014 /// For the node iterator we just need to turn the TreeEntry iterator into a
2015 /// TreeEntry* iterator so that it dereferences to NodeRef.
2016 class nodes_iterator
{
2017 using ItTy
= ContainerTy::iterator
;
2021 nodes_iterator(const ItTy
&It2
) : It(It2
) {}
2022 NodeRef
operator*() { return It
->get(); }
2023 nodes_iterator
operator++() {
2027 bool operator!=(const nodes_iterator
&N2
) const { return N2
.It
!= It
; }
2030 static nodes_iterator
nodes_begin(BoUpSLP
*R
) {
2031 return nodes_iterator(R
->VectorizableTree
.begin());
2034 static nodes_iterator
nodes_end(BoUpSLP
*R
) {
2035 return nodes_iterator(R
->VectorizableTree
.end());
2038 static unsigned size(BoUpSLP
*R
) { return R
->VectorizableTree
.size(); }
2041 template <> struct DOTGraphTraits
<BoUpSLP
*> : public DefaultDOTGraphTraits
{
2042 using TreeEntry
= BoUpSLP::TreeEntry
;
2044 DOTGraphTraits(bool isSimple
= false) : DefaultDOTGraphTraits(isSimple
) {}
2046 std::string
getNodeLabel(const TreeEntry
*Entry
, const BoUpSLP
*R
) {
2048 raw_string_ostream
OS(Str
);
2049 if (isSplat(Entry
->Scalars
)) {
2050 OS
<< "<splat> " << *Entry
->Scalars
[0];
2053 for (auto V
: Entry
->Scalars
) {
2056 R
->ExternalUses
.begin(), R
->ExternalUses
.end(),
2057 [&](const BoUpSLP::ExternalUser
&EU
) { return EU
.Scalar
== V
; }))
2064 static std::string
getNodeAttributes(const TreeEntry
*Entry
,
2066 if (Entry
->NeedToGather
)
2072 } // end namespace llvm
2074 BoUpSLP::~BoUpSLP() {
2075 for (const auto &Pair
: DeletedInstructions
) {
2076 // Replace operands of ignored instructions with Undefs in case if they were
2077 // marked for deletion.
2078 if (Pair
.getSecond()) {
2079 Value
*Undef
= UndefValue::get(Pair
.getFirst()->getType());
2080 Pair
.getFirst()->replaceAllUsesWith(Undef
);
2082 Pair
.getFirst()->dropAllReferences();
2084 for (const auto &Pair
: DeletedInstructions
) {
2085 assert(Pair
.getFirst()->use_empty() &&
2086 "trying to erase instruction with users.");
2087 Pair
.getFirst()->eraseFromParent();
2091 void BoUpSLP::eraseInstructions(ArrayRef
<Value
*> AV
) {
2092 for (auto *V
: AV
) {
2093 if (auto *I
= dyn_cast
<Instruction
>(V
))
2094 eraseInstruction(I
, /*ReplaceWithUndef=*/true);
2098 void BoUpSLP::buildTree(ArrayRef
<Value
*> Roots
,
2099 ArrayRef
<Value
*> UserIgnoreLst
) {
2100 ExtraValueToDebugLocsMap ExternallyUsedValues
;
2101 buildTree(Roots
, ExternallyUsedValues
, UserIgnoreLst
);
2104 void BoUpSLP::buildTree(ArrayRef
<Value
*> Roots
,
2105 ExtraValueToDebugLocsMap
&ExternallyUsedValues
,
2106 ArrayRef
<Value
*> UserIgnoreLst
) {
2108 UserIgnoreList
= UserIgnoreLst
;
2109 if (!allSameType(Roots
))
2111 buildTree_rec(Roots
, 0, EdgeInfo());
2113 // Collect the values that we need to extract from the tree.
2114 for (auto &TEPtr
: VectorizableTree
) {
2115 TreeEntry
*Entry
= TEPtr
.get();
2117 // No need to handle users of gathered values.
2118 if (Entry
->NeedToGather
)
2122 for (int Lane
= 0, LE
= Entry
->Scalars
.size(); Lane
!= LE
; ++Lane
) {
2123 Value
*Scalar
= Entry
->Scalars
[Lane
];
2124 int FoundLane
= Lane
;
2125 if (!Entry
->ReuseShuffleIndices
.empty()) {
2127 std::distance(Entry
->ReuseShuffleIndices
.begin(),
2128 llvm::find(Entry
->ReuseShuffleIndices
, FoundLane
));
2131 // Check if the scalar is externally used as an extra arg.
2132 auto ExtI
= ExternallyUsedValues
.find(Scalar
);
2133 if (ExtI
!= ExternallyUsedValues
.end()) {
2134 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
2135 << Lane
<< " from " << *Scalar
<< ".\n");
2136 ExternalUses
.emplace_back(Scalar
, nullptr, FoundLane
);
2138 for (User
*U
: Scalar
->users()) {
2139 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U
<< ".\n");
2141 Instruction
*UserInst
= dyn_cast
<Instruction
>(U
);
2145 // Skip in-tree scalars that become vectors
2146 if (TreeEntry
*UseEntry
= getTreeEntry(U
)) {
2147 Value
*UseScalar
= UseEntry
->Scalars
[0];
2148 // Some in-tree scalars will remain as scalar in vectorized
2149 // instructions. If that is the case, the one in Lane 0 will
2151 if (UseScalar
!= U
||
2152 !InTreeUserNeedToExtract(Scalar
, UserInst
, TLI
)) {
2153 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
2155 assert(!UseEntry
->NeedToGather
&& "Bad state");
2160 // Ignore users in the user ignore list.
2161 if (is_contained(UserIgnoreList
, UserInst
))
2164 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U
<< " from lane "
2165 << Lane
<< " from " << *Scalar
<< ".\n");
2166 ExternalUses
.push_back(ExternalUser(Scalar
, U
, FoundLane
));
2172 void BoUpSLP::buildTree_rec(ArrayRef
<Value
*> VL
, unsigned Depth
,
2173 const EdgeInfo
&UserTreeIdx
) {
2174 assert((allConstant(VL
) || allSameType(VL
)) && "Invalid types!");
2176 InstructionsState S
= getSameOpcode(VL
);
2177 if (Depth
== RecursionMaxDepth
) {
2178 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
2179 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2183 // Don't handle vectors.
2184 if (S
.OpValue
->getType()->isVectorTy()) {
2185 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
2186 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2190 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(S
.OpValue
))
2191 if (SI
->getValueOperand()->getType()->isVectorTy()) {
2192 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
2193 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2197 // If all of the operands are identical or constant we have a simple solution.
2198 if (allConstant(VL
) || isSplat(VL
) || !allSameBlock(VL
) || !S
.getOpcode()) {
2199 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
2200 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2204 // We now know that this is a vector of instructions of the same type from
2207 // Don't vectorize ephemeral values.
2208 for (Value
*V
: VL
) {
2209 if (EphValues
.count(V
)) {
2210 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2211 << ") is ephemeral.\n");
2212 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2217 // Check if this is a duplicate of another entry.
2218 if (TreeEntry
*E
= getTreeEntry(S
.OpValue
)) {
2219 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S
.OpValue
<< ".\n");
2220 if (!E
->isSame(VL
)) {
2221 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
2222 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2225 // Record the reuse of the tree node. FIXME, currently this is only used to
2226 // properly draw the graph rather than for the actual vectorization.
2227 E
->UserTreeIndices
.push_back(UserTreeIdx
);
2228 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S
.OpValue
2233 // Check that none of the instructions in the bundle are already in the tree.
2234 for (Value
*V
: VL
) {
2235 auto *I
= dyn_cast
<Instruction
>(V
);
2238 if (getTreeEntry(I
)) {
2239 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2240 << ") is already in tree.\n");
2241 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2246 // If any of the scalars is marked as a value that needs to stay scalar, then
2247 // we need to gather the scalars.
2248 // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
2249 for (Value
*V
: VL
) {
2250 if (MustGather
.count(V
) || is_contained(UserIgnoreList
, V
)) {
2251 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
2252 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2257 // Check that all of the users of the scalars that we want to vectorize are
2259 auto *VL0
= cast
<Instruction
>(S
.OpValue
);
2260 BasicBlock
*BB
= VL0
->getParent();
2262 if (!DT
->isReachableFromEntry(BB
)) {
2263 // Don't go into unreachable blocks. They may contain instructions with
2264 // dependency cycles which confuse the final scheduling.
2265 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
2266 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2270 // Check that every instruction appears once in this bundle.
2271 SmallVector
<unsigned, 4> ReuseShuffleIndicies
;
2272 SmallVector
<Value
*, 4> UniqueValues
;
2273 DenseMap
<Value
*, unsigned> UniquePositions
;
2274 for (Value
*V
: VL
) {
2275 auto Res
= UniquePositions
.try_emplace(V
, UniqueValues
.size());
2276 ReuseShuffleIndicies
.emplace_back(Res
.first
->second
);
2278 UniqueValues
.emplace_back(V
);
2280 size_t NumUniqueScalarValues
= UniqueValues
.size();
2281 if (NumUniqueScalarValues
== VL
.size()) {
2282 ReuseShuffleIndicies
.clear();
2284 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
2285 if (NumUniqueScalarValues
<= 1 ||
2286 !llvm::isPowerOf2_32(NumUniqueScalarValues
)) {
2287 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
2288 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
);
2294 auto &BSRef
= BlocksSchedules
[BB
];
2296 BSRef
= std::make_unique
<BlockScheduling
>(BB
);
2298 BlockScheduling
&BS
= *BSRef
.get();
2300 Optional
<ScheduleData
*> Bundle
= BS
.tryScheduleBundle(VL
, this, S
);
2302 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
2303 assert((!BS
.getScheduleData(VL0
) ||
2304 !BS
.getScheduleData(VL0
)->isPartOfBundle()) &&
2305 "tryScheduleBundle should cancelScheduling on failure");
2306 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2307 ReuseShuffleIndicies
);
2310 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
2312 unsigned ShuffleOrOp
= S
.isAltShuffle() ?
2313 (unsigned) Instruction::ShuffleVector
: S
.getOpcode();
2314 switch (ShuffleOrOp
) {
2315 case Instruction::PHI
: {
2316 auto *PH
= cast
<PHINode
>(VL0
);
2318 // Check for terminator values (e.g. invoke).
2319 for (unsigned j
= 0; j
< VL
.size(); ++j
)
2320 for (unsigned i
= 0, e
= PH
->getNumIncomingValues(); i
< e
; ++i
) {
2321 Instruction
*Term
= dyn_cast
<Instruction
>(
2322 cast
<PHINode
>(VL
[j
])->getIncomingValueForBlock(
2323 PH
->getIncomingBlock(i
)));
2324 if (Term
&& Term
->isTerminator()) {
2326 << "SLP: Need to swizzle PHINodes (terminator use).\n");
2327 BS
.cancelScheduling(VL
, VL0
);
2328 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2329 ReuseShuffleIndicies
);
2335 newTreeEntry(VL
, Bundle
, S
, UserTreeIdx
, ReuseShuffleIndicies
);
2336 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
2338 // Keeps the reordered operands to avoid code duplication.
2339 SmallVector
<ValueList
, 2> OperandsVec
;
2340 for (unsigned i
= 0, e
= PH
->getNumIncomingValues(); i
< e
; ++i
) {
2342 // Prepare the operand vector.
2344 Operands
.push_back(cast
<PHINode
>(j
)->getIncomingValueForBlock(
2345 PH
->getIncomingBlock(i
)));
2346 TE
->setOperand(i
, Operands
);
2347 OperandsVec
.push_back(Operands
);
2349 for (unsigned OpIdx
= 0, OpE
= OperandsVec
.size(); OpIdx
!= OpE
; ++OpIdx
)
2350 buildTree_rec(OperandsVec
[OpIdx
], Depth
+ 1, {TE
, OpIdx
});
2353 case Instruction::ExtractValue
:
2354 case Instruction::ExtractElement
: {
2355 OrdersType CurrentOrder
;
2356 bool Reuse
= canReuseExtract(VL
, VL0
, CurrentOrder
);
2358 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
2359 ++NumOpsWantToKeepOriginalOrder
;
2360 newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2361 ReuseShuffleIndicies
);
2362 // This is a special case, as it does not gather, but at the same time
2363 // we are not extending buildTree_rec() towards the operands.
2365 Op0
.assign(VL
.size(), VL0
->getOperand(0));
2366 VectorizableTree
.back()->setOperand(0, Op0
);
2369 if (!CurrentOrder
.empty()) {
2371 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
2373 for (unsigned Idx
: CurrentOrder
)
2374 dbgs() << " " << Idx
;
2377 // Insert new order with initial value 0, if it does not exist,
2378 // otherwise return the iterator to the existing one.
2379 auto StoredCurrentOrderAndNum
=
2380 NumOpsWantToKeepOrder
.try_emplace(CurrentOrder
).first
;
2381 ++StoredCurrentOrderAndNum
->getSecond();
2382 newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2383 ReuseShuffleIndicies
,
2384 StoredCurrentOrderAndNum
->getFirst());
2385 // This is a special case, as it does not gather, but at the same time
2386 // we are not extending buildTree_rec() towards the operands.
2388 Op0
.assign(VL
.size(), VL0
->getOperand(0));
2389 VectorizableTree
.back()->setOperand(0, Op0
);
2392 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
2393 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2394 ReuseShuffleIndicies
);
2395 BS
.cancelScheduling(VL
, VL0
);
2398 case Instruction::Load
: {
2399 // Check that a vectorized load would load the same memory as a scalar
2400 // load. For example, we don't want to vectorize loads that are smaller
2401 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
2402 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
2403 // from such a struct, we read/write packed bits disagreeing with the
2404 // unvectorized version.
2405 Type
*ScalarTy
= VL0
->getType();
2407 if (DL
->getTypeSizeInBits(ScalarTy
) !=
2408 DL
->getTypeAllocSizeInBits(ScalarTy
)) {
2409 BS
.cancelScheduling(VL
, VL0
);
2410 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2411 ReuseShuffleIndicies
);
2412 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
2416 // Make sure all loads in the bundle are simple - we can't vectorize
2417 // atomic or volatile loads.
2418 SmallVector
<Value
*, 4> PointerOps(VL
.size());
2419 auto POIter
= PointerOps
.begin();
2420 for (Value
*V
: VL
) {
2421 auto *L
= cast
<LoadInst
>(V
);
2422 if (!L
->isSimple()) {
2423 BS
.cancelScheduling(VL
, VL0
);
2424 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2425 ReuseShuffleIndicies
);
2426 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
2429 *POIter
= L
->getPointerOperand();
2433 OrdersType CurrentOrder
;
2434 // Check the order of pointer operands.
2435 if (llvm::sortPtrAccesses(PointerOps
, *DL
, *SE
, CurrentOrder
)) {
2438 if (CurrentOrder
.empty()) {
2439 Ptr0
= PointerOps
.front();
2440 PtrN
= PointerOps
.back();
2442 Ptr0
= PointerOps
[CurrentOrder
.front()];
2443 PtrN
= PointerOps
[CurrentOrder
.back()];
2445 const SCEV
*Scev0
= SE
->getSCEV(Ptr0
);
2446 const SCEV
*ScevN
= SE
->getSCEV(PtrN
);
2448 dyn_cast
<SCEVConstant
>(SE
->getMinusSCEV(ScevN
, Scev0
));
2449 uint64_t Size
= DL
->getTypeAllocSize(ScalarTy
);
2450 // Check that the sorted loads are consecutive.
2451 if (Diff
&& Diff
->getAPInt().getZExtValue() == (VL
.size() - 1) * Size
) {
2452 if (CurrentOrder
.empty()) {
2453 // Original loads are consecutive and does not require reordering.
2454 ++NumOpsWantToKeepOriginalOrder
;
2455 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
,
2456 UserTreeIdx
, ReuseShuffleIndicies
);
2457 TE
->setOperandsInOrder();
2458 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
2461 auto I
= NumOpsWantToKeepOrder
.try_emplace(CurrentOrder
).first
;
2464 newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2465 ReuseShuffleIndicies
, I
->getFirst());
2466 TE
->setOperandsInOrder();
2467 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
2473 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
2474 BS
.cancelScheduling(VL
, VL0
);
2475 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2476 ReuseShuffleIndicies
);
2479 case Instruction::ZExt
:
2480 case Instruction::SExt
:
2481 case Instruction::FPToUI
:
2482 case Instruction::FPToSI
:
2483 case Instruction::FPExt
:
2484 case Instruction::PtrToInt
:
2485 case Instruction::IntToPtr
:
2486 case Instruction::SIToFP
:
2487 case Instruction::UIToFP
:
2488 case Instruction::Trunc
:
2489 case Instruction::FPTrunc
:
2490 case Instruction::BitCast
: {
2491 Type
*SrcTy
= VL0
->getOperand(0)->getType();
2492 for (Value
*V
: VL
) {
2493 Type
*Ty
= cast
<Instruction
>(V
)->getOperand(0)->getType();
2494 if (Ty
!= SrcTy
|| !isValidElementType(Ty
)) {
2495 BS
.cancelScheduling(VL
, VL0
);
2496 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2497 ReuseShuffleIndicies
);
2499 << "SLP: Gathering casts with different src types.\n");
2503 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2504 ReuseShuffleIndicies
);
2505 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
2507 TE
->setOperandsInOrder();
2508 for (unsigned i
= 0, e
= VL0
->getNumOperands(); i
< e
; ++i
) {
2510 // Prepare the operand vector.
2512 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(i
));
2514 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2518 case Instruction::ICmp
:
2519 case Instruction::FCmp
: {
2520 // Check that all of the compares have the same predicate.
2521 CmpInst::Predicate P0
= cast
<CmpInst
>(VL0
)->getPredicate();
2522 CmpInst::Predicate SwapP0
= CmpInst::getSwappedPredicate(P0
);
2523 Type
*ComparedTy
= VL0
->getOperand(0)->getType();
2524 for (Value
*V
: VL
) {
2525 CmpInst
*Cmp
= cast
<CmpInst
>(V
);
2526 if ((Cmp
->getPredicate() != P0
&& Cmp
->getPredicate() != SwapP0
) ||
2527 Cmp
->getOperand(0)->getType() != ComparedTy
) {
2528 BS
.cancelScheduling(VL
, VL0
);
2529 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2530 ReuseShuffleIndicies
);
2532 << "SLP: Gathering cmp with different predicate.\n");
2537 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2538 ReuseShuffleIndicies
);
2539 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
2541 ValueList Left
, Right
;
2542 if (cast
<CmpInst
>(VL0
)->isCommutative()) {
2543 // Commutative predicate - collect + sort operands of the instructions
2544 // so that each side is more likely to have the same opcode.
2545 assert(P0
== SwapP0
&& "Commutative Predicate mismatch");
2546 reorderInputsAccordingToOpcode(VL
, Left
, Right
, *DL
, *SE
);
2548 // Collect operands - commute if it uses the swapped predicate.
2549 for (Value
*V
: VL
) {
2550 auto *Cmp
= cast
<CmpInst
>(V
);
2551 Value
*LHS
= Cmp
->getOperand(0);
2552 Value
*RHS
= Cmp
->getOperand(1);
2553 if (Cmp
->getPredicate() != P0
)
2554 std::swap(LHS
, RHS
);
2555 Left
.push_back(LHS
);
2556 Right
.push_back(RHS
);
2559 TE
->setOperand(0, Left
);
2560 TE
->setOperand(1, Right
);
2561 buildTree_rec(Left
, Depth
+ 1, {TE
, 0});
2562 buildTree_rec(Right
, Depth
+ 1, {TE
, 1});
2565 case Instruction::Select
:
2566 case Instruction::FNeg
:
2567 case Instruction::Add
:
2568 case Instruction::FAdd
:
2569 case Instruction::Sub
:
2570 case Instruction::FSub
:
2571 case Instruction::Mul
:
2572 case Instruction::FMul
:
2573 case Instruction::UDiv
:
2574 case Instruction::SDiv
:
2575 case Instruction::FDiv
:
2576 case Instruction::URem
:
2577 case Instruction::SRem
:
2578 case Instruction::FRem
:
2579 case Instruction::Shl
:
2580 case Instruction::LShr
:
2581 case Instruction::AShr
:
2582 case Instruction::And
:
2583 case Instruction::Or
:
2584 case Instruction::Xor
: {
2585 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2586 ReuseShuffleIndicies
);
2587 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
2589 // Sort operands of the instructions so that each side is more likely to
2590 // have the same opcode.
2591 if (isa
<BinaryOperator
>(VL0
) && VL0
->isCommutative()) {
2592 ValueList Left
, Right
;
2593 reorderInputsAccordingToOpcode(VL
, Left
, Right
, *DL
, *SE
);
2594 TE
->setOperand(0, Left
);
2595 TE
->setOperand(1, Right
);
2596 buildTree_rec(Left
, Depth
+ 1, {TE
, 0});
2597 buildTree_rec(Right
, Depth
+ 1, {TE
, 1});
2601 TE
->setOperandsInOrder();
2602 for (unsigned i
= 0, e
= VL0
->getNumOperands(); i
< e
; ++i
) {
2604 // Prepare the operand vector.
2606 Operands
.push_back(cast
<Instruction
>(j
)->getOperand(i
));
2608 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2612 case Instruction::GetElementPtr
: {
2613 // We don't combine GEPs with complicated (nested) indexing.
2614 for (Value
*V
: VL
) {
2615 if (cast
<Instruction
>(V
)->getNumOperands() != 2) {
2616 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
2617 BS
.cancelScheduling(VL
, VL0
);
2618 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2619 ReuseShuffleIndicies
);
2624 // We can't combine several GEPs into one vector if they operate on
2626 Type
*Ty0
= VL0
->getOperand(0)->getType();
2627 for (Value
*V
: VL
) {
2628 Type
*CurTy
= cast
<Instruction
>(V
)->getOperand(0)->getType();
2631 << "SLP: not-vectorizable GEP (different types).\n");
2632 BS
.cancelScheduling(VL
, VL0
);
2633 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2634 ReuseShuffleIndicies
);
2639 // We don't combine GEPs with non-constant indexes.
2640 for (Value
*V
: VL
) {
2641 auto Op
= cast
<Instruction
>(V
)->getOperand(1);
2642 if (!isa
<ConstantInt
>(Op
)) {
2644 << "SLP: not-vectorizable GEP (non-constant indexes).\n");
2645 BS
.cancelScheduling(VL
, VL0
);
2646 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2647 ReuseShuffleIndicies
);
2652 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2653 ReuseShuffleIndicies
);
2654 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
2655 TE
->setOperandsInOrder();
2656 for (unsigned i
= 0, e
= 2; i
< e
; ++i
) {
2658 // Prepare the operand vector.
2660 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(i
));
2662 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2666 case Instruction::Store
: {
2667 // Check if the stores are consecutive or if we need to swizzle them.
2668 for (unsigned i
= 0, e
= VL
.size() - 1; i
< e
; ++i
)
2669 if (!isConsecutiveAccess(VL
[i
], VL
[i
+ 1], *DL
, *SE
)) {
2670 BS
.cancelScheduling(VL
, VL0
);
2671 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2672 ReuseShuffleIndicies
);
2673 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
2677 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2678 ReuseShuffleIndicies
);
2679 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
2683 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(0));
2684 TE
->setOperandsInOrder();
2685 buildTree_rec(Operands
, Depth
+ 1, {TE
, 0});
2688 case Instruction::Call
: {
2689 // Check if the calls are all to the same vectorizable intrinsic.
2690 CallInst
*CI
= cast
<CallInst
>(VL0
);
2691 // Check if this is an Intrinsic call or something that can be
2692 // represented by an intrinsic call
2693 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
2694 if (!isTriviallyVectorizable(ID
)) {
2695 BS
.cancelScheduling(VL
, VL0
);
2696 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2697 ReuseShuffleIndicies
);
2698 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
2701 Function
*Int
= CI
->getCalledFunction();
2702 unsigned NumArgs
= CI
->getNumArgOperands();
2703 SmallVector
<Value
*, 4> ScalarArgs(NumArgs
, nullptr);
2704 for (unsigned j
= 0; j
!= NumArgs
; ++j
)
2705 if (hasVectorInstrinsicScalarOpd(ID
, j
))
2706 ScalarArgs
[j
] = CI
->getArgOperand(j
);
2707 for (Value
*V
: VL
) {
2708 CallInst
*CI2
= dyn_cast
<CallInst
>(V
);
2709 if (!CI2
|| CI2
->getCalledFunction() != Int
||
2710 getVectorIntrinsicIDForCall(CI2
, TLI
) != ID
||
2711 !CI
->hasIdenticalOperandBundleSchema(*CI2
)) {
2712 BS
.cancelScheduling(VL
, VL0
);
2713 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2714 ReuseShuffleIndicies
);
2715 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI
<< "!=" << *V
2719 // Some intrinsics have scalar arguments and should be same in order for
2720 // them to be vectorized.
2721 for (unsigned j
= 0; j
!= NumArgs
; ++j
) {
2722 if (hasVectorInstrinsicScalarOpd(ID
, j
)) {
2723 Value
*A1J
= CI2
->getArgOperand(j
);
2724 if (ScalarArgs
[j
] != A1J
) {
2725 BS
.cancelScheduling(VL
, VL0
);
2726 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2727 ReuseShuffleIndicies
);
2728 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
2729 << " argument " << ScalarArgs
[j
] << "!=" << A1J
2735 // Verify that the bundle operands are identical between the two calls.
2736 if (CI
->hasOperandBundles() &&
2737 !std::equal(CI
->op_begin() + CI
->getBundleOperandsStartIndex(),
2738 CI
->op_begin() + CI
->getBundleOperandsEndIndex(),
2739 CI2
->op_begin() + CI2
->getBundleOperandsStartIndex())) {
2740 BS
.cancelScheduling(VL
, VL0
);
2741 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2742 ReuseShuffleIndicies
);
2743 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
2744 << *CI
<< "!=" << *V
<< '\n');
2749 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2750 ReuseShuffleIndicies
);
2751 TE
->setOperandsInOrder();
2752 for (unsigned i
= 0, e
= CI
->getNumArgOperands(); i
!= e
; ++i
) {
2754 // Prepare the operand vector.
2755 for (Value
*V
: VL
) {
2756 auto *CI2
= cast
<CallInst
>(V
);
2757 Operands
.push_back(CI2
->getArgOperand(i
));
2759 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2763 case Instruction::ShuffleVector
: {
2764 // If this is not an alternate sequence of opcode like add-sub
2765 // then do not vectorize this instruction.
2766 if (!S
.isAltShuffle()) {
2767 BS
.cancelScheduling(VL
, VL0
);
2768 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2769 ReuseShuffleIndicies
);
2770 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
2773 TreeEntry
*TE
= newTreeEntry(VL
, Bundle
/*vectorized*/, S
, UserTreeIdx
,
2774 ReuseShuffleIndicies
);
2775 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
2777 // Reorder operands if reordering would enable vectorization.
2778 if (isa
<BinaryOperator
>(VL0
)) {
2779 ValueList Left
, Right
;
2780 reorderInputsAccordingToOpcode(VL
, Left
, Right
, *DL
, *SE
);
2781 TE
->setOperand(0, Left
);
2782 TE
->setOperand(1, Right
);
2783 buildTree_rec(Left
, Depth
+ 1, {TE
, 0});
2784 buildTree_rec(Right
, Depth
+ 1, {TE
, 1});
2788 TE
->setOperandsInOrder();
2789 for (unsigned i
= 0, e
= VL0
->getNumOperands(); i
< e
; ++i
) {
2791 // Prepare the operand vector.
2793 Operands
.push_back(cast
<Instruction
>(V
)->getOperand(i
));
2795 buildTree_rec(Operands
, Depth
+ 1, {TE
, i
});
2800 BS
.cancelScheduling(VL
, VL0
);
2801 newTreeEntry(VL
, None
/*not vectorized*/, S
, UserTreeIdx
,
2802 ReuseShuffleIndicies
);
2803 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
2808 unsigned BoUpSLP::canMapToVector(Type
*T
, const DataLayout
&DL
) const {
2811 auto *ST
= dyn_cast
<StructType
>(T
);
2813 N
= ST
->getNumElements();
2814 EltTy
= *ST
->element_begin();
2816 N
= cast
<ArrayType
>(T
)->getNumElements();
2817 EltTy
= cast
<ArrayType
>(T
)->getElementType();
2819 if (!isValidElementType(EltTy
))
2821 uint64_t VTSize
= DL
.getTypeStoreSizeInBits(VectorType::get(EltTy
, N
));
2822 if (VTSize
< MinVecRegSize
|| VTSize
> MaxVecRegSize
|| VTSize
!= DL
.getTypeStoreSizeInBits(T
))
2825 // Check that struct is homogeneous.
2826 for (const auto *Ty
: ST
->elements())
2833 bool BoUpSLP::canReuseExtract(ArrayRef
<Value
*> VL
, Value
*OpValue
,
2834 SmallVectorImpl
<unsigned> &CurrentOrder
) const {
2835 Instruction
*E0
= cast
<Instruction
>(OpValue
);
2836 assert(E0
->getOpcode() == Instruction::ExtractElement
||
2837 E0
->getOpcode() == Instruction::ExtractValue
);
2838 assert(E0
->getOpcode() == getSameOpcode(VL
).getOpcode() && "Invalid opcode");
2839 // Check if all of the extracts come from the same vector and from the
2841 Value
*Vec
= E0
->getOperand(0);
2843 CurrentOrder
.clear();
2845 // We have to extract from a vector/aggregate with the same number of elements.
2847 if (E0
->getOpcode() == Instruction::ExtractValue
) {
2848 const DataLayout
&DL
= E0
->getModule()->getDataLayout();
2849 NElts
= canMapToVector(Vec
->getType(), DL
);
2852 // Check if load can be rewritten as load of vector.
2853 LoadInst
*LI
= dyn_cast
<LoadInst
>(Vec
);
2854 if (!LI
|| !LI
->isSimple() || !LI
->hasNUses(VL
.size()))
2857 NElts
= Vec
->getType()->getVectorNumElements();
2860 if (NElts
!= VL
.size())
2863 // Check that all of the indices extract from the correct offset.
2864 bool ShouldKeepOrder
= true;
2865 unsigned E
= VL
.size();
2866 // Assign to all items the initial value E + 1 so we can check if the extract
2867 // instruction index was used already.
2868 // Also, later we can check that all the indices are used and we have a
2869 // consecutive access in the extract instructions, by checking that no
2870 // element of CurrentOrder still has value E + 1.
2871 CurrentOrder
.assign(E
, E
+ 1);
2873 for (; I
< E
; ++I
) {
2874 auto *Inst
= cast
<Instruction
>(VL
[I
]);
2875 if (Inst
->getOperand(0) != Vec
)
2877 Optional
<unsigned> Idx
= getExtractIndex(Inst
);
2880 const unsigned ExtIdx
= *Idx
;
2882 if (ExtIdx
>= E
|| CurrentOrder
[ExtIdx
] != E
+ 1)
2884 ShouldKeepOrder
= false;
2885 CurrentOrder
[ExtIdx
] = I
;
2887 if (CurrentOrder
[I
] != E
+ 1)
2889 CurrentOrder
[I
] = I
;
2893 CurrentOrder
.clear();
2897 return ShouldKeepOrder
;
2900 bool BoUpSLP::areAllUsersVectorized(Instruction
*I
) const {
2901 return I
->hasOneUse() ||
2902 std::all_of(I
->user_begin(), I
->user_end(), [this](User
*U
) {
2903 return ScalarToTreeEntry
.count(U
) > 0;
2907 int BoUpSLP::getEntryCost(TreeEntry
*E
) {
2908 ArrayRef
<Value
*> VL
= E
->Scalars
;
2910 Type
*ScalarTy
= VL
[0]->getType();
2911 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(VL
[0]))
2912 ScalarTy
= SI
->getValueOperand()->getType();
2913 else if (CmpInst
*CI
= dyn_cast
<CmpInst
>(VL
[0]))
2914 ScalarTy
= CI
->getOperand(0)->getType();
2915 VectorType
*VecTy
= VectorType::get(ScalarTy
, VL
.size());
2917 // If we have computed a smaller type for the expression, update VecTy so
2918 // that the costs will be accurate.
2919 if (MinBWs
.count(VL
[0]))
2920 VecTy
= VectorType::get(
2921 IntegerType::get(F
->getContext(), MinBWs
[VL
[0]].first
), VL
.size());
2923 unsigned ReuseShuffleNumbers
= E
->ReuseShuffleIndices
.size();
2924 bool NeedToShuffleReuses
= !E
->ReuseShuffleIndices
.empty();
2925 int ReuseShuffleCost
= 0;
2926 if (NeedToShuffleReuses
) {
2928 TTI
->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc
, VecTy
);
2930 if (E
->NeedToGather
) {
2931 if (allConstant(VL
))
2934 return ReuseShuffleCost
+
2935 TTI
->getShuffleCost(TargetTransformInfo::SK_Broadcast
, VecTy
, 0);
2937 if (E
->getOpcode() == Instruction::ExtractElement
&&
2938 allSameType(VL
) && allSameBlock(VL
)) {
2939 Optional
<TargetTransformInfo::ShuffleKind
> ShuffleKind
= isShuffle(VL
);
2940 if (ShuffleKind
.hasValue()) {
2941 int Cost
= TTI
->getShuffleCost(ShuffleKind
.getValue(), VecTy
);
2942 for (auto *V
: VL
) {
2943 // If all users of instruction are going to be vectorized and this
2944 // instruction itself is not going to be vectorized, consider this
2945 // instruction as dead and remove its cost from the final cost of the
2947 if (areAllUsersVectorized(cast
<Instruction
>(V
)) &&
2948 !ScalarToTreeEntry
.count(V
)) {
2949 auto *IO
= cast
<ConstantInt
>(
2950 cast
<ExtractElementInst
>(V
)->getIndexOperand());
2951 Cost
-= TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
,
2952 IO
->getZExtValue());
2955 return ReuseShuffleCost
+ Cost
;
2958 return ReuseShuffleCost
+ getGatherCost(VL
);
2960 assert(E
->getOpcode() && allSameType(VL
) && allSameBlock(VL
) && "Invalid VL");
2961 Instruction
*VL0
= E
->getMainOp();
2962 unsigned ShuffleOrOp
=
2963 E
->isAltShuffle() ? (unsigned)Instruction::ShuffleVector
: E
->getOpcode();
2964 switch (ShuffleOrOp
) {
2965 case Instruction::PHI
:
2968 case Instruction::ExtractValue
:
2969 case Instruction::ExtractElement
:
2970 if (NeedToShuffleReuses
) {
2972 for (unsigned I
: E
->ReuseShuffleIndices
) {
2973 if (ShuffleOrOp
== Instruction::ExtractElement
) {
2974 auto *IO
= cast
<ConstantInt
>(
2975 cast
<ExtractElementInst
>(VL
[I
])->getIndexOperand());
2976 Idx
= IO
->getZExtValue();
2977 ReuseShuffleCost
-= TTI
->getVectorInstrCost(
2978 Instruction::ExtractElement
, VecTy
, Idx
);
2980 ReuseShuffleCost
-= TTI
->getVectorInstrCost(
2981 Instruction::ExtractElement
, VecTy
, Idx
);
2985 Idx
= ReuseShuffleNumbers
;
2986 for (Value
*V
: VL
) {
2987 if (ShuffleOrOp
== Instruction::ExtractElement
) {
2988 auto *IO
= cast
<ConstantInt
>(
2989 cast
<ExtractElementInst
>(V
)->getIndexOperand());
2990 Idx
= IO
->getZExtValue();
2995 TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
, Idx
);
2998 if (!E
->NeedToGather
) {
2999 int DeadCost
= ReuseShuffleCost
;
3000 if (!E
->ReorderIndices
.empty()) {
3001 // TODO: Merge this shuffle with the ReuseShuffleCost.
3002 DeadCost
+= TTI
->getShuffleCost(
3003 TargetTransformInfo::SK_PermuteSingleSrc
, VecTy
);
3005 for (unsigned i
= 0, e
= VL
.size(); i
< e
; ++i
) {
3006 Instruction
*E
= cast
<Instruction
>(VL
[i
]);
3007 // If all users are going to be vectorized, instruction can be
3008 // considered as dead.
3009 // The same, if have only one user, it will be vectorized for sure.
3010 if (areAllUsersVectorized(E
)) {
3011 // Take credit for instruction that will become dead.
3012 if (E
->hasOneUse()) {
3013 Instruction
*Ext
= E
->user_back();
3014 if ((isa
<SExtInst
>(Ext
) || isa
<ZExtInst
>(Ext
)) &&
3015 all_of(Ext
->users(),
3016 [](User
*U
) { return isa
<GetElementPtrInst
>(U
); })) {
3017 // Use getExtractWithExtendCost() to calculate the cost of
3018 // extractelement/ext pair.
3019 DeadCost
-= TTI
->getExtractWithExtendCost(
3020 Ext
->getOpcode(), Ext
->getType(), VecTy
, i
);
3021 // Add back the cost of s|zext which is subtracted separately.
3022 DeadCost
+= TTI
->getCastInstrCost(
3023 Ext
->getOpcode(), Ext
->getType(), E
->getType(), Ext
);
3028 TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
, i
);
3033 return ReuseShuffleCost
+ getGatherCost(VL
);
3035 case Instruction::ZExt
:
3036 case Instruction::SExt
:
3037 case Instruction::FPToUI
:
3038 case Instruction::FPToSI
:
3039 case Instruction::FPExt
:
3040 case Instruction::PtrToInt
:
3041 case Instruction::IntToPtr
:
3042 case Instruction::SIToFP
:
3043 case Instruction::UIToFP
:
3044 case Instruction::Trunc
:
3045 case Instruction::FPTrunc
:
3046 case Instruction::BitCast
: {
3047 Type
*SrcTy
= VL0
->getOperand(0)->getType();
3049 TTI
->getCastInstrCost(E
->getOpcode(), ScalarTy
, SrcTy
, VL0
);
3050 if (NeedToShuffleReuses
) {
3051 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3054 // Calculate the cost of this instruction.
3055 int ScalarCost
= VL
.size() * ScalarEltCost
;
3057 VectorType
*SrcVecTy
= VectorType::get(SrcTy
, VL
.size());
3059 // Check if the values are candidates to demote.
3060 if (!MinBWs
.count(VL0
) || VecTy
!= SrcVecTy
) {
3061 VecCost
= ReuseShuffleCost
+
3062 TTI
->getCastInstrCost(E
->getOpcode(), VecTy
, SrcVecTy
, VL0
);
3064 return VecCost
- ScalarCost
;
3066 case Instruction::FCmp
:
3067 case Instruction::ICmp
:
3068 case Instruction::Select
: {
3069 // Calculate the cost of this instruction.
3070 int ScalarEltCost
= TTI
->getCmpSelInstrCost(E
->getOpcode(), ScalarTy
,
3071 Builder
.getInt1Ty(), VL0
);
3072 if (NeedToShuffleReuses
) {
3073 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3075 VectorType
*MaskTy
= VectorType::get(Builder
.getInt1Ty(), VL
.size());
3076 int ScalarCost
= VecTy
->getNumElements() * ScalarEltCost
;
3077 int VecCost
= TTI
->getCmpSelInstrCost(E
->getOpcode(), VecTy
, MaskTy
, VL0
);
3078 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3080 case Instruction::FNeg
:
3081 case Instruction::Add
:
3082 case Instruction::FAdd
:
3083 case Instruction::Sub
:
3084 case Instruction::FSub
:
3085 case Instruction::Mul
:
3086 case Instruction::FMul
:
3087 case Instruction::UDiv
:
3088 case Instruction::SDiv
:
3089 case Instruction::FDiv
:
3090 case Instruction::URem
:
3091 case Instruction::SRem
:
3092 case Instruction::FRem
:
3093 case Instruction::Shl
:
3094 case Instruction::LShr
:
3095 case Instruction::AShr
:
3096 case Instruction::And
:
3097 case Instruction::Or
:
3098 case Instruction::Xor
: {
3099 // Certain instructions can be cheaper to vectorize if they have a
3100 // constant second vector operand.
3101 TargetTransformInfo::OperandValueKind Op1VK
=
3102 TargetTransformInfo::OK_AnyValue
;
3103 TargetTransformInfo::OperandValueKind Op2VK
=
3104 TargetTransformInfo::OK_UniformConstantValue
;
3105 TargetTransformInfo::OperandValueProperties Op1VP
=
3106 TargetTransformInfo::OP_None
;
3107 TargetTransformInfo::OperandValueProperties Op2VP
=
3108 TargetTransformInfo::OP_PowerOf2
;
3110 // If all operands are exactly the same ConstantInt then set the
3111 // operand kind to OK_UniformConstantValue.
3112 // If instead not all operands are constants, then set the operand kind
3113 // to OK_AnyValue. If all operands are constants but not the same,
3114 // then set the operand kind to OK_NonUniformConstantValue.
3115 ConstantInt
*CInt0
= nullptr;
3116 for (unsigned i
= 0, e
= VL
.size(); i
< e
; ++i
) {
3117 const Instruction
*I
= cast
<Instruction
>(VL
[i
]);
3118 unsigned OpIdx
= isa
<BinaryOperator
>(I
) ? 1 : 0;
3119 ConstantInt
*CInt
= dyn_cast
<ConstantInt
>(I
->getOperand(OpIdx
));
3121 Op2VK
= TargetTransformInfo::OK_AnyValue
;
3122 Op2VP
= TargetTransformInfo::OP_None
;
3125 if (Op2VP
== TargetTransformInfo::OP_PowerOf2
&&
3126 !CInt
->getValue().isPowerOf2())
3127 Op2VP
= TargetTransformInfo::OP_None
;
3133 Op2VK
= TargetTransformInfo::OK_NonUniformConstantValue
;
3136 SmallVector
<const Value
*, 4> Operands(VL0
->operand_values());
3137 int ScalarEltCost
= TTI
->getArithmeticInstrCost(
3138 E
->getOpcode(), ScalarTy
, Op1VK
, Op2VK
, Op1VP
, Op2VP
, Operands
);
3139 if (NeedToShuffleReuses
) {
3140 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3142 int ScalarCost
= VecTy
->getNumElements() * ScalarEltCost
;
3143 int VecCost
= TTI
->getArithmeticInstrCost(E
->getOpcode(), VecTy
, Op1VK
,
3144 Op2VK
, Op1VP
, Op2VP
, Operands
);
3145 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3147 case Instruction::GetElementPtr
: {
3148 TargetTransformInfo::OperandValueKind Op1VK
=
3149 TargetTransformInfo::OK_AnyValue
;
3150 TargetTransformInfo::OperandValueKind Op2VK
=
3151 TargetTransformInfo::OK_UniformConstantValue
;
3154 TTI
->getArithmeticInstrCost(Instruction::Add
, ScalarTy
, Op1VK
, Op2VK
);
3155 if (NeedToShuffleReuses
) {
3156 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3158 int ScalarCost
= VecTy
->getNumElements() * ScalarEltCost
;
3160 TTI
->getArithmeticInstrCost(Instruction::Add
, VecTy
, Op1VK
, Op2VK
);
3161 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3163 case Instruction::Load
: {
3164 // Cost of wide load - cost of scalar loads.
3165 unsigned alignment
= cast
<LoadInst
>(VL0
)->getAlignment();
3167 TTI
->getMemoryOpCost(Instruction::Load
, ScalarTy
, alignment
, 0, VL0
);
3168 if (NeedToShuffleReuses
) {
3169 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3171 int ScalarLdCost
= VecTy
->getNumElements() * ScalarEltCost
;
3173 TTI
->getMemoryOpCost(Instruction::Load
, VecTy
, alignment
, 0, VL0
);
3174 if (!E
->ReorderIndices
.empty()) {
3175 // TODO: Merge this shuffle with the ReuseShuffleCost.
3176 VecLdCost
+= TTI
->getShuffleCost(
3177 TargetTransformInfo::SK_PermuteSingleSrc
, VecTy
);
3179 return ReuseShuffleCost
+ VecLdCost
- ScalarLdCost
;
3181 case Instruction::Store
: {
3182 // We know that we can merge the stores. Calculate the cost.
3183 unsigned alignment
= cast
<StoreInst
>(VL0
)->getAlignment();
3185 TTI
->getMemoryOpCost(Instruction::Store
, ScalarTy
, alignment
, 0, VL0
);
3186 if (NeedToShuffleReuses
) {
3187 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3189 int ScalarStCost
= VecTy
->getNumElements() * ScalarEltCost
;
3191 TTI
->getMemoryOpCost(Instruction::Store
, VecTy
, alignment
, 0, VL0
);
3192 return ReuseShuffleCost
+ VecStCost
- ScalarStCost
;
3194 case Instruction::Call
: {
3195 CallInst
*CI
= cast
<CallInst
>(VL0
);
3196 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
3198 // Calculate the cost of the scalar and vector calls.
3199 SmallVector
<Type
*, 4> ScalarTys
;
3200 for (unsigned op
= 0, opc
= CI
->getNumArgOperands(); op
!= opc
; ++op
)
3201 ScalarTys
.push_back(CI
->getArgOperand(op
)->getType());
3204 if (auto *FPMO
= dyn_cast
<FPMathOperator
>(CI
))
3205 FMF
= FPMO
->getFastMathFlags();
3208 TTI
->getIntrinsicInstrCost(ID
, ScalarTy
, ScalarTys
, FMF
);
3209 if (NeedToShuffleReuses
) {
3210 ReuseShuffleCost
-= (ReuseShuffleNumbers
- VL
.size()) * ScalarEltCost
;
3212 int ScalarCallCost
= VecTy
->getNumElements() * ScalarEltCost
;
3214 SmallVector
<Value
*, 4> Args(CI
->arg_operands());
3215 int VecCallCost
= TTI
->getIntrinsicInstrCost(ID
, CI
->getType(), Args
, FMF
,
3216 VecTy
->getNumElements());
3218 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost
- ScalarCallCost
3219 << " (" << VecCallCost
<< "-" << ScalarCallCost
<< ")"
3220 << " for " << *CI
<< "\n");
3222 return ReuseShuffleCost
+ VecCallCost
- ScalarCallCost
;
3224 case Instruction::ShuffleVector
: {
3225 assert(E
->isAltShuffle() &&
3226 ((Instruction::isBinaryOp(E
->getOpcode()) &&
3227 Instruction::isBinaryOp(E
->getAltOpcode())) ||
3228 (Instruction::isCast(E
->getOpcode()) &&
3229 Instruction::isCast(E
->getAltOpcode()))) &&
3230 "Invalid Shuffle Vector Operand");
3232 if (NeedToShuffleReuses
) {
3233 for (unsigned Idx
: E
->ReuseShuffleIndices
) {
3234 Instruction
*I
= cast
<Instruction
>(VL
[Idx
]);
3235 ReuseShuffleCost
-= TTI
->getInstructionCost(
3236 I
, TargetTransformInfo::TCK_RecipThroughput
);
3238 for (Value
*V
: VL
) {
3239 Instruction
*I
= cast
<Instruction
>(V
);
3240 ReuseShuffleCost
+= TTI
->getInstructionCost(
3241 I
, TargetTransformInfo::TCK_RecipThroughput
);
3244 for (Value
*V
: VL
) {
3245 Instruction
*I
= cast
<Instruction
>(V
);
3246 assert(E
->isOpcodeOrAlt(I
) && "Unexpected main/alternate opcode");
3247 ScalarCost
+= TTI
->getInstructionCost(
3248 I
, TargetTransformInfo::TCK_RecipThroughput
);
3250 // VecCost is equal to sum of the cost of creating 2 vectors
3251 // and the cost of creating shuffle.
3253 if (Instruction::isBinaryOp(E
->getOpcode())) {
3254 VecCost
= TTI
->getArithmeticInstrCost(E
->getOpcode(), VecTy
);
3255 VecCost
+= TTI
->getArithmeticInstrCost(E
->getAltOpcode(), VecTy
);
3257 Type
*Src0SclTy
= E
->getMainOp()->getOperand(0)->getType();
3258 Type
*Src1SclTy
= E
->getAltOp()->getOperand(0)->getType();
3259 VectorType
*Src0Ty
= VectorType::get(Src0SclTy
, VL
.size());
3260 VectorType
*Src1Ty
= VectorType::get(Src1SclTy
, VL
.size());
3261 VecCost
= TTI
->getCastInstrCost(E
->getOpcode(), VecTy
, Src0Ty
);
3262 VecCost
+= TTI
->getCastInstrCost(E
->getAltOpcode(), VecTy
, Src1Ty
);
3264 VecCost
+= TTI
->getShuffleCost(TargetTransformInfo::SK_Select
, VecTy
, 0);
3265 return ReuseShuffleCost
+ VecCost
- ScalarCost
;
3268 llvm_unreachable("Unknown instruction");
3272 bool BoUpSLP::isFullyVectorizableTinyTree() const {
3273 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
3274 << VectorizableTree
.size() << " is fully vectorizable .\n");
3276 // We only handle trees of heights 1 and 2.
3277 if (VectorizableTree
.size() == 1 && !VectorizableTree
[0]->NeedToGather
)
3280 if (VectorizableTree
.size() != 2)
3283 // Handle splat and all-constants stores.
3284 if (!VectorizableTree
[0]->NeedToGather
&&
3285 (allConstant(VectorizableTree
[1]->Scalars
) ||
3286 isSplat(VectorizableTree
[1]->Scalars
)))
3289 // Gathering cost would be too much for tiny trees.
3290 if (VectorizableTree
[0]->NeedToGather
|| VectorizableTree
[1]->NeedToGather
)
3296 bool BoUpSLP::isLoadCombineReductionCandidate(unsigned RdxOpcode
) const {
3297 if (RdxOpcode
!= Instruction::Or
)
3300 unsigned NumElts
= VectorizableTree
[0]->Scalars
.size();
3301 Value
*FirstReduced
= VectorizableTree
[0]->Scalars
[0];
3303 // Look past the reduction to find a source value. Arbitrarily follow the
3304 // path through operand 0 of any 'or'. Also, peek through optional
3305 // shift-left-by-constant.
3306 Value
*ZextLoad
= FirstReduced
;
3307 while (match(ZextLoad
, m_Or(m_Value(), m_Value())) ||
3308 match(ZextLoad
, m_Shl(m_Value(), m_Constant())))
3309 ZextLoad
= cast
<BinaryOperator
>(ZextLoad
)->getOperand(0);
3311 // Check if the input to the reduction is an extended load.
3313 if (!match(ZextLoad
, m_ZExt(m_Load(m_Value(LoadPtr
)))))
3316 // Require that the total load bit width is a legal integer type.
3317 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
3318 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
3319 Type
*SrcTy
= LoadPtr
->getType()->getPointerElementType();
3320 unsigned LoadBitWidth
= SrcTy
->getIntegerBitWidth() * NumElts
;
3321 LLVMContext
&Context
= FirstReduced
->getContext();
3322 if (!TTI
->isTypeLegal(IntegerType::get(Context
, LoadBitWidth
)))
3325 // Everything matched - assume that we can fold the whole sequence using
3327 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for scalar reduction of "
3328 << *(cast
<Instruction
>(FirstReduced
)) << "\n");
3333 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3334 // We can vectorize the tree if its size is greater than or equal to the
3335 // minimum size specified by the MinTreeSize command line option.
3336 if (VectorizableTree
.size() >= MinTreeSize
)
3339 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3340 // can vectorize it if we can prove it fully vectorizable.
3341 if (isFullyVectorizableTinyTree())
3344 assert(VectorizableTree
.empty()
3345 ? ExternalUses
.empty()
3346 : true && "We shouldn't have any external users");
3348 // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3353 int BoUpSLP::getSpillCost() const {
3354 // Walk from the bottom of the tree to the top, tracking which values are
3355 // live. When we see a call instruction that is not part of our tree,
3356 // query TTI to see if there is a cost to keeping values live over it
3357 // (for example, if spills and fills are required).
3358 unsigned BundleWidth
= VectorizableTree
.front()->Scalars
.size();
3361 SmallPtrSet
<Instruction
*, 4> LiveValues
;
3362 Instruction
*PrevInst
= nullptr;
3364 for (const auto &TEPtr
: VectorizableTree
) {
3365 Instruction
*Inst
= dyn_cast
<Instruction
>(TEPtr
->Scalars
[0]);
3374 // Update LiveValues.
3375 LiveValues
.erase(PrevInst
);
3376 for (auto &J
: PrevInst
->operands()) {
3377 if (isa
<Instruction
>(&*J
) && getTreeEntry(&*J
))
3378 LiveValues
.insert(cast
<Instruction
>(&*J
));
3382 dbgs() << "SLP: #LV: " << LiveValues
.size();
3383 for (auto *X
: LiveValues
)
3384 dbgs() << " " << X
->getName();
3385 dbgs() << ", Looking at ";
3389 // Now find the sequence of instructions between PrevInst and Inst.
3390 unsigned NumCalls
= 0;
3391 BasicBlock::reverse_iterator InstIt
= ++Inst
->getIterator().getReverse(),
3393 PrevInst
->getIterator().getReverse();
3394 while (InstIt
!= PrevInstIt
) {
3395 if (PrevInstIt
== PrevInst
->getParent()->rend()) {
3396 PrevInstIt
= Inst
->getParent()->rbegin();
3400 // Debug informations don't impact spill cost.
3401 if ((isa
<CallInst
>(&*PrevInstIt
) &&
3402 !isa
<DbgInfoIntrinsic
>(&*PrevInstIt
)) &&
3403 &*PrevInstIt
!= PrevInst
)
3410 SmallVector
<Type
*, 4> V
;
3411 for (auto *II
: LiveValues
)
3412 V
.push_back(VectorType::get(II
->getType(), BundleWidth
));
3413 Cost
+= NumCalls
* TTI
->getCostOfKeepingLiveOverCall(V
);
3422 int BoUpSLP::getTreeCost() {
3424 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
3425 << VectorizableTree
.size() << ".\n");
3427 unsigned BundleWidth
= VectorizableTree
[0]->Scalars
.size();
3429 for (unsigned I
= 0, E
= VectorizableTree
.size(); I
< E
; ++I
) {
3430 TreeEntry
&TE
= *VectorizableTree
[I
].get();
3432 // We create duplicate tree entries for gather sequences that have multiple
3433 // uses. However, we should not compute the cost of duplicate sequences.
3434 // For example, if we have a build vector (i.e., insertelement sequence)
3435 // that is used by more than one vector instruction, we only need to
3436 // compute the cost of the insertelement instructions once. The redundant
3437 // instructions will be eliminated by CSE.
3439 // We should consider not creating duplicate tree entries for gather
3440 // sequences, and instead add additional edges to the tree representing
3441 // their uses. Since such an approach results in fewer total entries,
3442 // existing heuristics based on tree size may yield different results.
3444 if (TE
.NeedToGather
&&
3446 std::next(VectorizableTree
.begin(), I
+ 1), VectorizableTree
.end(),
3447 [TE
](const std::unique_ptr
<TreeEntry
> &EntryPtr
) {
3448 return EntryPtr
->NeedToGather
&& EntryPtr
->isSame(TE
.Scalars
);
3452 int C
= getEntryCost(&TE
);
3453 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
3454 << " for bundle that starts with " << *TE
.Scalars
[0]
3459 SmallPtrSet
<Value
*, 16> ExtractCostCalculated
;
3460 int ExtractCost
= 0;
3461 for (ExternalUser
&EU
: ExternalUses
) {
3462 // We only add extract cost once for the same scalar.
3463 if (!ExtractCostCalculated
.insert(EU
.Scalar
).second
)
3466 // Uses by ephemeral values are free (because the ephemeral value will be
3467 // removed prior to code generation, and so the extraction will be
3468 // removed as well).
3469 if (EphValues
.count(EU
.User
))
3472 // If we plan to rewrite the tree in a smaller type, we will need to sign
3473 // extend the extracted value back to the original type. Here, we account
3474 // for the extract and the added cost of the sign extend if needed.
3475 auto *VecTy
= VectorType::get(EU
.Scalar
->getType(), BundleWidth
);
3476 auto *ScalarRoot
= VectorizableTree
[0]->Scalars
[0];
3477 if (MinBWs
.count(ScalarRoot
)) {
3478 auto *MinTy
= IntegerType::get(F
->getContext(), MinBWs
[ScalarRoot
].first
);
3480 MinBWs
[ScalarRoot
].second
? Instruction::SExt
: Instruction::ZExt
;
3481 VecTy
= VectorType::get(MinTy
, BundleWidth
);
3482 ExtractCost
+= TTI
->getExtractWithExtendCost(Extend
, EU
.Scalar
->getType(),
3486 TTI
->getVectorInstrCost(Instruction::ExtractElement
, VecTy
, EU
.Lane
);
3490 int SpillCost
= getSpillCost();
3491 Cost
+= SpillCost
+ ExtractCost
;
3495 raw_string_ostream
OS(Str
);
3496 OS
<< "SLP: Spill Cost = " << SpillCost
<< ".\n"
3497 << "SLP: Extract Cost = " << ExtractCost
<< ".\n"
3498 << "SLP: Total Cost = " << Cost
<< ".\n";
3500 LLVM_DEBUG(dbgs() << Str
);
3503 ViewGraph(this, "SLP" + F
->getName(), false, Str
);
3508 int BoUpSLP::getGatherCost(Type
*Ty
,
3509 const DenseSet
<unsigned> &ShuffledIndices
) const {
3511 for (unsigned i
= 0, e
= cast
<VectorType
>(Ty
)->getNumElements(); i
< e
; ++i
)
3512 if (!ShuffledIndices
.count(i
))
3513 Cost
+= TTI
->getVectorInstrCost(Instruction::InsertElement
, Ty
, i
);
3514 if (!ShuffledIndices
.empty())
3515 Cost
+= TTI
->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc
, Ty
);
3519 int BoUpSLP::getGatherCost(ArrayRef
<Value
*> VL
) const {
3520 // Find the type of the operands in VL.
3521 Type
*ScalarTy
= VL
[0]->getType();
3522 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(VL
[0]))
3523 ScalarTy
= SI
->getValueOperand()->getType();
3524 VectorType
*VecTy
= VectorType::get(ScalarTy
, VL
.size());
3525 // Find the cost of inserting/extracting values from the vector.
3526 // Check if the same elements are inserted several times and count them as
3527 // shuffle candidates.
3528 DenseSet
<unsigned> ShuffledElements
;
3529 DenseSet
<Value
*> UniqueElements
;
3530 // Iterate in reverse order to consider insert elements with the high cost.
3531 for (unsigned I
= VL
.size(); I
> 0; --I
) {
3532 unsigned Idx
= I
- 1;
3533 if (!UniqueElements
.insert(VL
[Idx
]).second
)
3534 ShuffledElements
.insert(Idx
);
3536 return getGatherCost(VecTy
, ShuffledElements
);
3539 // Perform operand reordering on the instructions in VL and return the reordered
3540 // operands in Left and Right.
3541 void BoUpSLP::reorderInputsAccordingToOpcode(
3542 ArrayRef
<Value
*> VL
, SmallVectorImpl
<Value
*> &Left
,
3543 SmallVectorImpl
<Value
*> &Right
, const DataLayout
&DL
,
3544 ScalarEvolution
&SE
) {
3547 VLOperands
Ops(VL
, DL
, SE
);
3548 // Reorder the operands in place.
3550 Left
= Ops
.getVL(0);
3551 Right
= Ops
.getVL(1);
3554 void BoUpSLP::setInsertPointAfterBundle(TreeEntry
*E
) {
3555 // Get the basic block this bundle is in. All instructions in the bundle
3556 // should be in this block.
3557 auto *Front
= E
->getMainOp();
3558 auto *BB
= Front
->getParent();
3559 assert(llvm::all_of(make_range(E
->Scalars
.begin(), E
->Scalars
.end()),
3560 [=](Value
*V
) -> bool {
3561 auto *I
= cast
<Instruction
>(V
);
3562 return !E
->isOpcodeOrAlt(I
) || I
->getParent() == BB
;
3565 // The last instruction in the bundle in program order.
3566 Instruction
*LastInst
= nullptr;
3568 // Find the last instruction. The common case should be that BB has been
3569 // scheduled, and the last instruction is VL.back(). So we start with
3570 // VL.back() and iterate over schedule data until we reach the end of the
3571 // bundle. The end of the bundle is marked by null ScheduleData.
3572 if (BlocksSchedules
.count(BB
)) {
3574 BlocksSchedules
[BB
]->getScheduleData(E
->isOneOf(E
->Scalars
.back()));
3575 if (Bundle
&& Bundle
->isPartOfBundle())
3576 for (; Bundle
; Bundle
= Bundle
->NextInBundle
)
3577 if (Bundle
->OpValue
== Bundle
->Inst
)
3578 LastInst
= Bundle
->Inst
;
3581 // LastInst can still be null at this point if there's either not an entry
3582 // for BB in BlocksSchedules or there's no ScheduleData available for
3583 // VL.back(). This can be the case if buildTree_rec aborts for various
3584 // reasons (e.g., the maximum recursion depth is reached, the maximum region
3585 // size is reached, etc.). ScheduleData is initialized in the scheduling
3588 // If this happens, we can still find the last instruction by brute force. We
3589 // iterate forwards from Front (inclusive) until we either see all
3590 // instructions in the bundle or reach the end of the block. If Front is the
3591 // last instruction in program order, LastInst will be set to Front, and we
3592 // will visit all the remaining instructions in the block.
3594 // One of the reasons we exit early from buildTree_rec is to place an upper
3595 // bound on compile-time. Thus, taking an additional compile-time hit here is
3596 // not ideal. However, this should be exceedingly rare since it requires that
3597 // we both exit early from buildTree_rec and that the bundle be out-of-order
3598 // (causing us to iterate all the way to the end of the block).
3600 SmallPtrSet
<Value
*, 16> Bundle(E
->Scalars
.begin(), E
->Scalars
.end());
3601 for (auto &I
: make_range(BasicBlock::iterator(Front
), BB
->end())) {
3602 if (Bundle
.erase(&I
) && E
->isOpcodeOrAlt(&I
))
3608 assert(LastInst
&& "Failed to find last instruction in bundle");
3610 // Set the insertion point after the last instruction in the bundle. Set the
3611 // debug location to Front.
3612 Builder
.SetInsertPoint(BB
, ++LastInst
->getIterator());
3613 Builder
.SetCurrentDebugLocation(Front
->getDebugLoc());
3616 Value
*BoUpSLP::Gather(ArrayRef
<Value
*> VL
, VectorType
*Ty
) {
3617 Value
*Vec
= UndefValue::get(Ty
);
3618 // Generate the 'InsertElement' instruction.
3619 for (unsigned i
= 0; i
< Ty
->getNumElements(); ++i
) {
3620 Vec
= Builder
.CreateInsertElement(Vec
, VL
[i
], Builder
.getInt32(i
));
3621 if (auto *Insrt
= dyn_cast
<InsertElementInst
>(Vec
)) {
3622 GatherSeq
.insert(Insrt
);
3623 CSEBlocks
.insert(Insrt
->getParent());
3625 // Add to our 'need-to-extract' list.
3626 if (TreeEntry
*E
= getTreeEntry(VL
[i
])) {
3627 // Find which lane we need to extract.
3629 for (unsigned Lane
= 0, LE
= E
->Scalars
.size(); Lane
!= LE
; ++Lane
) {
3630 // Is this the lane of the scalar that we are looking for ?
3631 if (E
->Scalars
[Lane
] == VL
[i
]) {
3636 assert(FoundLane
>= 0 && "Could not find the correct lane");
3637 if (!E
->ReuseShuffleIndices
.empty()) {
3639 std::distance(E
->ReuseShuffleIndices
.begin(),
3640 llvm::find(E
->ReuseShuffleIndices
, FoundLane
));
3642 ExternalUses
.push_back(ExternalUser(VL
[i
], Insrt
, FoundLane
));
3650 Value
*BoUpSLP::vectorizeTree(ArrayRef
<Value
*> VL
) {
3651 InstructionsState S
= getSameOpcode(VL
);
3652 if (S
.getOpcode()) {
3653 if (TreeEntry
*E
= getTreeEntry(S
.OpValue
)) {
3654 if (E
->isSame(VL
)) {
3655 Value
*V
= vectorizeTree(E
);
3656 if (VL
.size() == E
->Scalars
.size() && !E
->ReuseShuffleIndices
.empty()) {
3657 // We need to get the vectorized value but without shuffle.
3658 if (auto *SV
= dyn_cast
<ShuffleVectorInst
>(V
)) {
3659 V
= SV
->getOperand(0);
3661 // Reshuffle to get only unique values.
3662 SmallVector
<unsigned, 4> UniqueIdxs
;
3663 SmallSet
<unsigned, 4> UsedIdxs
;
3664 for(unsigned Idx
: E
->ReuseShuffleIndices
)
3665 if (UsedIdxs
.insert(Idx
).second
)
3666 UniqueIdxs
.emplace_back(Idx
);
3667 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(V
->getType()),
3676 Type
*ScalarTy
= S
.OpValue
->getType();
3677 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(S
.OpValue
))
3678 ScalarTy
= SI
->getValueOperand()->getType();
3680 // Check that every instruction appears once in this bundle.
3681 SmallVector
<unsigned, 4> ReuseShuffleIndicies
;
3682 SmallVector
<Value
*, 4> UniqueValues
;
3683 if (VL
.size() > 2) {
3684 DenseMap
<Value
*, unsigned> UniquePositions
;
3685 for (Value
*V
: VL
) {
3686 auto Res
= UniquePositions
.try_emplace(V
, UniqueValues
.size());
3687 ReuseShuffleIndicies
.emplace_back(Res
.first
->second
);
3688 if (Res
.second
|| isa
<Constant
>(V
))
3689 UniqueValues
.emplace_back(V
);
3691 // Do not shuffle single element or if number of unique values is not power
3693 if (UniqueValues
.size() == VL
.size() || UniqueValues
.size() <= 1 ||
3694 !llvm::isPowerOf2_32(UniqueValues
.size()))
3695 ReuseShuffleIndicies
.clear();
3699 VectorType
*VecTy
= VectorType::get(ScalarTy
, VL
.size());
3701 Value
*V
= Gather(VL
, VecTy
);
3702 if (!ReuseShuffleIndicies
.empty()) {
3703 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3704 ReuseShuffleIndicies
, "shuffle");
3705 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3706 GatherSeq
.insert(I
);
3707 CSEBlocks
.insert(I
->getParent());
3713 static void inversePermutation(ArrayRef
<unsigned> Indices
,
3714 SmallVectorImpl
<unsigned> &Mask
) {
3716 const unsigned E
= Indices
.size();
3718 for (unsigned I
= 0; I
< E
; ++I
)
3719 Mask
[Indices
[I
]] = I
;
3722 Value
*BoUpSLP::vectorizeTree(TreeEntry
*E
) {
3723 IRBuilder
<>::InsertPointGuard
Guard(Builder
);
3725 if (E
->VectorizedValue
) {
3726 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E
->Scalars
[0] << ".\n");
3727 return E
->VectorizedValue
;
3730 Instruction
*VL0
= E
->getMainOp();
3731 Type
*ScalarTy
= VL0
->getType();
3732 if (StoreInst
*SI
= dyn_cast
<StoreInst
>(VL0
))
3733 ScalarTy
= SI
->getValueOperand()->getType();
3734 VectorType
*VecTy
= VectorType::get(ScalarTy
, E
->Scalars
.size());
3736 bool NeedToShuffleReuses
= !E
->ReuseShuffleIndices
.empty();
3738 if (E
->NeedToGather
) {
3739 setInsertPointAfterBundle(E
);
3740 auto *V
= Gather(E
->Scalars
, VecTy
);
3741 if (NeedToShuffleReuses
) {
3742 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3743 E
->ReuseShuffleIndices
, "shuffle");
3744 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3745 GatherSeq
.insert(I
);
3746 CSEBlocks
.insert(I
->getParent());
3749 E
->VectorizedValue
= V
;
3753 unsigned ShuffleOrOp
=
3754 E
->isAltShuffle() ? (unsigned)Instruction::ShuffleVector
: E
->getOpcode();
3755 switch (ShuffleOrOp
) {
3756 case Instruction::PHI
: {
3757 auto *PH
= cast
<PHINode
>(VL0
);
3758 Builder
.SetInsertPoint(PH
->getParent()->getFirstNonPHI());
3759 Builder
.SetCurrentDebugLocation(PH
->getDebugLoc());
3760 PHINode
*NewPhi
= Builder
.CreatePHI(VecTy
, PH
->getNumIncomingValues());
3762 if (NeedToShuffleReuses
) {
3763 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3764 E
->ReuseShuffleIndices
, "shuffle");
3766 E
->VectorizedValue
= V
;
3768 // PHINodes may have multiple entries from the same block. We want to
3769 // visit every block once.
3770 SmallPtrSet
<BasicBlock
*, 4> VisitedBBs
;
3772 for (unsigned i
= 0, e
= PH
->getNumIncomingValues(); i
< e
; ++i
) {
3774 BasicBlock
*IBB
= PH
->getIncomingBlock(i
);
3776 if (!VisitedBBs
.insert(IBB
).second
) {
3777 NewPhi
->addIncoming(NewPhi
->getIncomingValueForBlock(IBB
), IBB
);
3781 Builder
.SetInsertPoint(IBB
->getTerminator());
3782 Builder
.SetCurrentDebugLocation(PH
->getDebugLoc());
3783 Value
*Vec
= vectorizeTree(E
->getOperand(i
));
3784 NewPhi
->addIncoming(Vec
, IBB
);
3787 assert(NewPhi
->getNumIncomingValues() == PH
->getNumIncomingValues() &&
3788 "Invalid number of incoming values");
3792 case Instruction::ExtractElement
: {
3793 if (!E
->NeedToGather
) {
3794 Value
*V
= E
->getSingleOperand(0);
3795 if (!E
->ReorderIndices
.empty()) {
3797 inversePermutation(E
->ReorderIndices
, Mask
);
3798 Builder
.SetInsertPoint(VL0
);
3799 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
), Mask
,
3802 if (NeedToShuffleReuses
) {
3803 // TODO: Merge this shuffle with the ReorderShuffleMask.
3804 if (E
->ReorderIndices
.empty())
3805 Builder
.SetInsertPoint(VL0
);
3806 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3807 E
->ReuseShuffleIndices
, "shuffle");
3809 E
->VectorizedValue
= V
;
3812 setInsertPointAfterBundle(E
);
3813 auto *V
= Gather(E
->Scalars
, VecTy
);
3814 if (NeedToShuffleReuses
) {
3815 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3816 E
->ReuseShuffleIndices
, "shuffle");
3817 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3818 GatherSeq
.insert(I
);
3819 CSEBlocks
.insert(I
->getParent());
3822 E
->VectorizedValue
= V
;
3825 case Instruction::ExtractValue
: {
3826 if (!E
->NeedToGather
) {
3827 LoadInst
*LI
= cast
<LoadInst
>(E
->getSingleOperand(0));
3828 Builder
.SetInsertPoint(LI
);
3829 PointerType
*PtrTy
= PointerType::get(VecTy
, LI
->getPointerAddressSpace());
3830 Value
*Ptr
= Builder
.CreateBitCast(LI
->getOperand(0), PtrTy
);
3831 LoadInst
*V
= Builder
.CreateAlignedLoad(VecTy
, Ptr
, LI
->getAlignment());
3832 Value
*NewV
= propagateMetadata(V
, E
->Scalars
);
3833 if (!E
->ReorderIndices
.empty()) {
3835 inversePermutation(E
->ReorderIndices
, Mask
);
3836 NewV
= Builder
.CreateShuffleVector(NewV
, UndefValue::get(VecTy
), Mask
,
3839 if (NeedToShuffleReuses
) {
3840 // TODO: Merge this shuffle with the ReorderShuffleMask.
3841 NewV
= Builder
.CreateShuffleVector(
3842 NewV
, UndefValue::get(VecTy
), E
->ReuseShuffleIndices
, "shuffle");
3844 E
->VectorizedValue
= NewV
;
3847 setInsertPointAfterBundle(E
);
3848 auto *V
= Gather(E
->Scalars
, VecTy
);
3849 if (NeedToShuffleReuses
) {
3850 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3851 E
->ReuseShuffleIndices
, "shuffle");
3852 if (auto *I
= dyn_cast
<Instruction
>(V
)) {
3853 GatherSeq
.insert(I
);
3854 CSEBlocks
.insert(I
->getParent());
3857 E
->VectorizedValue
= V
;
3860 case Instruction::ZExt
:
3861 case Instruction::SExt
:
3862 case Instruction::FPToUI
:
3863 case Instruction::FPToSI
:
3864 case Instruction::FPExt
:
3865 case Instruction::PtrToInt
:
3866 case Instruction::IntToPtr
:
3867 case Instruction::SIToFP
:
3868 case Instruction::UIToFP
:
3869 case Instruction::Trunc
:
3870 case Instruction::FPTrunc
:
3871 case Instruction::BitCast
: {
3872 setInsertPointAfterBundle(E
);
3874 Value
*InVec
= vectorizeTree(E
->getOperand(0));
3876 if (E
->VectorizedValue
) {
3877 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3878 return E
->VectorizedValue
;
3881 auto *CI
= cast
<CastInst
>(VL0
);
3882 Value
*V
= Builder
.CreateCast(CI
->getOpcode(), InVec
, VecTy
);
3883 if (NeedToShuffleReuses
) {
3884 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3885 E
->ReuseShuffleIndices
, "shuffle");
3887 E
->VectorizedValue
= V
;
3888 ++NumVectorInstructions
;
3891 case Instruction::FCmp
:
3892 case Instruction::ICmp
: {
3893 setInsertPointAfterBundle(E
);
3895 Value
*L
= vectorizeTree(E
->getOperand(0));
3896 Value
*R
= vectorizeTree(E
->getOperand(1));
3898 if (E
->VectorizedValue
) {
3899 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3900 return E
->VectorizedValue
;
3903 CmpInst::Predicate P0
= cast
<CmpInst
>(VL0
)->getPredicate();
3905 if (E
->getOpcode() == Instruction::FCmp
)
3906 V
= Builder
.CreateFCmp(P0
, L
, R
);
3908 V
= Builder
.CreateICmp(P0
, L
, R
);
3910 propagateIRFlags(V
, E
->Scalars
, VL0
);
3911 if (NeedToShuffleReuses
) {
3912 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3913 E
->ReuseShuffleIndices
, "shuffle");
3915 E
->VectorizedValue
= V
;
3916 ++NumVectorInstructions
;
3919 case Instruction::Select
: {
3920 setInsertPointAfterBundle(E
);
3922 Value
*Cond
= vectorizeTree(E
->getOperand(0));
3923 Value
*True
= vectorizeTree(E
->getOperand(1));
3924 Value
*False
= vectorizeTree(E
->getOperand(2));
3926 if (E
->VectorizedValue
) {
3927 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3928 return E
->VectorizedValue
;
3931 Value
*V
= Builder
.CreateSelect(Cond
, True
, False
);
3932 if (NeedToShuffleReuses
) {
3933 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3934 E
->ReuseShuffleIndices
, "shuffle");
3936 E
->VectorizedValue
= V
;
3937 ++NumVectorInstructions
;
3940 case Instruction::FNeg
: {
3941 setInsertPointAfterBundle(E
);
3943 Value
*Op
= vectorizeTree(E
->getOperand(0));
3945 if (E
->VectorizedValue
) {
3946 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3947 return E
->VectorizedValue
;
3950 Value
*V
= Builder
.CreateUnOp(
3951 static_cast<Instruction::UnaryOps
>(E
->getOpcode()), Op
);
3952 propagateIRFlags(V
, E
->Scalars
, VL0
);
3953 if (auto *I
= dyn_cast
<Instruction
>(V
))
3954 V
= propagateMetadata(I
, E
->Scalars
);
3956 if (NeedToShuffleReuses
) {
3957 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
3958 E
->ReuseShuffleIndices
, "shuffle");
3960 E
->VectorizedValue
= V
;
3961 ++NumVectorInstructions
;
3965 case Instruction::Add
:
3966 case Instruction::FAdd
:
3967 case Instruction::Sub
:
3968 case Instruction::FSub
:
3969 case Instruction::Mul
:
3970 case Instruction::FMul
:
3971 case Instruction::UDiv
:
3972 case Instruction::SDiv
:
3973 case Instruction::FDiv
:
3974 case Instruction::URem
:
3975 case Instruction::SRem
:
3976 case Instruction::FRem
:
3977 case Instruction::Shl
:
3978 case Instruction::LShr
:
3979 case Instruction::AShr
:
3980 case Instruction::And
:
3981 case Instruction::Or
:
3982 case Instruction::Xor
: {
3983 setInsertPointAfterBundle(E
);
3985 Value
*LHS
= vectorizeTree(E
->getOperand(0));
3986 Value
*RHS
= vectorizeTree(E
->getOperand(1));
3988 if (E
->VectorizedValue
) {
3989 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
3990 return E
->VectorizedValue
;
3993 Value
*V
= Builder
.CreateBinOp(
3994 static_cast<Instruction::BinaryOps
>(E
->getOpcode()), LHS
,
3996 propagateIRFlags(V
, E
->Scalars
, VL0
);
3997 if (auto *I
= dyn_cast
<Instruction
>(V
))
3998 V
= propagateMetadata(I
, E
->Scalars
);
4000 if (NeedToShuffleReuses
) {
4001 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4002 E
->ReuseShuffleIndices
, "shuffle");
4004 E
->VectorizedValue
= V
;
4005 ++NumVectorInstructions
;
4009 case Instruction::Load
: {
4010 // Loads are inserted at the head of the tree because we don't want to
4011 // sink them all the way down past store instructions.
4012 bool IsReorder
= E
->updateStateIfReorder();
4014 VL0
= E
->getMainOp();
4015 setInsertPointAfterBundle(E
);
4017 LoadInst
*LI
= cast
<LoadInst
>(VL0
);
4018 Type
*ScalarLoadTy
= LI
->getType();
4019 unsigned AS
= LI
->getPointerAddressSpace();
4021 Value
*VecPtr
= Builder
.CreateBitCast(LI
->getPointerOperand(),
4022 VecTy
->getPointerTo(AS
));
4024 // The pointer operand uses an in-tree scalar so we add the new BitCast to
4025 // ExternalUses list to make sure that an extract will be generated in the
4027 Value
*PO
= LI
->getPointerOperand();
4028 if (getTreeEntry(PO
))
4029 ExternalUses
.push_back(ExternalUser(PO
, cast
<User
>(VecPtr
), 0));
4031 MaybeAlign Alignment
= MaybeAlign(LI
->getAlignment());
4032 LI
= Builder
.CreateLoad(VecTy
, VecPtr
);
4034 Alignment
= MaybeAlign(DL
->getABITypeAlignment(ScalarLoadTy
));
4035 LI
->setAlignment(Alignment
);
4036 Value
*V
= propagateMetadata(LI
, E
->Scalars
);
4039 inversePermutation(E
->ReorderIndices
, Mask
);
4040 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(V
->getType()),
4041 Mask
, "reorder_shuffle");
4043 if (NeedToShuffleReuses
) {
4044 // TODO: Merge this shuffle with the ReorderShuffleMask.
4045 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4046 E
->ReuseShuffleIndices
, "shuffle");
4048 E
->VectorizedValue
= V
;
4049 ++NumVectorInstructions
;
4052 case Instruction::Store
: {
4053 StoreInst
*SI
= cast
<StoreInst
>(VL0
);
4054 unsigned Alignment
= SI
->getAlignment();
4055 unsigned AS
= SI
->getPointerAddressSpace();
4057 setInsertPointAfterBundle(E
);
4059 Value
*VecValue
= vectorizeTree(E
->getOperand(0));
4060 Value
*ScalarPtr
= SI
->getPointerOperand();
4061 Value
*VecPtr
= Builder
.CreateBitCast(ScalarPtr
, VecTy
->getPointerTo(AS
));
4062 StoreInst
*ST
= Builder
.CreateStore(VecValue
, VecPtr
);
4064 // The pointer operand uses an in-tree scalar, so add the new BitCast to
4065 // ExternalUses to make sure that an extract will be generated in the
4067 if (getTreeEntry(ScalarPtr
))
4068 ExternalUses
.push_back(ExternalUser(ScalarPtr
, cast
<User
>(VecPtr
), 0));
4071 Alignment
= DL
->getABITypeAlignment(SI
->getValueOperand()->getType());
4073 ST
->setAlignment(Align(Alignment
));
4074 Value
*V
= propagateMetadata(ST
, E
->Scalars
);
4075 if (NeedToShuffleReuses
) {
4076 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4077 E
->ReuseShuffleIndices
, "shuffle");
4079 E
->VectorizedValue
= V
;
4080 ++NumVectorInstructions
;
4083 case Instruction::GetElementPtr
: {
4084 setInsertPointAfterBundle(E
);
4086 Value
*Op0
= vectorizeTree(E
->getOperand(0));
4088 std::vector
<Value
*> OpVecs
;
4089 for (int j
= 1, e
= cast
<GetElementPtrInst
>(VL0
)->getNumOperands(); j
< e
;
4091 Value
*OpVec
= vectorizeTree(E
->getOperand(j
));
4092 OpVecs
.push_back(OpVec
);
4095 Value
*V
= Builder
.CreateGEP(
4096 cast
<GetElementPtrInst
>(VL0
)->getSourceElementType(), Op0
, OpVecs
);
4097 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
4098 V
= propagateMetadata(I
, E
->Scalars
);
4100 if (NeedToShuffleReuses
) {
4101 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4102 E
->ReuseShuffleIndices
, "shuffle");
4104 E
->VectorizedValue
= V
;
4105 ++NumVectorInstructions
;
4109 case Instruction::Call
: {
4110 CallInst
*CI
= cast
<CallInst
>(VL0
);
4111 setInsertPointAfterBundle(E
);
4113 Intrinsic::ID IID
= Intrinsic::not_intrinsic
;
4114 if (Function
*FI
= CI
->getCalledFunction())
4115 IID
= FI
->getIntrinsicID();
4117 Value
*ScalarArg
= nullptr;
4118 std::vector
<Value
*> OpVecs
;
4119 for (int j
= 0, e
= CI
->getNumArgOperands(); j
< e
; ++j
) {
4121 // Some intrinsics have scalar arguments. This argument should not be
4123 if (hasVectorInstrinsicScalarOpd(IID
, j
)) {
4124 CallInst
*CEI
= cast
<CallInst
>(VL0
);
4125 ScalarArg
= CEI
->getArgOperand(j
);
4126 OpVecs
.push_back(CEI
->getArgOperand(j
));
4130 Value
*OpVec
= vectorizeTree(E
->getOperand(j
));
4131 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j
<< "]: " << *OpVec
<< "\n");
4132 OpVecs
.push_back(OpVec
);
4135 Module
*M
= F
->getParent();
4136 Intrinsic::ID ID
= getVectorIntrinsicIDForCall(CI
, TLI
);
4137 Type
*Tys
[] = { VectorType::get(CI
->getType(), E
->Scalars
.size()) };
4138 Function
*CF
= Intrinsic::getDeclaration(M
, ID
, Tys
);
4139 SmallVector
<OperandBundleDef
, 1> OpBundles
;
4140 CI
->getOperandBundlesAsDefs(OpBundles
);
4141 Value
*V
= Builder
.CreateCall(CF
, OpVecs
, OpBundles
);
4143 // The scalar argument uses an in-tree scalar so we add the new vectorized
4144 // call to ExternalUses list to make sure that an extract will be
4145 // generated in the future.
4146 if (ScalarArg
&& getTreeEntry(ScalarArg
))
4147 ExternalUses
.push_back(ExternalUser(ScalarArg
, cast
<User
>(V
), 0));
4149 propagateIRFlags(V
, E
->Scalars
, VL0
);
4150 if (NeedToShuffleReuses
) {
4151 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4152 E
->ReuseShuffleIndices
, "shuffle");
4154 E
->VectorizedValue
= V
;
4155 ++NumVectorInstructions
;
4158 case Instruction::ShuffleVector
: {
4159 assert(E
->isAltShuffle() &&
4160 ((Instruction::isBinaryOp(E
->getOpcode()) &&
4161 Instruction::isBinaryOp(E
->getAltOpcode())) ||
4162 (Instruction::isCast(E
->getOpcode()) &&
4163 Instruction::isCast(E
->getAltOpcode()))) &&
4164 "Invalid Shuffle Vector Operand");
4166 Value
*LHS
= nullptr, *RHS
= nullptr;
4167 if (Instruction::isBinaryOp(E
->getOpcode())) {
4168 setInsertPointAfterBundle(E
);
4169 LHS
= vectorizeTree(E
->getOperand(0));
4170 RHS
= vectorizeTree(E
->getOperand(1));
4172 setInsertPointAfterBundle(E
);
4173 LHS
= vectorizeTree(E
->getOperand(0));
4176 if (E
->VectorizedValue
) {
4177 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0
<< ".\n");
4178 return E
->VectorizedValue
;
4182 if (Instruction::isBinaryOp(E
->getOpcode())) {
4183 V0
= Builder
.CreateBinOp(
4184 static_cast<Instruction::BinaryOps
>(E
->getOpcode()), LHS
, RHS
);
4185 V1
= Builder
.CreateBinOp(
4186 static_cast<Instruction::BinaryOps
>(E
->getAltOpcode()), LHS
, RHS
);
4188 V0
= Builder
.CreateCast(
4189 static_cast<Instruction::CastOps
>(E
->getOpcode()), LHS
, VecTy
);
4190 V1
= Builder
.CreateCast(
4191 static_cast<Instruction::CastOps
>(E
->getAltOpcode()), LHS
, VecTy
);
4194 // Create shuffle to take alternate operations from the vector.
4195 // Also, gather up main and alt scalar ops to propagate IR flags to
4196 // each vector operation.
4197 ValueList OpScalars
, AltScalars
;
4198 unsigned e
= E
->Scalars
.size();
4199 SmallVector
<Constant
*, 8> Mask(e
);
4200 for (unsigned i
= 0; i
< e
; ++i
) {
4201 auto *OpInst
= cast
<Instruction
>(E
->Scalars
[i
]);
4202 assert(E
->isOpcodeOrAlt(OpInst
) && "Unexpected main/alternate opcode");
4203 if (OpInst
->getOpcode() == E
->getAltOpcode()) {
4204 Mask
[i
] = Builder
.getInt32(e
+ i
);
4205 AltScalars
.push_back(E
->Scalars
[i
]);
4207 Mask
[i
] = Builder
.getInt32(i
);
4208 OpScalars
.push_back(E
->Scalars
[i
]);
4212 Value
*ShuffleMask
= ConstantVector::get(Mask
);
4213 propagateIRFlags(V0
, OpScalars
);
4214 propagateIRFlags(V1
, AltScalars
);
4216 Value
*V
= Builder
.CreateShuffleVector(V0
, V1
, ShuffleMask
);
4217 if (Instruction
*I
= dyn_cast
<Instruction
>(V
))
4218 V
= propagateMetadata(I
, E
->Scalars
);
4219 if (NeedToShuffleReuses
) {
4220 V
= Builder
.CreateShuffleVector(V
, UndefValue::get(VecTy
),
4221 E
->ReuseShuffleIndices
, "shuffle");
4223 E
->VectorizedValue
= V
;
4224 ++NumVectorInstructions
;
4229 llvm_unreachable("unknown inst");
4234 Value
*BoUpSLP::vectorizeTree() {
4235 ExtraValueToDebugLocsMap ExternallyUsedValues
;
4236 return vectorizeTree(ExternallyUsedValues
);
4240 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap
&ExternallyUsedValues
) {
4241 // All blocks must be scheduled before any instructions are inserted.
4242 for (auto &BSIter
: BlocksSchedules
) {
4243 scheduleBlock(BSIter
.second
.get());
4246 Builder
.SetInsertPoint(&F
->getEntryBlock().front());
4247 auto *VectorRoot
= vectorizeTree(VectorizableTree
[0].get());
4249 // If the vectorized tree can be rewritten in a smaller type, we truncate the
4250 // vectorized root. InstCombine will then rewrite the entire expression. We
4251 // sign extend the extracted values below.
4252 auto *ScalarRoot
= VectorizableTree
[0]->Scalars
[0];
4253 if (MinBWs
.count(ScalarRoot
)) {
4254 if (auto *I
= dyn_cast
<Instruction
>(VectorRoot
))
4255 Builder
.SetInsertPoint(&*++BasicBlock::iterator(I
));
4256 auto BundleWidth
= VectorizableTree
[0]->Scalars
.size();
4257 auto *MinTy
= IntegerType::get(F
->getContext(), MinBWs
[ScalarRoot
].first
);
4258 auto *VecTy
= VectorType::get(MinTy
, BundleWidth
);
4259 auto *Trunc
= Builder
.CreateTrunc(VectorRoot
, VecTy
);
4260 VectorizableTree
[0]->VectorizedValue
= Trunc
;
4263 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses
.size()
4266 // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4267 // specified by ScalarType.
4268 auto extend
= [&](Value
*ScalarRoot
, Value
*Ex
, Type
*ScalarType
) {
4269 if (!MinBWs
.count(ScalarRoot
))
4271 if (MinBWs
[ScalarRoot
].second
)
4272 return Builder
.CreateSExt(Ex
, ScalarType
);
4273 return Builder
.CreateZExt(Ex
, ScalarType
);
4276 // Extract all of the elements with the external uses.
4277 for (const auto &ExternalUse
: ExternalUses
) {
4278 Value
*Scalar
= ExternalUse
.Scalar
;
4279 llvm::User
*User
= ExternalUse
.User
;
4281 // Skip users that we already RAUW. This happens when one instruction
4282 // has multiple uses of the same value.
4283 if (User
&& !is_contained(Scalar
->users(), User
))
4285 TreeEntry
*E
= getTreeEntry(Scalar
);
4286 assert(E
&& "Invalid scalar");
4287 assert(!E
->NeedToGather
&& "Extracting from a gather list");
4289 Value
*Vec
= E
->VectorizedValue
;
4290 assert(Vec
&& "Can't find vectorizable value");
4292 Value
*Lane
= Builder
.getInt32(ExternalUse
.Lane
);
4293 // If User == nullptr, the Scalar is used as extra arg. Generate
4294 // ExtractElement instruction and update the record for this scalar in
4295 // ExternallyUsedValues.
4297 assert(ExternallyUsedValues
.count(Scalar
) &&
4298 "Scalar with nullptr as an external user must be registered in "
4299 "ExternallyUsedValues map");
4300 if (auto *VecI
= dyn_cast
<Instruction
>(Vec
)) {
4301 Builder
.SetInsertPoint(VecI
->getParent(),
4302 std::next(VecI
->getIterator()));
4304 Builder
.SetInsertPoint(&F
->getEntryBlock().front());
4306 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4307 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4308 CSEBlocks
.insert(cast
<Instruction
>(Scalar
)->getParent());
4309 auto &Locs
= ExternallyUsedValues
[Scalar
];
4310 ExternallyUsedValues
.insert({Ex
, Locs
});
4311 ExternallyUsedValues
.erase(Scalar
);
4312 // Required to update internally referenced instructions.
4313 Scalar
->replaceAllUsesWith(Ex
);
4317 // Generate extracts for out-of-tree users.
4318 // Find the insertion point for the extractelement lane.
4319 if (auto *VecI
= dyn_cast
<Instruction
>(Vec
)) {
4320 if (PHINode
*PH
= dyn_cast
<PHINode
>(User
)) {
4321 for (int i
= 0, e
= PH
->getNumIncomingValues(); i
!= e
; ++i
) {
4322 if (PH
->getIncomingValue(i
) == Scalar
) {
4323 Instruction
*IncomingTerminator
=
4324 PH
->getIncomingBlock(i
)->getTerminator();
4325 if (isa
<CatchSwitchInst
>(IncomingTerminator
)) {
4326 Builder
.SetInsertPoint(VecI
->getParent(),
4327 std::next(VecI
->getIterator()));
4329 Builder
.SetInsertPoint(PH
->getIncomingBlock(i
)->getTerminator());
4331 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4332 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4333 CSEBlocks
.insert(PH
->getIncomingBlock(i
));
4334 PH
->setOperand(i
, Ex
);
4338 Builder
.SetInsertPoint(cast
<Instruction
>(User
));
4339 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4340 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4341 CSEBlocks
.insert(cast
<Instruction
>(User
)->getParent());
4342 User
->replaceUsesOfWith(Scalar
, Ex
);
4345 Builder
.SetInsertPoint(&F
->getEntryBlock().front());
4346 Value
*Ex
= Builder
.CreateExtractElement(Vec
, Lane
);
4347 Ex
= extend(ScalarRoot
, Ex
, Scalar
->getType());
4348 CSEBlocks
.insert(&F
->getEntryBlock());
4349 User
->replaceUsesOfWith(Scalar
, Ex
);
4352 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User
<< ".\n");
4355 // For each vectorized value:
4356 for (auto &TEPtr
: VectorizableTree
) {
4357 TreeEntry
*Entry
= TEPtr
.get();
4359 // No need to handle users of gathered values.
4360 if (Entry
->NeedToGather
)
4363 assert(Entry
->VectorizedValue
&& "Can't find vectorizable value");
4366 for (int Lane
= 0, LE
= Entry
->Scalars
.size(); Lane
!= LE
; ++Lane
) {
4367 Value
*Scalar
= Entry
->Scalars
[Lane
];
4370 Type
*Ty
= Scalar
->getType();
4371 if (!Ty
->isVoidTy()) {
4372 for (User
*U
: Scalar
->users()) {
4373 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U
<< ".\n");
4375 // It is legal to delete users in the ignorelist.
4376 assert((getTreeEntry(U
) || is_contained(UserIgnoreList
, U
)) &&
4377 "Deleting out-of-tree value");
4381 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar
<< ".\n");
4382 eraseInstruction(cast
<Instruction
>(Scalar
));
4386 Builder
.ClearInsertionPoint();
4388 return VectorizableTree
[0]->VectorizedValue
;
4391 void BoUpSLP::optimizeGatherSequence() {
4392 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq
.size()
4393 << " gather sequences instructions.\n");
4394 // LICM InsertElementInst sequences.
4395 for (Instruction
*I
: GatherSeq
) {
4399 // Check if this block is inside a loop.
4400 Loop
*L
= LI
->getLoopFor(I
->getParent());
4404 // Check if it has a preheader.
4405 BasicBlock
*PreHeader
= L
->getLoopPreheader();
4409 // If the vector or the element that we insert into it are
4410 // instructions that are defined in this basic block then we can't
4411 // hoist this instruction.
4412 auto *Op0
= dyn_cast
<Instruction
>(I
->getOperand(0));
4413 auto *Op1
= dyn_cast
<Instruction
>(I
->getOperand(1));
4414 if (Op0
&& L
->contains(Op0
))
4416 if (Op1
&& L
->contains(Op1
))
4419 // We can hoist this instruction. Move it to the pre-header.
4420 I
->moveBefore(PreHeader
->getTerminator());
4423 // Make a list of all reachable blocks in our CSE queue.
4424 SmallVector
<const DomTreeNode
*, 8> CSEWorkList
;
4425 CSEWorkList
.reserve(CSEBlocks
.size());
4426 for (BasicBlock
*BB
: CSEBlocks
)
4427 if (DomTreeNode
*N
= DT
->getNode(BB
)) {
4428 assert(DT
->isReachableFromEntry(N
));
4429 CSEWorkList
.push_back(N
);
4432 // Sort blocks by domination. This ensures we visit a block after all blocks
4433 // dominating it are visited.
4434 llvm::stable_sort(CSEWorkList
,
4435 [this](const DomTreeNode
*A
, const DomTreeNode
*B
) {
4436 return DT
->properlyDominates(A
, B
);
4439 // Perform O(N^2) search over the gather sequences and merge identical
4440 // instructions. TODO: We can further optimize this scan if we split the
4441 // instructions into different buckets based on the insert lane.
4442 SmallVector
<Instruction
*, 16> Visited
;
4443 for (auto I
= CSEWorkList
.begin(), E
= CSEWorkList
.end(); I
!= E
; ++I
) {
4444 assert((I
== CSEWorkList
.begin() || !DT
->dominates(*I
, *std::prev(I
))) &&
4445 "Worklist not sorted properly!");
4446 BasicBlock
*BB
= (*I
)->getBlock();
4447 // For all instructions in blocks containing gather sequences:
4448 for (BasicBlock::iterator it
= BB
->begin(), e
= BB
->end(); it
!= e
;) {
4449 Instruction
*In
= &*it
++;
4452 if (!isa
<InsertElementInst
>(In
) && !isa
<ExtractElementInst
>(In
))
4455 // Check if we can replace this instruction with any of the
4456 // visited instructions.
4457 for (Instruction
*v
: Visited
) {
4458 if (In
->isIdenticalTo(v
) &&
4459 DT
->dominates(v
->getParent(), In
->getParent())) {
4460 In
->replaceAllUsesWith(v
);
4461 eraseInstruction(In
);
4467 assert(!is_contained(Visited
, In
));
4468 Visited
.push_back(In
);
4476 // Groups the instructions to a bundle (which is then a single scheduling entity)
4477 // and schedules instructions until the bundle gets ready.
4478 Optional
<BoUpSLP::ScheduleData
*>
4479 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef
<Value
*> VL
, BoUpSLP
*SLP
,
4480 const InstructionsState
&S
) {
4481 if (isa
<PHINode
>(S
.OpValue
))
4484 // Initialize the instruction bundle.
4485 Instruction
*OldScheduleEnd
= ScheduleEnd
;
4486 ScheduleData
*PrevInBundle
= nullptr;
4487 ScheduleData
*Bundle
= nullptr;
4488 bool ReSchedule
= false;
4489 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S
.OpValue
<< "\n");
4491 // Make sure that the scheduling region contains all
4492 // instructions of the bundle.
4493 for (Value
*V
: VL
) {
4494 if (!extendSchedulingRegion(V
, S
))
4498 for (Value
*V
: VL
) {
4499 ScheduleData
*BundleMember
= getScheduleData(V
);
4500 assert(BundleMember
&&
4501 "no ScheduleData for bundle member (maybe not in same basic block)");
4502 if (BundleMember
->IsScheduled
) {
4503 // A bundle member was scheduled as single instruction before and now
4504 // needs to be scheduled as part of the bundle. We just get rid of the
4505 // existing schedule.
4506 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
4507 << " was already scheduled\n");
4510 assert(BundleMember
->isSchedulingEntity() &&
4511 "bundle member already part of other bundle");
4513 PrevInBundle
->NextInBundle
= BundleMember
;
4515 Bundle
= BundleMember
;
4517 BundleMember
->UnscheduledDepsInBundle
= 0;
4518 Bundle
->UnscheduledDepsInBundle
+= BundleMember
->UnscheduledDeps
;
4520 // Group the instructions to a bundle.
4521 BundleMember
->FirstInBundle
= Bundle
;
4522 PrevInBundle
= BundleMember
;
4524 if (ScheduleEnd
!= OldScheduleEnd
) {
4525 // The scheduling region got new instructions at the lower end (or it is a
4526 // new region for the first bundle). This makes it necessary to
4527 // recalculate all dependencies.
4528 // It is seldom that this needs to be done a second time after adding the
4529 // initial bundle to the region.
4530 for (auto *I
= ScheduleStart
; I
!= ScheduleEnd
; I
= I
->getNextNode()) {
4531 doForAllOpcodes(I
, [](ScheduleData
*SD
) {
4532 SD
->clearDependencies();
4539 initialFillReadyList(ReadyInsts
);
4541 assert(Bundle
&& "Failed to find schedule bundle");
4543 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
<< " in block "
4544 << BB
->getName() << "\n");
4546 calculateDependencies(Bundle
, true, SLP
);
4548 // Now try to schedule the new bundle. As soon as the bundle is "ready" it
4549 // means that there are no cyclic dependencies and we can schedule it.
4550 // Note that's important that we don't "schedule" the bundle yet (see
4551 // cancelScheduling).
4552 while (!Bundle
->isReady() && !ReadyInsts
.empty()) {
4554 ScheduleData
*pickedSD
= ReadyInsts
.back();
4555 ReadyInsts
.pop_back();
4557 if (pickedSD
->isSchedulingEntity() && pickedSD
->isReady()) {
4558 schedule(pickedSD
, ReadyInsts
);
4561 if (!Bundle
->isReady()) {
4562 cancelScheduling(VL
, S
.OpValue
);
4568 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef
<Value
*> VL
,
4570 if (isa
<PHINode
>(OpValue
))
4573 ScheduleData
*Bundle
= getScheduleData(OpValue
);
4574 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle
<< "\n");
4575 assert(!Bundle
->IsScheduled
&&
4576 "Can't cancel bundle which is already scheduled");
4577 assert(Bundle
->isSchedulingEntity() && Bundle
->isPartOfBundle() &&
4578 "tried to unbundle something which is not a bundle");
4580 // Un-bundle: make single instructions out of the bundle.
4581 ScheduleData
*BundleMember
= Bundle
;
4582 while (BundleMember
) {
4583 assert(BundleMember
->FirstInBundle
== Bundle
&& "corrupt bundle links");
4584 BundleMember
->FirstInBundle
= BundleMember
;
4585 ScheduleData
*Next
= BundleMember
->NextInBundle
;
4586 BundleMember
->NextInBundle
= nullptr;
4587 BundleMember
->UnscheduledDepsInBundle
= BundleMember
->UnscheduledDeps
;
4588 if (BundleMember
->UnscheduledDepsInBundle
== 0) {
4589 ReadyInsts
.insert(BundleMember
);
4591 BundleMember
= Next
;
4595 BoUpSLP::ScheduleData
*BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
4596 // Allocate a new ScheduleData for the instruction.
4597 if (ChunkPos
>= ChunkSize
) {
4598 ScheduleDataChunks
.push_back(std::make_unique
<ScheduleData
[]>(ChunkSize
));
4601 return &(ScheduleDataChunks
.back()[ChunkPos
++]);
4604 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value
*V
,
4605 const InstructionsState
&S
) {
4606 if (getScheduleData(V
, isOneOf(S
, V
)))
4608 Instruction
*I
= dyn_cast
<Instruction
>(V
);
4609 assert(I
&& "bundle member must be an instruction");
4610 assert(!isa
<PHINode
>(I
) && "phi nodes don't need to be scheduled");
4611 auto &&CheckSheduleForI
= [this, &S
](Instruction
*I
) -> bool {
4612 ScheduleData
*ISD
= getScheduleData(I
);
4615 assert(isInSchedulingRegion(ISD
) &&
4616 "ScheduleData not in scheduling region");
4617 ScheduleData
*SD
= allocateScheduleDataChunks();
4619 SD
->init(SchedulingRegionID
, S
.OpValue
);
4620 ExtraScheduleDataMap
[I
][S
.OpValue
] = SD
;
4623 if (CheckSheduleForI(I
))
4625 if (!ScheduleStart
) {
4626 // It's the first instruction in the new region.
4627 initScheduleData(I
, I
->getNextNode(), nullptr, nullptr);
4629 ScheduleEnd
= I
->getNextNode();
4630 if (isOneOf(S
, I
) != I
)
4631 CheckSheduleForI(I
);
4632 assert(ScheduleEnd
&& "tried to vectorize a terminator?");
4633 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I
<< "\n");
4636 // Search up and down at the same time, because we don't know if the new
4637 // instruction is above or below the existing scheduling region.
4638 BasicBlock::reverse_iterator UpIter
=
4639 ++ScheduleStart
->getIterator().getReverse();
4640 BasicBlock::reverse_iterator UpperEnd
= BB
->rend();
4641 BasicBlock::iterator DownIter
= ScheduleEnd
->getIterator();
4642 BasicBlock::iterator LowerEnd
= BB
->end();
4644 if (++ScheduleRegionSize
> ScheduleRegionSizeLimit
) {
4645 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
4649 if (UpIter
!= UpperEnd
) {
4650 if (&*UpIter
== I
) {
4651 initScheduleData(I
, ScheduleStart
, nullptr, FirstLoadStoreInRegion
);
4653 if (isOneOf(S
, I
) != I
)
4654 CheckSheduleForI(I
);
4655 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
4661 if (DownIter
!= LowerEnd
) {
4662 if (&*DownIter
== I
) {
4663 initScheduleData(ScheduleEnd
, I
->getNextNode(), LastLoadStoreInRegion
,
4665 ScheduleEnd
= I
->getNextNode();
4666 if (isOneOf(S
, I
) != I
)
4667 CheckSheduleForI(I
);
4668 assert(ScheduleEnd
&& "tried to vectorize a terminator?");
4669 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I
4675 assert((UpIter
!= UpperEnd
|| DownIter
!= LowerEnd
) &&
4676 "instruction not found in block");
4681 void BoUpSLP::BlockScheduling::initScheduleData(Instruction
*FromI
,
4683 ScheduleData
*PrevLoadStore
,
4684 ScheduleData
*NextLoadStore
) {
4685 ScheduleData
*CurrentLoadStore
= PrevLoadStore
;
4686 for (Instruction
*I
= FromI
; I
!= ToI
; I
= I
->getNextNode()) {
4687 ScheduleData
*SD
= ScheduleDataMap
[I
];
4689 SD
= allocateScheduleDataChunks();
4690 ScheduleDataMap
[I
] = SD
;
4693 assert(!isInSchedulingRegion(SD
) &&
4694 "new ScheduleData already in scheduling region");
4695 SD
->init(SchedulingRegionID
, I
);
4697 if (I
->mayReadOrWriteMemory() &&
4698 (!isa
<IntrinsicInst
>(I
) ||
4699 cast
<IntrinsicInst
>(I
)->getIntrinsicID() != Intrinsic::sideeffect
)) {
4700 // Update the linked list of memory accessing instructions.
4701 if (CurrentLoadStore
) {
4702 CurrentLoadStore
->NextLoadStore
= SD
;
4704 FirstLoadStoreInRegion
= SD
;
4706 CurrentLoadStore
= SD
;
4709 if (NextLoadStore
) {
4710 if (CurrentLoadStore
)
4711 CurrentLoadStore
->NextLoadStore
= NextLoadStore
;
4713 LastLoadStoreInRegion
= CurrentLoadStore
;
4717 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData
*SD
,
4718 bool InsertInReadyList
,
4720 assert(SD
->isSchedulingEntity());
4722 SmallVector
<ScheduleData
*, 10> WorkList
;
4723 WorkList
.push_back(SD
);
4725 while (!WorkList
.empty()) {
4726 ScheduleData
*SD
= WorkList
.back();
4727 WorkList
.pop_back();
4729 ScheduleData
*BundleMember
= SD
;
4730 while (BundleMember
) {
4731 assert(isInSchedulingRegion(BundleMember
));
4732 if (!BundleMember
->hasValidDependencies()) {
4734 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
4736 BundleMember
->Dependencies
= 0;
4737 BundleMember
->resetUnscheduledDeps();
4739 // Handle def-use chain dependencies.
4740 if (BundleMember
->OpValue
!= BundleMember
->Inst
) {
4741 ScheduleData
*UseSD
= getScheduleData(BundleMember
->Inst
);
4742 if (UseSD
&& isInSchedulingRegion(UseSD
->FirstInBundle
)) {
4743 BundleMember
->Dependencies
++;
4744 ScheduleData
*DestBundle
= UseSD
->FirstInBundle
;
4745 if (!DestBundle
->IsScheduled
)
4746 BundleMember
->incrementUnscheduledDeps(1);
4747 if (!DestBundle
->hasValidDependencies())
4748 WorkList
.push_back(DestBundle
);
4751 for (User
*U
: BundleMember
->Inst
->users()) {
4752 if (isa
<Instruction
>(U
)) {
4753 ScheduleData
*UseSD
= getScheduleData(U
);
4754 if (UseSD
&& isInSchedulingRegion(UseSD
->FirstInBundle
)) {
4755 BundleMember
->Dependencies
++;
4756 ScheduleData
*DestBundle
= UseSD
->FirstInBundle
;
4757 if (!DestBundle
->IsScheduled
)
4758 BundleMember
->incrementUnscheduledDeps(1);
4759 if (!DestBundle
->hasValidDependencies())
4760 WorkList
.push_back(DestBundle
);
4763 // I'm not sure if this can ever happen. But we need to be safe.
4764 // This lets the instruction/bundle never be scheduled and
4765 // eventually disable vectorization.
4766 BundleMember
->Dependencies
++;
4767 BundleMember
->incrementUnscheduledDeps(1);
4772 // Handle the memory dependencies.
4773 ScheduleData
*DepDest
= BundleMember
->NextLoadStore
;
4775 Instruction
*SrcInst
= BundleMember
->Inst
;
4776 MemoryLocation SrcLoc
= getLocation(SrcInst
, SLP
->AA
);
4777 bool SrcMayWrite
= BundleMember
->Inst
->mayWriteToMemory();
4778 unsigned numAliased
= 0;
4779 unsigned DistToSrc
= 1;
4782 assert(isInSchedulingRegion(DepDest
));
4784 // We have two limits to reduce the complexity:
4785 // 1) AliasedCheckLimit: It's a small limit to reduce calls to
4786 // SLP->isAliased (which is the expensive part in this loop).
4787 // 2) MaxMemDepDistance: It's for very large blocks and it aborts
4788 // the whole loop (even if the loop is fast, it's quadratic).
4789 // It's important for the loop break condition (see below) to
4790 // check this limit even between two read-only instructions.
4791 if (DistToSrc
>= MaxMemDepDistance
||
4792 ((SrcMayWrite
|| DepDest
->Inst
->mayWriteToMemory()) &&
4793 (numAliased
>= AliasedCheckLimit
||
4794 SLP
->isAliased(SrcLoc
, SrcInst
, DepDest
->Inst
)))) {
4796 // We increment the counter only if the locations are aliased
4797 // (instead of counting all alias checks). This gives a better
4798 // balance between reduced runtime and accurate dependencies.
4801 DepDest
->MemoryDependencies
.push_back(BundleMember
);
4802 BundleMember
->Dependencies
++;
4803 ScheduleData
*DestBundle
= DepDest
->FirstInBundle
;
4804 if (!DestBundle
->IsScheduled
) {
4805 BundleMember
->incrementUnscheduledDeps(1);
4807 if (!DestBundle
->hasValidDependencies()) {
4808 WorkList
.push_back(DestBundle
);
4811 DepDest
= DepDest
->NextLoadStore
;
4813 // Example, explaining the loop break condition: Let's assume our
4814 // starting instruction is i0 and MaxMemDepDistance = 3.
4817 // i0,i1,i2,i3,i4,i5,i6,i7,i8
4820 // MaxMemDepDistance let us stop alias-checking at i3 and we add
4821 // dependencies from i0 to i3,i4,.. (even if they are not aliased).
4822 // Previously we already added dependencies from i3 to i6,i7,i8
4823 // (because of MaxMemDepDistance). As we added a dependency from
4824 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4825 // and we can abort this loop at i6.
4826 if (DistToSrc
>= 2 * MaxMemDepDistance
)
4832 BundleMember
= BundleMember
->NextInBundle
;
4834 if (InsertInReadyList
&& SD
->isReady()) {
4835 ReadyInsts
.push_back(SD
);
4836 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD
->Inst
4842 void BoUpSLP::BlockScheduling::resetSchedule() {
4843 assert(ScheduleStart
&&
4844 "tried to reset schedule on block which has not been scheduled");
4845 for (Instruction
*I
= ScheduleStart
; I
!= ScheduleEnd
; I
= I
->getNextNode()) {
4846 doForAllOpcodes(I
, [&](ScheduleData
*SD
) {
4847 assert(isInSchedulingRegion(SD
) &&
4848 "ScheduleData not in scheduling region");
4849 SD
->IsScheduled
= false;
4850 SD
->resetUnscheduledDeps();
4856 void BoUpSLP::scheduleBlock(BlockScheduling
*BS
) {
4857 if (!BS
->ScheduleStart
)
4860 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS
->BB
->getName() << "\n");
4862 BS
->resetSchedule();
4864 // For the real scheduling we use a more sophisticated ready-list: it is
4865 // sorted by the original instruction location. This lets the final schedule
4866 // be as close as possible to the original instruction order.
4867 struct ScheduleDataCompare
{
4868 bool operator()(ScheduleData
*SD1
, ScheduleData
*SD2
) const {
4869 return SD2
->SchedulingPriority
< SD1
->SchedulingPriority
;
4872 std::set
<ScheduleData
*, ScheduleDataCompare
> ReadyInsts
;
4874 // Ensure that all dependency data is updated and fill the ready-list with
4875 // initial instructions.
4877 int NumToSchedule
= 0;
4878 for (auto *I
= BS
->ScheduleStart
; I
!= BS
->ScheduleEnd
;
4879 I
= I
->getNextNode()) {
4880 BS
->doForAllOpcodes(I
, [this, &Idx
, &NumToSchedule
, BS
](ScheduleData
*SD
) {
4881 assert(SD
->isPartOfBundle() ==
4882 (getTreeEntry(SD
->Inst
) != nullptr) &&
4883 "scheduler and vectorizer bundle mismatch");
4884 SD
->FirstInBundle
->SchedulingPriority
= Idx
++;
4885 if (SD
->isSchedulingEntity()) {
4886 BS
->calculateDependencies(SD
, false, this);
4891 BS
->initialFillReadyList(ReadyInsts
);
4893 Instruction
*LastScheduledInst
= BS
->ScheduleEnd
;
4895 // Do the "real" scheduling.
4896 while (!ReadyInsts
.empty()) {
4897 ScheduleData
*picked
= *ReadyInsts
.begin();
4898 ReadyInsts
.erase(ReadyInsts
.begin());
4900 // Move the scheduled instruction(s) to their dedicated places, if not
4902 ScheduleData
*BundleMember
= picked
;
4903 while (BundleMember
) {
4904 Instruction
*pickedInst
= BundleMember
->Inst
;
4905 if (LastScheduledInst
->getNextNode() != pickedInst
) {
4906 BS
->BB
->getInstList().remove(pickedInst
);
4907 BS
->BB
->getInstList().insert(LastScheduledInst
->getIterator(),
4910 LastScheduledInst
= pickedInst
;
4911 BundleMember
= BundleMember
->NextInBundle
;
4914 BS
->schedule(picked
, ReadyInsts
);
4917 assert(NumToSchedule
== 0 && "could not schedule all instructions");
4919 // Avoid duplicate scheduling of the block.
4920 BS
->ScheduleStart
= nullptr;
4923 unsigned BoUpSLP::getVectorElementSize(Value
*V
) const {
4924 // If V is a store, just return the width of the stored value without
4925 // traversing the expression tree. This is the common case.
4926 if (auto *Store
= dyn_cast
<StoreInst
>(V
))
4927 return DL
->getTypeSizeInBits(Store
->getValueOperand()->getType());
4929 // If V is not a store, we can traverse the expression tree to find loads
4930 // that feed it. The type of the loaded value may indicate a more suitable
4931 // width than V's type. We want to base the vector element size on the width
4932 // of memory operations where possible.
4933 SmallVector
<Instruction
*, 16> Worklist
;
4934 SmallPtrSet
<Instruction
*, 16> Visited
;
4935 if (auto *I
= dyn_cast
<Instruction
>(V
))
4936 Worklist
.push_back(I
);
4938 // Traverse the expression tree in bottom-up order looking for loads. If we
4939 // encounter an instruction we don't yet handle, we give up.
4941 auto FoundUnknownInst
= false;
4942 while (!Worklist
.empty() && !FoundUnknownInst
) {
4943 auto *I
= Worklist
.pop_back_val();
4946 // We should only be looking at scalar instructions here. If the current
4947 // instruction has a vector type, give up.
4948 auto *Ty
= I
->getType();
4949 if (isa
<VectorType
>(Ty
))
4950 FoundUnknownInst
= true;
4952 // If the current instruction is a load, update MaxWidth to reflect the
4953 // width of the loaded value.
4954 else if (isa
<LoadInst
>(I
))
4955 MaxWidth
= std::max
<unsigned>(MaxWidth
, DL
->getTypeSizeInBits(Ty
));
4957 // Otherwise, we need to visit the operands of the instruction. We only
4958 // handle the interesting cases from buildTree here. If an operand is an
4959 // instruction we haven't yet visited, we add it to the worklist.
4960 else if (isa
<PHINode
>(I
) || isa
<CastInst
>(I
) || isa
<GetElementPtrInst
>(I
) ||
4961 isa
<CmpInst
>(I
) || isa
<SelectInst
>(I
) || isa
<BinaryOperator
>(I
)) {
4962 for (Use
&U
: I
->operands())
4963 if (auto *J
= dyn_cast
<Instruction
>(U
.get()))
4964 if (!Visited
.count(J
))
4965 Worklist
.push_back(J
);
4968 // If we don't yet handle the instruction, give up.
4970 FoundUnknownInst
= true;
4973 // If we didn't encounter a memory access in the expression tree, or if we
4974 // gave up for some reason, just return the width of V.
4975 if (!MaxWidth
|| FoundUnknownInst
)
4976 return DL
->getTypeSizeInBits(V
->getType());
4978 // Otherwise, return the maximum width we found.
4982 // Determine if a value V in a vectorizable expression Expr can be demoted to a
4983 // smaller type with a truncation. We collect the values that will be demoted
4984 // in ToDemote and additional roots that require investigating in Roots.
4985 static bool collectValuesToDemote(Value
*V
, SmallPtrSetImpl
<Value
*> &Expr
,
4986 SmallVectorImpl
<Value
*> &ToDemote
,
4987 SmallVectorImpl
<Value
*> &Roots
) {
4988 // We can always demote constants.
4989 if (isa
<Constant
>(V
)) {
4990 ToDemote
.push_back(V
);
4994 // If the value is not an instruction in the expression with only one use, it
4995 // cannot be demoted.
4996 auto *I
= dyn_cast
<Instruction
>(V
);
4997 if (!I
|| !I
->hasOneUse() || !Expr
.count(I
))
5000 switch (I
->getOpcode()) {
5002 // We can always demote truncations and extensions. Since truncations can
5003 // seed additional demotion, we save the truncated value.
5004 case Instruction::Trunc
:
5005 Roots
.push_back(I
->getOperand(0));
5007 case Instruction::ZExt
:
5008 case Instruction::SExt
:
5011 // We can demote certain binary operations if we can demote both of their
5013 case Instruction::Add
:
5014 case Instruction::Sub
:
5015 case Instruction::Mul
:
5016 case Instruction::And
:
5017 case Instruction::Or
:
5018 case Instruction::Xor
:
5019 if (!collectValuesToDemote(I
->getOperand(0), Expr
, ToDemote
, Roots
) ||
5020 !collectValuesToDemote(I
->getOperand(1), Expr
, ToDemote
, Roots
))
5024 // We can demote selects if we can demote their true and false values.
5025 case Instruction::Select
: {
5026 SelectInst
*SI
= cast
<SelectInst
>(I
);
5027 if (!collectValuesToDemote(SI
->getTrueValue(), Expr
, ToDemote
, Roots
) ||
5028 !collectValuesToDemote(SI
->getFalseValue(), Expr
, ToDemote
, Roots
))
5033 // We can demote phis if we can demote all their incoming operands. Note that
5034 // we don't need to worry about cycles since we ensure single use above.
5035 case Instruction::PHI
: {
5036 PHINode
*PN
= cast
<PHINode
>(I
);
5037 for (Value
*IncValue
: PN
->incoming_values())
5038 if (!collectValuesToDemote(IncValue
, Expr
, ToDemote
, Roots
))
5043 // Otherwise, conservatively give up.
5048 // Record the value that we can demote.
5049 ToDemote
.push_back(V
);
5053 void BoUpSLP::computeMinimumValueSizes() {
5054 // If there are no external uses, the expression tree must be rooted by a
5055 // store. We can't demote in-memory values, so there is nothing to do here.
5056 if (ExternalUses
.empty())
5059 // We only attempt to truncate integer expressions.
5060 auto &TreeRoot
= VectorizableTree
[0]->Scalars
;
5061 auto *TreeRootIT
= dyn_cast
<IntegerType
>(TreeRoot
[0]->getType());
5065 // If the expression is not rooted by a store, these roots should have
5066 // external uses. We will rely on InstCombine to rewrite the expression in
5067 // the narrower type. However, InstCombine only rewrites single-use values.
5068 // This means that if a tree entry other than a root is used externally, it
5069 // must have multiple uses and InstCombine will not rewrite it. The code
5070 // below ensures that only the roots are used externally.
5071 SmallPtrSet
<Value
*, 32> Expr(TreeRoot
.begin(), TreeRoot
.end());
5072 for (auto &EU
: ExternalUses
)
5073 if (!Expr
.erase(EU
.Scalar
))
5078 // Collect the scalar values of the vectorizable expression. We will use this
5079 // context to determine which values can be demoted. If we see a truncation,
5080 // we mark it as seeding another demotion.
5081 for (auto &EntryPtr
: VectorizableTree
)
5082 Expr
.insert(EntryPtr
->Scalars
.begin(), EntryPtr
->Scalars
.end());
5084 // Ensure the roots of the vectorizable tree don't form a cycle. They must
5085 // have a single external user that is not in the vectorizable tree.
5086 for (auto *Root
: TreeRoot
)
5087 if (!Root
->hasOneUse() || Expr
.count(*Root
->user_begin()))
5090 // Conservatively determine if we can actually truncate the roots of the
5091 // expression. Collect the values that can be demoted in ToDemote and
5092 // additional roots that require investigating in Roots.
5093 SmallVector
<Value
*, 32> ToDemote
;
5094 SmallVector
<Value
*, 4> Roots
;
5095 for (auto *Root
: TreeRoot
)
5096 if (!collectValuesToDemote(Root
, Expr
, ToDemote
, Roots
))
5099 // The maximum bit width required to represent all the values that can be
5100 // demoted without loss of precision. It would be safe to truncate the roots
5101 // of the expression to this width.
5102 auto MaxBitWidth
= 8u;
5104 // We first check if all the bits of the roots are demanded. If they're not,
5105 // we can truncate the roots to this narrower type.
5106 for (auto *Root
: TreeRoot
) {
5107 auto Mask
= DB
->getDemandedBits(cast
<Instruction
>(Root
));
5108 MaxBitWidth
= std::max
<unsigned>(
5109 Mask
.getBitWidth() - Mask
.countLeadingZeros(), MaxBitWidth
);
5112 // True if the roots can be zero-extended back to their original type, rather
5113 // than sign-extended. We know that if the leading bits are not demanded, we
5114 // can safely zero-extend. So we initialize IsKnownPositive to True.
5115 bool IsKnownPositive
= true;
5117 // If all the bits of the roots are demanded, we can try a little harder to
5118 // compute a narrower type. This can happen, for example, if the roots are
5119 // getelementptr indices. InstCombine promotes these indices to the pointer
5120 // width. Thus, all their bits are technically demanded even though the
5121 // address computation might be vectorized in a smaller type.
5123 // We start by looking at each entry that can be demoted. We compute the
5124 // maximum bit width required to store the scalar by using ValueTracking to
5125 // compute the number of high-order bits we can truncate.
5126 if (MaxBitWidth
== DL
->getTypeSizeInBits(TreeRoot
[0]->getType()) &&
5127 llvm::all_of(TreeRoot
, [](Value
*R
) {
5128 assert(R
->hasOneUse() && "Root should have only one use!");
5129 return isa
<GetElementPtrInst
>(R
->user_back());
5133 // Determine if the sign bit of all the roots is known to be zero. If not,
5134 // IsKnownPositive is set to False.
5135 IsKnownPositive
= llvm::all_of(TreeRoot
, [&](Value
*R
) {
5136 KnownBits Known
= computeKnownBits(R
, *DL
);
5137 return Known
.isNonNegative();
5140 // Determine the maximum number of bits required to store the scalar
5142 for (auto *Scalar
: ToDemote
) {
5143 auto NumSignBits
= ComputeNumSignBits(Scalar
, *DL
, 0, AC
, nullptr, DT
);
5144 auto NumTypeBits
= DL
->getTypeSizeInBits(Scalar
->getType());
5145 MaxBitWidth
= std::max
<unsigned>(NumTypeBits
- NumSignBits
, MaxBitWidth
);
5148 // If we can't prove that the sign bit is zero, we must add one to the
5149 // maximum bit width to account for the unknown sign bit. This preserves
5150 // the existing sign bit so we can safely sign-extend the root back to the
5151 // original type. Otherwise, if we know the sign bit is zero, we will
5152 // zero-extend the root instead.
5154 // FIXME: This is somewhat suboptimal, as there will be cases where adding
5155 // one to the maximum bit width will yield a larger-than-necessary
5156 // type. In general, we need to add an extra bit only if we can't
5157 // prove that the upper bit of the original type is equal to the
5158 // upper bit of the proposed smaller type. If these two bits are the
5159 // same (either zero or one) we know that sign-extending from the
5160 // smaller type will result in the same value. Here, since we can't
5161 // yet prove this, we are just making the proposed smaller type
5162 // larger to ensure correctness.
5163 if (!IsKnownPositive
)
5167 // Round MaxBitWidth up to the next power-of-two.
5168 if (!isPowerOf2_64(MaxBitWidth
))
5169 MaxBitWidth
= NextPowerOf2(MaxBitWidth
);
5171 // If the maximum bit width we compute is less than the with of the roots'
5172 // type, we can proceed with the narrowing. Otherwise, do nothing.
5173 if (MaxBitWidth
>= TreeRootIT
->getBitWidth())
5176 // If we can truncate the root, we must collect additional values that might
5177 // be demoted as a result. That is, those seeded by truncations we will
5179 while (!Roots
.empty())
5180 collectValuesToDemote(Roots
.pop_back_val(), Expr
, ToDemote
, Roots
);
5182 // Finally, map the values we can demote to the maximum bit with we computed.
5183 for (auto *Scalar
: ToDemote
)
5184 MinBWs
[Scalar
] = std::make_pair(MaxBitWidth
, !IsKnownPositive
);
5189 /// The SLPVectorizer Pass.
5190 struct SLPVectorizer
: public FunctionPass
{
5191 SLPVectorizerPass Impl
;
5193 /// Pass identification, replacement for typeid
5196 explicit SLPVectorizer() : FunctionPass(ID
) {
5197 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5200 bool doInitialization(Module
&M
) override
{
5204 bool runOnFunction(Function
&F
) override
{
5205 if (skipFunction(F
))
5208 auto *SE
= &getAnalysis
<ScalarEvolutionWrapperPass
>().getSE();
5209 auto *TTI
= &getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
5210 auto *TLIP
= getAnalysisIfAvailable
<TargetLibraryInfoWrapperPass
>();
5211 auto *TLI
= TLIP
? &TLIP
->getTLI(F
) : nullptr;
5212 auto *AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
5213 auto *LI
= &getAnalysis
<LoopInfoWrapperPass
>().getLoopInfo();
5214 auto *DT
= &getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
5215 auto *AC
= &getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
);
5216 auto *DB
= &getAnalysis
<DemandedBitsWrapperPass
>().getDemandedBits();
5217 auto *ORE
= &getAnalysis
<OptimizationRemarkEmitterWrapperPass
>().getORE();
5219 return Impl
.runImpl(F
, SE
, TTI
, TLI
, AA
, LI
, DT
, AC
, DB
, ORE
);
5222 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
5223 FunctionPass::getAnalysisUsage(AU
);
5224 AU
.addRequired
<AssumptionCacheTracker
>();
5225 AU
.addRequired
<ScalarEvolutionWrapperPass
>();
5226 AU
.addRequired
<AAResultsWrapperPass
>();
5227 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
5228 AU
.addRequired
<LoopInfoWrapperPass
>();
5229 AU
.addRequired
<DominatorTreeWrapperPass
>();
5230 AU
.addRequired
<DemandedBitsWrapperPass
>();
5231 AU
.addRequired
<OptimizationRemarkEmitterWrapperPass
>();
5232 AU
.addPreserved
<LoopInfoWrapperPass
>();
5233 AU
.addPreserved
<DominatorTreeWrapperPass
>();
5234 AU
.addPreserved
<AAResultsWrapperPass
>();
5235 AU
.addPreserved
<GlobalsAAWrapperPass
>();
5236 AU
.setPreservesCFG();
5240 } // end anonymous namespace
5242 PreservedAnalyses
SLPVectorizerPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
5243 auto *SE
= &AM
.getResult
<ScalarEvolutionAnalysis
>(F
);
5244 auto *TTI
= &AM
.getResult
<TargetIRAnalysis
>(F
);
5245 auto *TLI
= AM
.getCachedResult
<TargetLibraryAnalysis
>(F
);
5246 auto *AA
= &AM
.getResult
<AAManager
>(F
);
5247 auto *LI
= &AM
.getResult
<LoopAnalysis
>(F
);
5248 auto *DT
= &AM
.getResult
<DominatorTreeAnalysis
>(F
);
5249 auto *AC
= &AM
.getResult
<AssumptionAnalysis
>(F
);
5250 auto *DB
= &AM
.getResult
<DemandedBitsAnalysis
>(F
);
5251 auto *ORE
= &AM
.getResult
<OptimizationRemarkEmitterAnalysis
>(F
);
5253 bool Changed
= runImpl(F
, SE
, TTI
, TLI
, AA
, LI
, DT
, AC
, DB
, ORE
);
5255 return PreservedAnalyses::all();
5257 PreservedAnalyses PA
;
5258 PA
.preserveSet
<CFGAnalyses
>();
5259 PA
.preserve
<AAManager
>();
5260 PA
.preserve
<GlobalsAA
>();
5264 bool SLPVectorizerPass::runImpl(Function
&F
, ScalarEvolution
*SE_
,
5265 TargetTransformInfo
*TTI_
,
5266 TargetLibraryInfo
*TLI_
, AliasAnalysis
*AA_
,
5267 LoopInfo
*LI_
, DominatorTree
*DT_
,
5268 AssumptionCache
*AC_
, DemandedBits
*DB_
,
5269 OptimizationRemarkEmitter
*ORE_
) {
5278 DL
= &F
.getParent()->getDataLayout();
5282 bool Changed
= false;
5284 // If the target claims to have no vector registers don't attempt
5286 if (!TTI
->getNumberOfRegisters(TTI
->getRegisterClassForType(true)))
5289 // Don't vectorize when the attribute NoImplicitFloat is used.
5290 if (F
.hasFnAttribute(Attribute::NoImplicitFloat
))
5293 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F
.getName() << ".\n");
5295 // Use the bottom up slp vectorizer to construct chains that start with
5296 // store instructions.
5297 BoUpSLP
R(&F
, SE
, TTI
, TLI
, AA
, LI
, DT
, AC
, DB
, DL
, ORE_
);
5299 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5300 // delete instructions.
5302 // Scan the blocks in the function in post order.
5303 for (auto BB
: post_order(&F
.getEntryBlock())) {
5304 collectSeedInstructions(BB
);
5306 // Vectorize trees that end at stores.
5307 if (!Stores
.empty()) {
5308 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores
.size()
5309 << " underlying objects.\n");
5310 Changed
|= vectorizeStoreChains(R
);
5313 // Vectorize trees that end at reductions.
5314 Changed
|= vectorizeChainsInBlock(BB
, R
);
5316 // Vectorize the index computations of getelementptr instructions. This
5317 // is primarily intended to catch gather-like idioms ending at
5318 // non-consecutive loads.
5319 if (!GEPs
.empty()) {
5320 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs
.size()
5321 << " underlying objects.\n");
5322 Changed
|= vectorizeGEPIndices(BB
, R
);
5327 R
.optimizeGatherSequence();
5328 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F
.getName() << "\"\n");
5329 LLVM_DEBUG(verifyFunction(F
));
5334 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef
<Value
*> Chain
, BoUpSLP
&R
,
5335 unsigned VecRegSize
) {
5336 const unsigned ChainLen
= Chain
.size();
5337 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
5339 const unsigned Sz
= R
.getVectorElementSize(Chain
[0]);
5340 const unsigned VF
= VecRegSize
/ Sz
;
5342 if (!isPowerOf2_32(Sz
) || VF
< 2)
5345 bool Changed
= false;
5346 // Look for profitable vectorizable trees at all offsets, starting at zero.
5347 for (unsigned i
= 0, e
= ChainLen
; i
+ VF
<= e
; ++i
) {
5349 ArrayRef
<Value
*> Operands
= Chain
.slice(i
, VF
);
5350 // Check that a previous iteration of this loop did not delete the Value.
5351 if (llvm::any_of(Operands
, [&R
](Value
*V
) {
5352 auto *I
= dyn_cast
<Instruction
>(V
);
5353 return I
&& R
.isDeleted(I
);
5357 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF
<< " stores at offset " << i
5360 R
.buildTree(Operands
);
5361 if (R
.isTreeTinyAndNotFullyVectorizable())
5364 R
.computeMinimumValueSizes();
5366 int Cost
= R
.getTreeCost();
5368 LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost
<< " for VF=" << VF
5370 if (Cost
< -SLPCostThreshold
) {
5371 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost
<< "\n");
5373 using namespace ore
;
5375 R
.getORE()->emit(OptimizationRemark(SV_NAME
, "StoresVectorized",
5376 cast
<StoreInst
>(Chain
[i
]))
5377 << "Stores SLP vectorized with cost " << NV("Cost", Cost
)
5378 << " and with tree size "
5379 << NV("TreeSize", R
.getTreeSize()));
5383 // Move to the next bundle.
5392 bool SLPVectorizerPass::vectorizeStores(ArrayRef
<StoreInst
*> Stores
,
5394 SetVector
<StoreInst
*> Heads
;
5395 SmallDenseSet
<StoreInst
*> Tails
;
5396 SmallDenseMap
<StoreInst
*, StoreInst
*> ConsecutiveChain
;
5398 // We may run into multiple chains that merge into a single chain. We mark the
5399 // stores that we vectorized so that we don't visit the same store twice.
5400 BoUpSLP::ValueSet VectorizedStores
;
5401 bool Changed
= false;
5403 auto &&FindConsecutiveAccess
=
5404 [this, &Stores
, &Heads
, &Tails
, &ConsecutiveChain
] (int K
, int Idx
) {
5405 if (!isConsecutiveAccess(Stores
[K
], Stores
[Idx
], *DL
, *SE
))
5408 Tails
.insert(Stores
[Idx
]);
5409 Heads
.insert(Stores
[K
]);
5410 ConsecutiveChain
[Stores
[K
]] = Stores
[Idx
];
5414 // Do a quadratic search on all of the given stores in reverse order and find
5415 // all of the pairs of stores that follow each other.
5416 int E
= Stores
.size();
5417 for (int Idx
= E
- 1; Idx
>= 0; --Idx
) {
5418 // If a store has multiple consecutive store candidates, search according
5419 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
5420 // This is because usually pairing with immediate succeeding or preceding
5421 // candidate create the best chance to find slp vectorization opportunity.
5422 for (int Offset
= 1, F
= std::max(E
- Idx
, Idx
+ 1); Offset
< F
; ++Offset
)
5423 if ((Idx
>= Offset
&& FindConsecutiveAccess(Idx
- Offset
, Idx
)) ||
5424 (Idx
+ Offset
< E
&& FindConsecutiveAccess(Idx
+ Offset
, Idx
)))
5428 // For stores that start but don't end a link in the chain:
5429 for (auto *SI
: llvm::reverse(Heads
)) {
5430 if (Tails
.count(SI
))
5433 // We found a store instr that starts a chain. Now follow the chain and try
5435 BoUpSLP::ValueList Operands
;
5437 // Collect the chain into a list.
5438 while ((Tails
.count(I
) || Heads
.count(I
)) && !VectorizedStores
.count(I
)) {
5439 Operands
.push_back(I
);
5440 // Move to the next value in the chain.
5441 I
= ConsecutiveChain
[I
];
5444 // FIXME: Is division-by-2 the correct step? Should we assert that the
5445 // register size is a power-of-2?
5446 for (unsigned Size
= R
.getMaxVecRegSize(); Size
>= R
.getMinVecRegSize();
5448 if (vectorizeStoreChain(Operands
, R
, Size
)) {
5449 // Mark the vectorized stores so that we don't vectorize them again.
5450 VectorizedStores
.insert(Operands
.begin(), Operands
.end());
5460 void SLPVectorizerPass::collectSeedInstructions(BasicBlock
*BB
) {
5461 // Initialize the collections. We will make a single pass over the block.
5465 // Visit the store and getelementptr instructions in BB and organize them in
5466 // Stores and GEPs according to the underlying objects of their pointer
5468 for (Instruction
&I
: *BB
) {
5469 // Ignore store instructions that are volatile or have a pointer operand
5470 // that doesn't point to a scalar type.
5471 if (auto *SI
= dyn_cast
<StoreInst
>(&I
)) {
5472 if (!SI
->isSimple())
5474 if (!isValidElementType(SI
->getValueOperand()->getType()))
5476 Stores
[GetUnderlyingObject(SI
->getPointerOperand(), *DL
)].push_back(SI
);
5479 // Ignore getelementptr instructions that have more than one index, a
5480 // constant index, or a pointer operand that doesn't point to a scalar
5482 else if (auto *GEP
= dyn_cast
<GetElementPtrInst
>(&I
)) {
5483 auto Idx
= GEP
->idx_begin()->get();
5484 if (GEP
->getNumIndices() > 1 || isa
<Constant
>(Idx
))
5486 if (!isValidElementType(Idx
->getType()))
5488 if (GEP
->getType()->isVectorTy())
5490 GEPs
[GEP
->getPointerOperand()].push_back(GEP
);
5495 bool SLPVectorizerPass::tryToVectorizePair(Value
*A
, Value
*B
, BoUpSLP
&R
) {
5498 Value
*VL
[] = { A
, B
};
5499 return tryToVectorizeList(VL
, R
, /*UserCost=*/0, true);
5502 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef
<Value
*> VL
, BoUpSLP
&R
,
5503 int UserCost
, bool AllowReorder
) {
5507 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
5508 << VL
.size() << ".\n");
5510 // Check that all of the parts are scalar instructions of the same type,
5511 // we permit an alternate opcode via InstructionsState.
5512 InstructionsState S
= getSameOpcode(VL
);
5516 Instruction
*I0
= cast
<Instruction
>(S
.OpValue
);
5517 unsigned Sz
= R
.getVectorElementSize(I0
);
5518 unsigned MinVF
= std::max(2U, R
.getMinVecRegSize() / Sz
);
5519 unsigned MaxVF
= std::max
<unsigned>(PowerOf2Floor(VL
.size()), MinVF
);
5521 R
.getORE()->emit([&]() {
5522 return OptimizationRemarkMissed(SV_NAME
, "SmallVF", I0
)
5523 << "Cannot SLP vectorize list: vectorization factor "
5524 << "less than 2 is not supported";
5529 for (Value
*V
: VL
) {
5530 Type
*Ty
= V
->getType();
5531 if (!isValidElementType(Ty
)) {
5532 // NOTE: the following will give user internal llvm type name, which may
5534 R
.getORE()->emit([&]() {
5535 std::string type_str
;
5536 llvm::raw_string_ostream
rso(type_str
);
5538 return OptimizationRemarkMissed(SV_NAME
, "UnsupportedType", I0
)
5539 << "Cannot SLP vectorize list: type "
5540 << rso
.str() + " is unsupported by vectorizer";
5546 bool Changed
= false;
5547 bool CandidateFound
= false;
5548 int MinCost
= SLPCostThreshold
;
5550 unsigned NextInst
= 0, MaxInst
= VL
.size();
5551 for (unsigned VF
= MaxVF
; NextInst
+ 1 < MaxInst
&& VF
>= MinVF
; VF
/= 2) {
5552 // No actual vectorization should happen, if number of parts is the same as
5553 // provided vectorization factor (i.e. the scalar type is used for vector
5554 // code during codegen).
5555 auto *VecTy
= VectorType::get(VL
[0]->getType(), VF
);
5556 if (TTI
->getNumberOfParts(VecTy
) == VF
)
5558 for (unsigned I
= NextInst
; I
< MaxInst
; ++I
) {
5559 unsigned OpsWidth
= 0;
5561 if (I
+ VF
> MaxInst
)
5562 OpsWidth
= MaxInst
- I
;
5566 if (!isPowerOf2_32(OpsWidth
) || OpsWidth
< 2)
5569 ArrayRef
<Value
*> Ops
= VL
.slice(I
, OpsWidth
);
5570 // Check that a previous iteration of this loop did not delete the Value.
5571 if (llvm::any_of(Ops
, [&R
](Value
*V
) {
5572 auto *I
= dyn_cast
<Instruction
>(V
);
5573 return I
&& R
.isDeleted(I
);
5577 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth
<< " operations "
5581 Optional
<ArrayRef
<unsigned>> Order
= R
.bestOrder();
5582 // TODO: check if we can allow reordering for more cases.
5583 if (AllowReorder
&& Order
) {
5584 // TODO: reorder tree nodes without tree rebuilding.
5585 // Conceptually, there is nothing actually preventing us from trying to
5586 // reorder a larger list. In fact, we do exactly this when vectorizing
5587 // reductions. However, at this point, we only expect to get here when
5588 // there are exactly two operations.
5589 assert(Ops
.size() == 2);
5590 Value
*ReorderedOps
[] = {Ops
[1], Ops
[0]};
5591 R
.buildTree(ReorderedOps
, None
);
5593 if (R
.isTreeTinyAndNotFullyVectorizable())
5596 R
.computeMinimumValueSizes();
5597 int Cost
= R
.getTreeCost() - UserCost
;
5598 CandidateFound
= true;
5599 MinCost
= std::min(MinCost
, Cost
);
5601 if (Cost
< -SLPCostThreshold
) {
5602 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost
<< ".\n");
5603 R
.getORE()->emit(OptimizationRemark(SV_NAME
, "VectorizedList",
5604 cast
<Instruction
>(Ops
[0]))
5605 << "SLP vectorized with cost " << ore::NV("Cost", Cost
)
5606 << " and with tree size "
5607 << ore::NV("TreeSize", R
.getTreeSize()));
5610 // Move to the next bundle.
5618 if (!Changed
&& CandidateFound
) {
5619 R
.getORE()->emit([&]() {
5620 return OptimizationRemarkMissed(SV_NAME
, "NotBeneficial", I0
)
5621 << "List vectorization was possible but not beneficial with cost "
5622 << ore::NV("Cost", MinCost
) << " >= "
5623 << ore::NV("Treshold", -SLPCostThreshold
);
5625 } else if (!Changed
) {
5626 R
.getORE()->emit([&]() {
5627 return OptimizationRemarkMissed(SV_NAME
, "NotPossible", I0
)
5628 << "Cannot SLP vectorize list: vectorization was impossible"
5629 << " with available vectorization factors";
5635 bool SLPVectorizerPass::tryToVectorize(Instruction
*I
, BoUpSLP
&R
) {
5639 if (!isa
<BinaryOperator
>(I
) && !isa
<CmpInst
>(I
))
5642 Value
*P
= I
->getParent();
5644 // Vectorize in current basic block only.
5645 auto *Op0
= dyn_cast
<Instruction
>(I
->getOperand(0));
5646 auto *Op1
= dyn_cast
<Instruction
>(I
->getOperand(1));
5647 if (!Op0
|| !Op1
|| Op0
->getParent() != P
|| Op1
->getParent() != P
)
5650 // Try to vectorize V.
5651 if (tryToVectorizePair(Op0
, Op1
, R
))
5654 auto *A
= dyn_cast
<BinaryOperator
>(Op0
);
5655 auto *B
= dyn_cast
<BinaryOperator
>(Op1
);
5657 if (B
&& B
->hasOneUse()) {
5658 auto *B0
= dyn_cast
<BinaryOperator
>(B
->getOperand(0));
5659 auto *B1
= dyn_cast
<BinaryOperator
>(B
->getOperand(1));
5660 if (B0
&& B0
->getParent() == P
&& tryToVectorizePair(A
, B0
, R
))
5662 if (B1
&& B1
->getParent() == P
&& tryToVectorizePair(A
, B1
, R
))
5667 if (A
&& A
->hasOneUse()) {
5668 auto *A0
= dyn_cast
<BinaryOperator
>(A
->getOperand(0));
5669 auto *A1
= dyn_cast
<BinaryOperator
>(A
->getOperand(1));
5670 if (A0
&& A0
->getParent() == P
&& tryToVectorizePair(A0
, B
, R
))
5672 if (A1
&& A1
->getParent() == P
&& tryToVectorizePair(A1
, B
, R
))
5678 /// Generate a shuffle mask to be used in a reduction tree.
5680 /// \param VecLen The length of the vector to be reduced.
5681 /// \param NumEltsToRdx The number of elements that should be reduced in the
5683 /// \param IsPairwise Whether the reduction is a pairwise or splitting
5684 /// reduction. A pairwise reduction will generate a mask of
5685 /// <0,2,...> or <1,3,..> while a splitting reduction will generate
5686 /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
5687 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
5688 static Value
*createRdxShuffleMask(unsigned VecLen
, unsigned NumEltsToRdx
,
5689 bool IsPairwise
, bool IsLeft
,
5690 IRBuilder
<> &Builder
) {
5691 assert((IsPairwise
|| !IsLeft
) && "Don't support a <0,1,undef,...> mask");
5693 SmallVector
<Constant
*, 32> ShuffleMask(
5694 VecLen
, UndefValue::get(Builder
.getInt32Ty()));
5697 // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
5698 for (unsigned i
= 0; i
!= NumEltsToRdx
; ++i
)
5699 ShuffleMask
[i
] = Builder
.getInt32(2 * i
+ !IsLeft
);
5701 // Move the upper half of the vector to the lower half.
5702 for (unsigned i
= 0; i
!= NumEltsToRdx
; ++i
)
5703 ShuffleMask
[i
] = Builder
.getInt32(NumEltsToRdx
+ i
);
5705 return ConstantVector::get(ShuffleMask
);
5710 /// Model horizontal reductions.
5712 /// A horizontal reduction is a tree of reduction operations (currently add and
5713 /// fadd) that has operations that can be put into a vector as its leaf.
5714 /// For example, this tree:
5721 /// This tree has "mul" as its reduced values and "+" as its reduction
5722 /// operations. A reduction might be feeding into a store or a binary operation
5737 class HorizontalReduction
{
5738 using ReductionOpsType
= SmallVector
<Value
*, 16>;
5739 using ReductionOpsListType
= SmallVector
<ReductionOpsType
, 2>;
5740 ReductionOpsListType ReductionOps
;
5741 SmallVector
<Value
*, 32> ReducedVals
;
5742 // Use map vector to make stable output.
5743 MapVector
<Instruction
*, Value
*> ExtraArgs
;
5745 /// Kind of the reduction data.
5746 enum ReductionKind
{
5747 RK_None
, /// Not a reduction.
5748 RK_Arithmetic
, /// Binary reduction data.
5749 RK_Min
, /// Minimum reduction data.
5750 RK_UMin
, /// Unsigned minimum reduction data.
5751 RK_Max
, /// Maximum reduction data.
5752 RK_UMax
, /// Unsigned maximum reduction data.
5755 /// Contains info about operation, like its opcode, left and right operands.
5756 class OperationData
{
5757 /// Opcode of the instruction.
5758 unsigned Opcode
= 0;
5760 /// Left operand of the reduction operation.
5761 Value
*LHS
= nullptr;
5763 /// Right operand of the reduction operation.
5764 Value
*RHS
= nullptr;
5766 /// Kind of the reduction operation.
5767 ReductionKind Kind
= RK_None
;
5769 /// True if float point min/max reduction has no NaNs.
5772 /// Checks if the reduction operation can be vectorized.
5773 bool isVectorizable() const {
5774 return LHS
&& RHS
&&
5775 // We currently only support add/mul/logical && min/max reductions.
5776 ((Kind
== RK_Arithmetic
&&
5777 (Opcode
== Instruction::Add
|| Opcode
== Instruction::FAdd
||
5778 Opcode
== Instruction::Mul
|| Opcode
== Instruction::FMul
||
5779 Opcode
== Instruction::And
|| Opcode
== Instruction::Or
||
5780 Opcode
== Instruction::Xor
)) ||
5781 ((Opcode
== Instruction::ICmp
|| Opcode
== Instruction::FCmp
) &&
5782 (Kind
== RK_Min
|| Kind
== RK_Max
)) ||
5783 (Opcode
== Instruction::ICmp
&&
5784 (Kind
== RK_UMin
|| Kind
== RK_UMax
)));
5787 /// Creates reduction operation with the current opcode.
5788 Value
*createOp(IRBuilder
<> &Builder
, const Twine
&Name
) const {
5789 assert(isVectorizable() &&
5790 "Expected add|fadd or min/max reduction operation.");
5791 Value
*Cmp
= nullptr;
5794 return Builder
.CreateBinOp((Instruction::BinaryOps
)Opcode
, LHS
, RHS
,
5797 Cmp
= Opcode
== Instruction::ICmp
? Builder
.CreateICmpSLT(LHS
, RHS
)
5798 : Builder
.CreateFCmpOLT(LHS
, RHS
);
5799 return Builder
.CreateSelect(Cmp
, LHS
, RHS
, Name
);
5801 Cmp
= Opcode
== Instruction::ICmp
? Builder
.CreateICmpSGT(LHS
, RHS
)
5802 : Builder
.CreateFCmpOGT(LHS
, RHS
);
5803 return Builder
.CreateSelect(Cmp
, LHS
, RHS
, Name
);
5805 assert(Opcode
== Instruction::ICmp
&& "Expected integer types.");
5806 Cmp
= Builder
.CreateICmpULT(LHS
, RHS
);
5807 return Builder
.CreateSelect(Cmp
, LHS
, RHS
, Name
);
5809 assert(Opcode
== Instruction::ICmp
&& "Expected integer types.");
5810 Cmp
= Builder
.CreateICmpUGT(LHS
, RHS
);
5811 return Builder
.CreateSelect(Cmp
, LHS
, RHS
, Name
);
5815 llvm_unreachable("Unknown reduction operation.");
5819 explicit OperationData() = default;
5821 /// Construction for reduced values. They are identified by opcode only and
5822 /// don't have associated LHS/RHS values.
5823 explicit OperationData(Value
*V
) {
5824 if (auto *I
= dyn_cast
<Instruction
>(V
))
5825 Opcode
= I
->getOpcode();
5828 /// Constructor for reduction operations with opcode and its left and
5830 OperationData(unsigned Opcode
, Value
*LHS
, Value
*RHS
, ReductionKind Kind
,
5832 : Opcode(Opcode
), LHS(LHS
), RHS(RHS
), Kind(Kind
), NoNaN(NoNaN
) {
5833 assert(Kind
!= RK_None
&& "One of the reduction operations is expected.");
5836 explicit operator bool() const { return Opcode
; }
5838 /// Get the index of the first operand.
5839 unsigned getFirstOperandIndex() const {
5840 assert(!!*this && "The opcode is not set.");
5854 /// Total number of operands in the reduction operation.
5855 unsigned getNumberOfOperands() const {
5856 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5857 "Expected reduction operation.");
5869 llvm_unreachable("Reduction kind is not set");
5872 /// Checks if the operation has the same parent as \p P.
5873 bool hasSameParent(Instruction
*I
, Value
*P
, bool IsRedOp
) const {
5874 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5875 "Expected reduction operation.");
5877 return I
->getParent() == P
;
5880 // Arithmetic reduction operation must be used once only.
5881 return I
->getParent() == P
;
5886 // SelectInst must be used twice while the condition op must have single
5888 auto *Cmp
= cast
<Instruction
>(cast
<SelectInst
>(I
)->getCondition());
5889 return I
->getParent() == P
&& Cmp
&& Cmp
->getParent() == P
;
5894 llvm_unreachable("Reduction kind is not set");
5896 /// Expected number of uses for reduction operations/reduced values.
5897 bool hasRequiredNumberOfUses(Instruction
*I
, bool IsReductionOp
) const {
5898 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5899 "Expected reduction operation.");
5902 return I
->hasOneUse();
5907 return I
->hasNUses(2) &&
5909 cast
<SelectInst
>(I
)->getCondition()->hasOneUse());
5913 llvm_unreachable("Reduction kind is not set");
5916 /// Initializes the list of reduction operations.
5917 void initReductionOps(ReductionOpsListType
&ReductionOps
) {
5918 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5919 "Expected reduction operation.");
5922 ReductionOps
.assign(1, ReductionOpsType());
5928 ReductionOps
.assign(2, ReductionOpsType());
5931 llvm_unreachable("Reduction kind is not set");
5934 /// Add all reduction operations for the reduction instruction \p I.
5935 void addReductionOps(Instruction
*I
, ReductionOpsListType
&ReductionOps
) {
5936 assert(Kind
!= RK_None
&& !!*this && LHS
&& RHS
&&
5937 "Expected reduction operation.");
5940 ReductionOps
[0].emplace_back(I
);
5946 ReductionOps
[0].emplace_back(cast
<SelectInst
>(I
)->getCondition());
5947 ReductionOps
[1].emplace_back(I
);
5950 llvm_unreachable("Reduction kind is not set");
5954 /// Checks if instruction is associative and can be vectorized.
5955 bool isAssociative(Instruction
*I
) const {
5956 assert(Kind
!= RK_None
&& *this && LHS
&& RHS
&&
5957 "Expected reduction operation.");
5960 return I
->isAssociative();
5963 return Opcode
== Instruction::ICmp
||
5964 cast
<Instruction
>(I
->getOperand(0))->isFast();
5967 assert(Opcode
== Instruction::ICmp
&&
5968 "Only integer compare operation is expected.");
5973 llvm_unreachable("Reduction kind is not set");
5976 /// Checks if the reduction operation can be vectorized.
5977 bool isVectorizable(Instruction
*I
) const {
5978 return isVectorizable() && isAssociative(I
);
5981 /// Checks if two operation data are both a reduction op or both a reduced
5983 bool operator==(const OperationData
&OD
) {
5984 assert(((Kind
!= OD
.Kind
) || ((!LHS
== !OD
.LHS
) && (!RHS
== !OD
.RHS
))) &&
5985 "One of the comparing operations is incorrect.");
5986 return this == &OD
|| (Kind
== OD
.Kind
&& Opcode
== OD
.Opcode
);
5988 bool operator!=(const OperationData
&OD
) { return !(*this == OD
); }
5997 /// Get the opcode of the reduction operation.
5998 unsigned getOpcode() const {
5999 assert(isVectorizable() && "Expected vectorizable operation.");
6003 /// Get kind of reduction data.
6004 ReductionKind
getKind() const { return Kind
; }
6005 Value
*getLHS() const { return LHS
; }
6006 Value
*getRHS() const { return RHS
; }
6007 Type
*getConditionType() const {
6015 return CmpInst::makeCmpResultType(LHS
->getType());
6019 llvm_unreachable("Reduction kind is not set");
6022 /// Creates reduction operation with the current opcode with the IR flags
6023 /// from \p ReductionOps.
6024 Value
*createOp(IRBuilder
<> &Builder
, const Twine
&Name
,
6025 const ReductionOpsListType
&ReductionOps
) const {
6026 assert(isVectorizable() &&
6027 "Expected add|fadd or min/max reduction operation.");
6028 auto *Op
= createOp(Builder
, Name
);
6031 propagateIRFlags(Op
, ReductionOps
[0]);
6037 if (auto *SI
= dyn_cast
<SelectInst
>(Op
))
6038 propagateIRFlags(SI
->getCondition(), ReductionOps
[0]);
6039 propagateIRFlags(Op
, ReductionOps
[1]);
6044 llvm_unreachable("Unknown reduction operation.");
6046 /// Creates reduction operation with the current opcode with the IR flags
6048 Value
*createOp(IRBuilder
<> &Builder
, const Twine
&Name
,
6049 Instruction
*I
) const {
6050 assert(isVectorizable() &&
6051 "Expected add|fadd or min/max reduction operation.");
6052 auto *Op
= createOp(Builder
, Name
);
6055 propagateIRFlags(Op
, I
);
6061 if (auto *SI
= dyn_cast
<SelectInst
>(Op
)) {
6062 propagateIRFlags(SI
->getCondition(),
6063 cast
<SelectInst
>(I
)->getCondition());
6065 propagateIRFlags(Op
, I
);
6070 llvm_unreachable("Unknown reduction operation.");
6073 TargetTransformInfo::ReductionFlags
getFlags() const {
6074 TargetTransformInfo::ReductionFlags Flags
;
6075 Flags
.NoNaN
= NoNaN
;
6080 Flags
.IsSigned
= Opcode
== Instruction::ICmp
;
6081 Flags
.IsMaxOp
= false;
6084 Flags
.IsSigned
= Opcode
== Instruction::ICmp
;
6085 Flags
.IsMaxOp
= true;
6088 Flags
.IsSigned
= false;
6089 Flags
.IsMaxOp
= false;
6092 Flags
.IsSigned
= false;
6093 Flags
.IsMaxOp
= true;
6096 llvm_unreachable("Reduction kind is not set");
6102 WeakTrackingVH ReductionRoot
;
6104 /// The operation data of the reduction operation.
6105 OperationData ReductionData
;
6107 /// The operation data of the values we perform a reduction on.
6108 OperationData ReducedValueData
;
6110 /// Should we model this reduction as a pairwise reduction tree or a tree that
6111 /// splits the vector in halves and adds those halves.
6112 bool IsPairwiseReduction
= false;
6114 /// Checks if the ParentStackElem.first should be marked as a reduction
6115 /// operation with an extra argument or as extra argument itself.
6116 void markExtraArg(std::pair
<Instruction
*, unsigned> &ParentStackElem
,
6118 if (ExtraArgs
.count(ParentStackElem
.first
)) {
6119 ExtraArgs
[ParentStackElem
.first
] = nullptr;
6120 // We ran into something like:
6121 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6122 // The whole ParentStackElem.first should be considered as an extra value
6124 // Do not perform analysis of remaining operands of ParentStackElem.first
6125 // instruction, this whole instruction is an extra argument.
6126 ParentStackElem
.second
= ParentStackElem
.first
->getNumOperands();
6128 // We ran into something like:
6129 // ParentStackElem.first += ... + ExtraArg + ...
6130 ExtraArgs
[ParentStackElem
.first
] = ExtraArg
;
6134 static OperationData
getOperationData(Value
*V
) {
6136 return OperationData();
6140 if (m_BinOp(m_Value(LHS
), m_Value(RHS
)).match(V
)) {
6141 return OperationData(cast
<BinaryOperator
>(V
)->getOpcode(), LHS
, RHS
,
6144 if (auto *Select
= dyn_cast
<SelectInst
>(V
)) {
6145 // Look for a min/max pattern.
6146 if (m_UMin(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6147 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMin
);
6148 } else if (m_SMin(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6149 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Min
);
6150 } else if (m_OrdFMin(m_Value(LHS
), m_Value(RHS
)).match(Select
) ||
6151 m_UnordFMin(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6152 return OperationData(
6153 Instruction::FCmp
, LHS
, RHS
, RK_Min
,
6154 cast
<Instruction
>(Select
->getCondition())->hasNoNaNs());
6155 } else if (m_UMax(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6156 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMax
);
6157 } else if (m_SMax(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6158 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Max
);
6159 } else if (m_OrdFMax(m_Value(LHS
), m_Value(RHS
)).match(Select
) ||
6160 m_UnordFMax(m_Value(LHS
), m_Value(RHS
)).match(Select
)) {
6161 return OperationData(
6162 Instruction::FCmp
, LHS
, RHS
, RK_Max
,
6163 cast
<Instruction
>(Select
->getCondition())->hasNoNaNs());
6165 // Try harder: look for min/max pattern based on instructions producing
6166 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6167 // During the intermediate stages of SLP, it's very common to have
6168 // pattern like this (since optimizeGatherSequence is run only once
6170 // %1 = extractelement <2 x i32> %a, i32 0
6171 // %2 = extractelement <2 x i32> %a, i32 1
6172 // %cond = icmp sgt i32 %1, %2
6173 // %3 = extractelement <2 x i32> %a, i32 0
6174 // %4 = extractelement <2 x i32> %a, i32 1
6175 // %select = select i1 %cond, i32 %3, i32 %4
6176 CmpInst::Predicate Pred
;
6180 LHS
= Select
->getTrueValue();
6181 RHS
= Select
->getFalseValue();
6182 Value
*Cond
= Select
->getCondition();
6184 // TODO: Support inverse predicates.
6185 if (match(Cond
, m_Cmp(Pred
, m_Specific(LHS
), m_Instruction(L2
)))) {
6186 if (!isa
<ExtractElementInst
>(RHS
) ||
6187 !L2
->isIdenticalTo(cast
<Instruction
>(RHS
)))
6188 return OperationData(V
);
6189 } else if (match(Cond
, m_Cmp(Pred
, m_Instruction(L1
), m_Specific(RHS
)))) {
6190 if (!isa
<ExtractElementInst
>(LHS
) ||
6191 !L1
->isIdenticalTo(cast
<Instruction
>(LHS
)))
6192 return OperationData(V
);
6194 if (!isa
<ExtractElementInst
>(LHS
) || !isa
<ExtractElementInst
>(RHS
))
6195 return OperationData(V
);
6196 if (!match(Cond
, m_Cmp(Pred
, m_Instruction(L1
), m_Instruction(L2
))) ||
6197 !L1
->isIdenticalTo(cast
<Instruction
>(LHS
)) ||
6198 !L2
->isIdenticalTo(cast
<Instruction
>(RHS
)))
6199 return OperationData(V
);
6203 return OperationData(V
);
6205 case CmpInst::ICMP_ULT
:
6206 case CmpInst::ICMP_ULE
:
6207 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMin
);
6209 case CmpInst::ICMP_SLT
:
6210 case CmpInst::ICMP_SLE
:
6211 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Min
);
6213 case CmpInst::FCMP_OLT
:
6214 case CmpInst::FCMP_OLE
:
6215 case CmpInst::FCMP_ULT
:
6216 case CmpInst::FCMP_ULE
:
6217 return OperationData(Instruction::FCmp
, LHS
, RHS
, RK_Min
,
6218 cast
<Instruction
>(Cond
)->hasNoNaNs());
6220 case CmpInst::ICMP_UGT
:
6221 case CmpInst::ICMP_UGE
:
6222 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_UMax
);
6224 case CmpInst::ICMP_SGT
:
6225 case CmpInst::ICMP_SGE
:
6226 return OperationData(Instruction::ICmp
, LHS
, RHS
, RK_Max
);
6228 case CmpInst::FCMP_OGT
:
6229 case CmpInst::FCMP_OGE
:
6230 case CmpInst::FCMP_UGT
:
6231 case CmpInst::FCMP_UGE
:
6232 return OperationData(Instruction::FCmp
, LHS
, RHS
, RK_Max
,
6233 cast
<Instruction
>(Cond
)->hasNoNaNs());
6237 return OperationData(V
);
6241 HorizontalReduction() = default;
6243 /// Try to find a reduction tree.
6244 bool matchAssociativeReduction(PHINode
*Phi
, Instruction
*B
) {
6245 assert((!Phi
|| is_contained(Phi
->operands(), B
)) &&
6246 "Thi phi needs to use the binary operator");
6248 ReductionData
= getOperationData(B
);
6250 // We could have a initial reductions that is not an add.
6251 // r *= v1 + v2 + v3 + v4
6252 // In such a case start looking for a tree rooted in the first '+'.
6254 if (ReductionData
.getLHS() == Phi
) {
6256 B
= dyn_cast
<Instruction
>(ReductionData
.getRHS());
6257 ReductionData
= getOperationData(B
);
6258 } else if (ReductionData
.getRHS() == Phi
) {
6260 B
= dyn_cast
<Instruction
>(ReductionData
.getLHS());
6261 ReductionData
= getOperationData(B
);
6265 if (!ReductionData
.isVectorizable(B
))
6268 Type
*Ty
= B
->getType();
6269 if (!isValidElementType(Ty
))
6271 if (!Ty
->isIntOrIntVectorTy() && !Ty
->isFPOrFPVectorTy())
6274 ReducedValueData
.clear();
6277 // Post order traverse the reduction tree starting at B. We only handle true
6278 // trees containing only binary operators.
6279 SmallVector
<std::pair
<Instruction
*, unsigned>, 32> Stack
;
6280 Stack
.push_back(std::make_pair(B
, ReductionData
.getFirstOperandIndex()));
6281 ReductionData
.initReductionOps(ReductionOps
);
6282 while (!Stack
.empty()) {
6283 Instruction
*TreeN
= Stack
.back().first
;
6284 unsigned EdgeToVist
= Stack
.back().second
++;
6285 OperationData OpData
= getOperationData(TreeN
);
6286 bool IsReducedValue
= OpData
!= ReductionData
;
6289 if (IsReducedValue
|| EdgeToVist
== OpData
.getNumberOfOperands()) {
6291 ReducedVals
.push_back(TreeN
);
6293 auto I
= ExtraArgs
.find(TreeN
);
6294 if (I
!= ExtraArgs
.end() && !I
->second
) {
6295 // Check if TreeN is an extra argument of its parent operation.
6296 if (Stack
.size() <= 1) {
6297 // TreeN can't be an extra argument as it is a root reduction
6301 // Yes, TreeN is an extra argument, do not add it to a list of
6302 // reduction operations.
6303 // Stack[Stack.size() - 2] always points to the parent operation.
6304 markExtraArg(Stack
[Stack
.size() - 2], TreeN
);
6305 ExtraArgs
.erase(TreeN
);
6307 ReductionData
.addReductionOps(TreeN
, ReductionOps
);
6314 // Visit left or right.
6315 Value
*NextV
= TreeN
->getOperand(EdgeToVist
);
6317 auto *I
= dyn_cast
<Instruction
>(NextV
);
6318 OpData
= getOperationData(I
);
6319 // Continue analysis if the next operand is a reduction operation or
6320 // (possibly) a reduced value. If the reduced value opcode is not set,
6321 // the first met operation != reduction operation is considered as the
6322 // reduced value class.
6323 if (I
&& (!ReducedValueData
|| OpData
== ReducedValueData
||
6324 OpData
== ReductionData
)) {
6325 const bool IsReductionOperation
= OpData
== ReductionData
;
6326 // Only handle trees in the current basic block.
6327 if (!ReductionData
.hasSameParent(I
, B
->getParent(),
6328 IsReductionOperation
)) {
6329 // I is an extra argument for TreeN (its parent operation).
6330 markExtraArg(Stack
.back(), I
);
6334 // Each tree node needs to have minimal number of users except for the
6335 // ultimate reduction.
6336 if (!ReductionData
.hasRequiredNumberOfUses(I
,
6337 OpData
== ReductionData
) &&
6339 // I is an extra argument for TreeN (its parent operation).
6340 markExtraArg(Stack
.back(), I
);
6344 if (IsReductionOperation
) {
6345 // We need to be able to reassociate the reduction operations.
6346 if (!OpData
.isAssociative(I
)) {
6347 // I is an extra argument for TreeN (its parent operation).
6348 markExtraArg(Stack
.back(), I
);
6351 } else if (ReducedValueData
&&
6352 ReducedValueData
!= OpData
) {
6353 // Make sure that the opcodes of the operations that we are going to
6355 // I is an extra argument for TreeN (its parent operation).
6356 markExtraArg(Stack
.back(), I
);
6358 } else if (!ReducedValueData
)
6359 ReducedValueData
= OpData
;
6361 Stack
.push_back(std::make_pair(I
, OpData
.getFirstOperandIndex()));
6365 // NextV is an extra argument for TreeN (its parent operation).
6366 markExtraArg(Stack
.back(), NextV
);
6371 /// Attempt to vectorize the tree found by
6372 /// matchAssociativeReduction.
6373 bool tryToReduce(BoUpSLP
&V
, TargetTransformInfo
*TTI
) {
6374 if (ReducedVals
.empty())
6377 // If there is a sufficient number of reduction values, reduce
6378 // to a nearby power-of-2. Can safely generate oversized
6379 // vectors and rely on the backend to split them to legal sizes.
6380 unsigned NumReducedVals
= ReducedVals
.size();
6381 if (NumReducedVals
< 4)
6384 unsigned ReduxWidth
= PowerOf2Floor(NumReducedVals
);
6386 Value
*VectorizedTree
= nullptr;
6388 // FIXME: Fast-math-flags should be set based on the instructions in the
6389 // reduction (not all of 'fast' are required).
6390 IRBuilder
<> Builder(cast
<Instruction
>(ReductionRoot
));
6391 FastMathFlags Unsafe
;
6393 Builder
.setFastMathFlags(Unsafe
);
6396 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues
;
6397 // The same extra argument may be used several time, so log each attempt
6399 for (auto &Pair
: ExtraArgs
) {
6400 assert(Pair
.first
&& "DebugLoc must be set.");
6401 ExternallyUsedValues
[Pair
.second
].push_back(Pair
.first
);
6403 // The reduction root is used as the insertion point for new instructions,
6404 // so set it as externally used to prevent it from being deleted.
6405 ExternallyUsedValues
[ReductionRoot
];
6406 SmallVector
<Value
*, 16> IgnoreList
;
6407 for (auto &V
: ReductionOps
)
6408 IgnoreList
.append(V
.begin(), V
.end());
6409 while (i
< NumReducedVals
- ReduxWidth
+ 1 && ReduxWidth
> 2) {
6410 auto VL
= makeArrayRef(&ReducedVals
[i
], ReduxWidth
);
6411 V
.buildTree(VL
, ExternallyUsedValues
, IgnoreList
);
6412 Optional
<ArrayRef
<unsigned>> Order
= V
.bestOrder();
6413 // TODO: Handle orders of size less than number of elements in the vector.
6414 if (Order
&& Order
->size() == VL
.size()) {
6415 // TODO: reorder tree nodes without tree rebuilding.
6416 SmallVector
<Value
*, 4> ReorderedOps(VL
.size());
6417 llvm::transform(*Order
, ReorderedOps
.begin(),
6418 [VL
](const unsigned Idx
) { return VL
[Idx
]; });
6419 V
.buildTree(ReorderedOps
, ExternallyUsedValues
, IgnoreList
);
6421 if (V
.isTreeTinyAndNotFullyVectorizable())
6423 if (V
.isLoadCombineReductionCandidate(ReductionData
.getOpcode()))
6426 V
.computeMinimumValueSizes();
6429 int TreeCost
= V
.getTreeCost();
6430 int ReductionCost
= getReductionCost(TTI
, ReducedVals
[i
], ReduxWidth
);
6431 int Cost
= TreeCost
+ ReductionCost
;
6432 if (Cost
>= -SLPCostThreshold
) {
6433 V
.getORE()->emit([&]() {
6434 return OptimizationRemarkMissed(
6435 SV_NAME
, "HorSLPNotBeneficial", cast
<Instruction
>(VL
[0]))
6436 << "Vectorizing horizontal reduction is possible"
6437 << "but not beneficial with cost "
6438 << ore::NV("Cost", Cost
) << " and threshold "
6439 << ore::NV("Threshold", -SLPCostThreshold
);
6444 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
6445 << Cost
<< ". (HorRdx)\n");
6446 V
.getORE()->emit([&]() {
6447 return OptimizationRemark(
6448 SV_NAME
, "VectorizedHorizontalReduction", cast
<Instruction
>(VL
[0]))
6449 << "Vectorized horizontal reduction with cost "
6450 << ore::NV("Cost", Cost
) << " and with tree size "
6451 << ore::NV("TreeSize", V
.getTreeSize());
6454 // Vectorize a tree.
6455 DebugLoc Loc
= cast
<Instruction
>(ReducedVals
[i
])->getDebugLoc();
6456 Value
*VectorizedRoot
= V
.vectorizeTree(ExternallyUsedValues
);
6458 // Emit a reduction.
6459 Builder
.SetInsertPoint(cast
<Instruction
>(ReductionRoot
));
6460 Value
*ReducedSubTree
=
6461 emitReduction(VectorizedRoot
, Builder
, ReduxWidth
, TTI
);
6462 if (VectorizedTree
) {
6463 Builder
.SetCurrentDebugLocation(Loc
);
6464 OperationData
VectReductionData(ReductionData
.getOpcode(),
6465 VectorizedTree
, ReducedSubTree
,
6466 ReductionData
.getKind());
6468 VectReductionData
.createOp(Builder
, "op.rdx", ReductionOps
);
6470 VectorizedTree
= ReducedSubTree
;
6472 ReduxWidth
= PowerOf2Floor(NumReducedVals
- i
);
6475 if (VectorizedTree
) {
6476 // Finish the reduction.
6477 for (; i
< NumReducedVals
; ++i
) {
6478 auto *I
= cast
<Instruction
>(ReducedVals
[i
]);
6479 Builder
.SetCurrentDebugLocation(I
->getDebugLoc());
6480 OperationData
VectReductionData(ReductionData
.getOpcode(),
6482 ReductionData
.getKind());
6483 VectorizedTree
= VectReductionData
.createOp(Builder
, "", ReductionOps
);
6485 for (auto &Pair
: ExternallyUsedValues
) {
6486 // Add each externally used value to the final reduction.
6487 for (auto *I
: Pair
.second
) {
6488 Builder
.SetCurrentDebugLocation(I
->getDebugLoc());
6489 OperationData
VectReductionData(ReductionData
.getOpcode(),
6490 VectorizedTree
, Pair
.first
,
6491 ReductionData
.getKind());
6492 VectorizedTree
= VectReductionData
.createOp(Builder
, "op.extra", I
);
6496 ReductionRoot
->replaceAllUsesWith(VectorizedTree
);
6497 // Mark all scalar reduction ops for deletion, they are replaced by the
6498 // vector reductions.
6499 V
.eraseInstructions(IgnoreList
);
6501 return VectorizedTree
!= nullptr;
6504 unsigned numReductionValues() const {
6505 return ReducedVals
.size();
6509 /// Calculate the cost of a reduction.
6510 int getReductionCost(TargetTransformInfo
*TTI
, Value
*FirstReducedVal
,
6511 unsigned ReduxWidth
) {
6512 Type
*ScalarTy
= FirstReducedVal
->getType();
6513 Type
*VecTy
= VectorType::get(ScalarTy
, ReduxWidth
);
6515 int PairwiseRdxCost
;
6516 int SplittingRdxCost
;
6517 switch (ReductionData
.getKind()) {
6520 TTI
->getArithmeticReductionCost(ReductionData
.getOpcode(), VecTy
,
6521 /*IsPairwiseForm=*/true);
6523 TTI
->getArithmeticReductionCost(ReductionData
.getOpcode(), VecTy
,
6524 /*IsPairwiseForm=*/false);
6530 Type
*VecCondTy
= CmpInst::makeCmpResultType(VecTy
);
6531 bool IsUnsigned
= ReductionData
.getKind() == RK_UMin
||
6532 ReductionData
.getKind() == RK_UMax
;
6534 TTI
->getMinMaxReductionCost(VecTy
, VecCondTy
,
6535 /*IsPairwiseForm=*/true, IsUnsigned
);
6537 TTI
->getMinMaxReductionCost(VecTy
, VecCondTy
,
6538 /*IsPairwiseForm=*/false, IsUnsigned
);
6542 llvm_unreachable("Expected arithmetic or min/max reduction operation");
6545 IsPairwiseReduction
= PairwiseRdxCost
< SplittingRdxCost
;
6546 int VecReduxCost
= IsPairwiseReduction
? PairwiseRdxCost
: SplittingRdxCost
;
6548 int ScalarReduxCost
= 0;
6549 switch (ReductionData
.getKind()) {
6552 TTI
->getArithmeticInstrCost(ReductionData
.getOpcode(), ScalarTy
);
6559 TTI
->getCmpSelInstrCost(ReductionData
.getOpcode(), ScalarTy
) +
6560 TTI
->getCmpSelInstrCost(Instruction::Select
, ScalarTy
,
6561 CmpInst::makeCmpResultType(ScalarTy
));
6564 llvm_unreachable("Expected arithmetic or min/max reduction operation");
6566 ScalarReduxCost
*= (ReduxWidth
- 1);
6568 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost
- ScalarReduxCost
6569 << " for reduction that starts with " << *FirstReducedVal
6571 << (IsPairwiseReduction
? "pairwise" : "splitting")
6572 << " reduction)\n");
6574 return VecReduxCost
- ScalarReduxCost
;
6577 /// Emit a horizontal reduction of the vectorized value.
6578 Value
*emitReduction(Value
*VectorizedValue
, IRBuilder
<> &Builder
,
6579 unsigned ReduxWidth
, const TargetTransformInfo
*TTI
) {
6580 assert(VectorizedValue
&& "Need to have a vectorized tree node");
6581 assert(isPowerOf2_32(ReduxWidth
) &&
6582 "We only handle power-of-two reductions for now");
6584 if (!IsPairwiseReduction
) {
6585 // FIXME: The builder should use an FMF guard. It should not be hard-coded
6587 assert(Builder
.getFastMathFlags().isFast() && "Expected 'fast' FMF");
6588 return createSimpleTargetReduction(
6589 Builder
, TTI
, ReductionData
.getOpcode(), VectorizedValue
,
6590 ReductionData
.getFlags(), ReductionOps
.back());
6593 Value
*TmpVec
= VectorizedValue
;
6594 for (unsigned i
= ReduxWidth
/ 2; i
!= 0; i
>>= 1) {
6596 createRdxShuffleMask(ReduxWidth
, i
, true, true, Builder
);
6598 createRdxShuffleMask(ReduxWidth
, i
, true, false, Builder
);
6600 Value
*LeftShuf
= Builder
.CreateShuffleVector(
6601 TmpVec
, UndefValue::get(TmpVec
->getType()), LeftMask
, "rdx.shuf.l");
6602 Value
*RightShuf
= Builder
.CreateShuffleVector(
6603 TmpVec
, UndefValue::get(TmpVec
->getType()), (RightMask
),
6605 OperationData
VectReductionData(ReductionData
.getOpcode(), LeftShuf
,
6606 RightShuf
, ReductionData
.getKind());
6607 TmpVec
= VectReductionData
.createOp(Builder
, "op.rdx", ReductionOps
);
6610 // The result is in the first element of the vector.
6611 return Builder
.CreateExtractElement(TmpVec
, Builder
.getInt32(0));
6615 } // end anonymous namespace
6617 /// Recognize construction of vectors like
6618 /// %ra = insertelement <4 x float> undef, float %s0, i32 0
6619 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
6620 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
6621 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
6622 /// starting from the last insertelement instruction.
6624 /// Returns true if it matches
6625 static bool findBuildVector(InsertElementInst
*LastInsertElem
,
6626 TargetTransformInfo
*TTI
,
6627 SmallVectorImpl
<Value
*> &BuildVectorOpds
,
6632 if (auto *CI
= dyn_cast
<ConstantInt
>(LastInsertElem
->getOperand(2))) {
6633 UserCost
+= TTI
->getVectorInstrCost(Instruction::InsertElement
,
6634 LastInsertElem
->getType(),
6635 CI
->getZExtValue());
6637 BuildVectorOpds
.push_back(LastInsertElem
->getOperand(1));
6638 V
= LastInsertElem
->getOperand(0);
6639 if (isa
<UndefValue
>(V
))
6641 LastInsertElem
= dyn_cast
<InsertElementInst
>(V
);
6642 if (!LastInsertElem
|| !LastInsertElem
->hasOneUse())
6645 std::reverse(BuildVectorOpds
.begin(), BuildVectorOpds
.end());
6649 /// Like findBuildVector, but looks for construction of aggregate.
6651 /// \return true if it matches.
6652 static bool findBuildAggregate(InsertValueInst
*IV
,
6653 SmallVectorImpl
<Value
*> &BuildVectorOpds
) {
6655 BuildVectorOpds
.push_back(IV
->getInsertedValueOperand());
6656 Value
*V
= IV
->getAggregateOperand();
6657 if (isa
<UndefValue
>(V
))
6659 IV
= dyn_cast
<InsertValueInst
>(V
);
6660 if (!IV
|| !IV
->hasOneUse())
6663 std::reverse(BuildVectorOpds
.begin(), BuildVectorOpds
.end());
6667 static bool PhiTypeSorterFunc(Value
*V
, Value
*V2
) {
6668 return V
->getType() < V2
->getType();
6671 /// Try and get a reduction value from a phi node.
6673 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
6674 /// if they come from either \p ParentBB or a containing loop latch.
6676 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
6677 /// if not possible.
6678 static Value
*getReductionValue(const DominatorTree
*DT
, PHINode
*P
,
6679 BasicBlock
*ParentBB
, LoopInfo
*LI
) {
6680 // There are situations where the reduction value is not dominated by the
6681 // reduction phi. Vectorizing such cases has been reported to cause
6682 // miscompiles. See PR25787.
6683 auto DominatedReduxValue
= [&](Value
*R
) {
6684 return isa
<Instruction
>(R
) &&
6685 DT
->dominates(P
->getParent(), cast
<Instruction
>(R
)->getParent());
6688 Value
*Rdx
= nullptr;
6690 // Return the incoming value if it comes from the same BB as the phi node.
6691 if (P
->getIncomingBlock(0) == ParentBB
) {
6692 Rdx
= P
->getIncomingValue(0);
6693 } else if (P
->getIncomingBlock(1) == ParentBB
) {
6694 Rdx
= P
->getIncomingValue(1);
6697 if (Rdx
&& DominatedReduxValue(Rdx
))
6700 // Otherwise, check whether we have a loop latch to look at.
6701 Loop
*BBL
= LI
->getLoopFor(ParentBB
);
6704 BasicBlock
*BBLatch
= BBL
->getLoopLatch();
6708 // There is a loop latch, return the incoming value if it comes from
6709 // that. This reduction pattern occasionally turns up.
6710 if (P
->getIncomingBlock(0) == BBLatch
) {
6711 Rdx
= P
->getIncomingValue(0);
6712 } else if (P
->getIncomingBlock(1) == BBLatch
) {
6713 Rdx
= P
->getIncomingValue(1);
6716 if (Rdx
&& DominatedReduxValue(Rdx
))
6722 /// Attempt to reduce a horizontal reduction.
6723 /// If it is legal to match a horizontal reduction feeding the phi node \a P
6724 /// with reduction operators \a Root (or one of its operands) in a basic block
6725 /// \a BB, then check if it can be done. If horizontal reduction is not found
6726 /// and root instruction is a binary operation, vectorization of the operands is
6728 /// \returns true if a horizontal reduction was matched and reduced or operands
6729 /// of one of the binary instruction were vectorized.
6730 /// \returns false if a horizontal reduction was not matched (or not possible)
6731 /// or no vectorization of any binary operation feeding \a Root instruction was
6733 static bool tryToVectorizeHorReductionOrInstOperands(
6734 PHINode
*P
, Instruction
*Root
, BasicBlock
*BB
, BoUpSLP
&R
,
6735 TargetTransformInfo
*TTI
,
6736 const function_ref
<bool(Instruction
*, BoUpSLP
&)> Vectorize
) {
6737 if (!ShouldVectorizeHor
)
6743 if (Root
->getParent() != BB
|| isa
<PHINode
>(Root
))
6745 // Start analysis starting from Root instruction. If horizontal reduction is
6746 // found, try to vectorize it. If it is not a horizontal reduction or
6747 // vectorization is not possible or not effective, and currently analyzed
6748 // instruction is a binary operation, try to vectorize the operands, using
6749 // pre-order DFS traversal order. If the operands were not vectorized, repeat
6750 // the same procedure considering each operand as a possible root of the
6751 // horizontal reduction.
6752 // Interrupt the process if the Root instruction itself was vectorized or all
6753 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
6754 SmallVector
<std::pair
<Instruction
*, unsigned>, 8> Stack(1, {Root
, 0});
6755 SmallPtrSet
<Value
*, 8> VisitedInstrs
;
6757 while (!Stack
.empty()) {
6760 std::tie(Inst
, Level
) = Stack
.pop_back_val();
6761 auto *BI
= dyn_cast
<BinaryOperator
>(Inst
);
6762 auto *SI
= dyn_cast
<SelectInst
>(Inst
);
6764 HorizontalReduction HorRdx
;
6765 if (HorRdx
.matchAssociativeReduction(P
, Inst
)) {
6766 if (HorRdx
.tryToReduce(R
, TTI
)) {
6768 // Set P to nullptr to avoid re-analysis of phi node in
6769 // matchAssociativeReduction function unless this is the root node.
6775 Inst
= dyn_cast
<Instruction
>(BI
->getOperand(0));
6777 Inst
= dyn_cast
<Instruction
>(BI
->getOperand(1));
6779 // Set P to nullptr to avoid re-analysis of phi node in
6780 // matchAssociativeReduction function unless this is the root node.
6786 // Set P to nullptr to avoid re-analysis of phi node in
6787 // matchAssociativeReduction function unless this is the root node.
6789 if (Vectorize(Inst
, R
)) {
6794 // Try to vectorize operands.
6795 // Continue analysis for the instruction from the same basic block only to
6796 // save compile time.
6797 if (++Level
< RecursionMaxDepth
)
6798 for (auto *Op
: Inst
->operand_values())
6799 if (VisitedInstrs
.insert(Op
).second
)
6800 if (auto *I
= dyn_cast
<Instruction
>(Op
))
6801 if (!isa
<PHINode
>(I
) && !R
.isDeleted(I
) && I
->getParent() == BB
)
6802 Stack
.emplace_back(I
, Level
);
6807 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode
*P
, Value
*V
,
6808 BasicBlock
*BB
, BoUpSLP
&R
,
6809 TargetTransformInfo
*TTI
) {
6812 auto *I
= dyn_cast
<Instruction
>(V
);
6816 if (!isa
<BinaryOperator
>(I
))
6818 // Try to match and vectorize a horizontal reduction.
6819 auto &&ExtraVectorization
= [this](Instruction
*I
, BoUpSLP
&R
) -> bool {
6820 return tryToVectorize(I
, R
);
6822 return tryToVectorizeHorReductionOrInstOperands(P
, I
, BB
, R
, TTI
,
6823 ExtraVectorization
);
6826 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst
*IVI
,
6827 BasicBlock
*BB
, BoUpSLP
&R
) {
6828 const DataLayout
&DL
= BB
->getModule()->getDataLayout();
6829 if (!R
.canMapToVector(IVI
->getType(), DL
))
6832 SmallVector
<Value
*, 16> BuildVectorOpds
;
6833 if (!findBuildAggregate(IVI
, BuildVectorOpds
))
6836 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI
<< "\n");
6837 // Aggregate value is unlikely to be processed in vector register, we need to
6838 // extract scalars into scalar registers, so NeedExtraction is set true.
6839 return tryToVectorizeList(BuildVectorOpds
, R
);
6842 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst
*IEI
,
6843 BasicBlock
*BB
, BoUpSLP
&R
) {
6845 SmallVector
<Value
*, 16> BuildVectorOpds
;
6846 if (!findBuildVector(IEI
, TTI
, BuildVectorOpds
, UserCost
) ||
6847 (llvm::all_of(BuildVectorOpds
,
6848 [](Value
*V
) { return isa
<ExtractElementInst
>(V
); }) &&
6849 isShuffle(BuildVectorOpds
)))
6852 // Vectorize starting with the build vector operands ignoring the BuildVector
6853 // instructions for the purpose of scheduling and user extraction.
6854 return tryToVectorizeList(BuildVectorOpds
, R
, UserCost
);
6857 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst
*CI
, BasicBlock
*BB
,
6859 if (tryToVectorizePair(CI
->getOperand(0), CI
->getOperand(1), R
))
6862 bool OpsChanged
= false;
6863 for (int Idx
= 0; Idx
< 2; ++Idx
) {
6865 vectorizeRootInstruction(nullptr, CI
->getOperand(Idx
), BB
, R
, TTI
);
6870 bool SLPVectorizerPass::vectorizeSimpleInstructions(
6871 SmallVectorImpl
<Instruction
*> &Instructions
, BasicBlock
*BB
, BoUpSLP
&R
) {
6872 bool OpsChanged
= false;
6873 for (auto *I
: reverse(Instructions
)) {
6876 if (auto *LastInsertValue
= dyn_cast
<InsertValueInst
>(I
))
6877 OpsChanged
|= vectorizeInsertValueInst(LastInsertValue
, BB
, R
);
6878 else if (auto *LastInsertElem
= dyn_cast
<InsertElementInst
>(I
))
6879 OpsChanged
|= vectorizeInsertElementInst(LastInsertElem
, BB
, R
);
6880 else if (auto *CI
= dyn_cast
<CmpInst
>(I
))
6881 OpsChanged
|= vectorizeCmpInst(CI
, BB
, R
);
6883 Instructions
.clear();
6887 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock
*BB
, BoUpSLP
&R
) {
6888 bool Changed
= false;
6889 SmallVector
<Value
*, 4> Incoming
;
6890 SmallPtrSet
<Value
*, 16> VisitedInstrs
;
6892 bool HaveVectorizedPhiNodes
= true;
6893 while (HaveVectorizedPhiNodes
) {
6894 HaveVectorizedPhiNodes
= false;
6896 // Collect the incoming values from the PHIs.
6898 for (Instruction
&I
: *BB
) {
6899 PHINode
*P
= dyn_cast
<PHINode
>(&I
);
6903 if (!VisitedInstrs
.count(P
) && !R
.isDeleted(P
))
6904 Incoming
.push_back(P
);
6908 llvm::stable_sort(Incoming
, PhiTypeSorterFunc
);
6910 // Try to vectorize elements base on their type.
6911 for (SmallVector
<Value
*, 4>::iterator IncIt
= Incoming
.begin(),
6915 // Look for the next elements with the same type.
6916 SmallVector
<Value
*, 4>::iterator SameTypeIt
= IncIt
;
6917 while (SameTypeIt
!= E
&&
6918 (*SameTypeIt
)->getType() == (*IncIt
)->getType()) {
6919 VisitedInstrs
.insert(*SameTypeIt
);
6923 // Try to vectorize them.
6924 unsigned NumElts
= (SameTypeIt
- IncIt
);
6925 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
6926 << NumElts
<< ")\n");
6927 // The order in which the phi nodes appear in the program does not matter.
6928 // So allow tryToVectorizeList to reorder them if it is beneficial. This
6929 // is done when there are exactly two elements since tryToVectorizeList
6930 // asserts that there are only two values when AllowReorder is true.
6931 bool AllowReorder
= NumElts
== 2;
6932 if (NumElts
> 1 && tryToVectorizeList(makeArrayRef(IncIt
, NumElts
), R
,
6933 /*UserCost=*/0, AllowReorder
)) {
6934 // Success start over because instructions might have been changed.
6935 HaveVectorizedPhiNodes
= true;
6940 // Start over at the next instruction of a different type (or the end).
6945 VisitedInstrs
.clear();
6947 SmallVector
<Instruction
*, 8> PostProcessInstructions
;
6948 SmallDenseSet
<Instruction
*, 4> KeyNodes
;
6949 for (BasicBlock::iterator it
= BB
->begin(), e
= BB
->end(); it
!= e
; ++it
) {
6950 // Skip instructions marked for the deletion.
6951 if (R
.isDeleted(&*it
))
6953 // We may go through BB multiple times so skip the one we have checked.
6954 if (!VisitedInstrs
.insert(&*it
).second
) {
6955 if (it
->use_empty() && KeyNodes
.count(&*it
) > 0 &&
6956 vectorizeSimpleInstructions(PostProcessInstructions
, BB
, R
)) {
6957 // We would like to start over since some instructions are deleted
6958 // and the iterator may become invalid value.
6966 if (isa
<DbgInfoIntrinsic
>(it
))
6969 // Try to vectorize reductions that use PHINodes.
6970 if (PHINode
*P
= dyn_cast
<PHINode
>(it
)) {
6971 // Check that the PHI is a reduction PHI.
6972 if (P
->getNumIncomingValues() != 2)
6975 // Try to match and vectorize a horizontal reduction.
6976 if (vectorizeRootInstruction(P
, getReductionValue(DT
, P
, BB
, LI
), BB
, R
,
6986 // Ran into an instruction without users, like terminator, or function call
6987 // with ignored return value, store. Ignore unused instructions (basing on
6988 // instruction type, except for CallInst and InvokeInst).
6989 if (it
->use_empty() && (it
->getType()->isVoidTy() || isa
<CallInst
>(it
) ||
6990 isa
<InvokeInst
>(it
))) {
6991 KeyNodes
.insert(&*it
);
6992 bool OpsChanged
= false;
6993 if (ShouldStartVectorizeHorAtStore
|| !isa
<StoreInst
>(it
)) {
6994 for (auto *V
: it
->operand_values()) {
6995 // Try to match and vectorize a horizontal reduction.
6996 OpsChanged
|= vectorizeRootInstruction(nullptr, V
, BB
, R
, TTI
);
6999 // Start vectorization of post-process list of instructions from the
7000 // top-tree instructions to try to vectorize as many instructions as
7002 OpsChanged
|= vectorizeSimpleInstructions(PostProcessInstructions
, BB
, R
);
7004 // We would like to start over since some instructions are deleted
7005 // and the iterator may become invalid value.
7013 if (isa
<InsertElementInst
>(it
) || isa
<CmpInst
>(it
) ||
7014 isa
<InsertValueInst
>(it
))
7015 PostProcessInstructions
.push_back(&*it
);
7021 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock
*BB
, BoUpSLP
&R
) {
7022 auto Changed
= false;
7023 for (auto &Entry
: GEPs
) {
7024 // If the getelementptr list has fewer than two elements, there's nothing
7026 if (Entry
.second
.size() < 2)
7029 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
7030 << Entry
.second
.size() << ".\n");
7032 // Process the GEP list in chunks suitable for the target's supported
7033 // vector size. If a vector register can't hold 1 element, we are done.
7034 unsigned MaxVecRegSize
= R
.getMaxVecRegSize();
7035 unsigned EltSize
= R
.getVectorElementSize(Entry
.second
[0]);
7036 if (MaxVecRegSize
< EltSize
)
7039 unsigned MaxElts
= MaxVecRegSize
/ EltSize
;
7040 for (unsigned BI
= 0, BE
= Entry
.second
.size(); BI
< BE
; BI
+= MaxElts
) {
7041 auto Len
= std::min
<unsigned>(BE
- BI
, MaxElts
);
7042 auto GEPList
= makeArrayRef(&Entry
.second
[BI
], Len
);
7044 // Initialize a set a candidate getelementptrs. Note that we use a
7045 // SetVector here to preserve program order. If the index computations
7046 // are vectorizable and begin with loads, we want to minimize the chance
7047 // of having to reorder them later.
7048 SetVector
<Value
*> Candidates(GEPList
.begin(), GEPList
.end());
7050 // Some of the candidates may have already been vectorized after we
7051 // initially collected them. If so, they are marked as deleted, so remove
7052 // them from the set of candidates.
7053 Candidates
.remove_if(
7054 [&R
](Value
*I
) { return R
.isDeleted(cast
<Instruction
>(I
)); });
7056 // Remove from the set of candidates all pairs of getelementptrs with
7057 // constant differences. Such getelementptrs are likely not good
7058 // candidates for vectorization in a bottom-up phase since one can be
7059 // computed from the other. We also ensure all candidate getelementptr
7060 // indices are unique.
7061 for (int I
= 0, E
= GEPList
.size(); I
< E
&& Candidates
.size() > 1; ++I
) {
7062 auto *GEPI
= GEPList
[I
];
7063 if (!Candidates
.count(GEPI
))
7065 auto *SCEVI
= SE
->getSCEV(GEPList
[I
]);
7066 for (int J
= I
+ 1; J
< E
&& Candidates
.size() > 1; ++J
) {
7067 auto *GEPJ
= GEPList
[J
];
7068 auto *SCEVJ
= SE
->getSCEV(GEPList
[J
]);
7069 if (isa
<SCEVConstant
>(SE
->getMinusSCEV(SCEVI
, SCEVJ
))) {
7070 Candidates
.remove(GEPI
);
7071 Candidates
.remove(GEPJ
);
7072 } else if (GEPI
->idx_begin()->get() == GEPJ
->idx_begin()->get()) {
7073 Candidates
.remove(GEPJ
);
7078 // We break out of the above computation as soon as we know there are
7079 // fewer than two candidates remaining.
7080 if (Candidates
.size() < 2)
7083 // Add the single, non-constant index of each candidate to the bundle. We
7084 // ensured the indices met these constraints when we originally collected
7085 // the getelementptrs.
7086 SmallVector
<Value
*, 16> Bundle(Candidates
.size());
7087 auto BundleIndex
= 0u;
7088 for (auto *V
: Candidates
) {
7089 auto *GEP
= cast
<GetElementPtrInst
>(V
);
7090 auto *GEPIdx
= GEP
->idx_begin()->get();
7091 assert(GEP
->getNumIndices() == 1 || !isa
<Constant
>(GEPIdx
));
7092 Bundle
[BundleIndex
++] = GEPIdx
;
7095 // Try and vectorize the indices. We are currently only interested in
7096 // gather-like cases of the form:
7098 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7100 // where the loads of "a", the loads of "b", and the subtractions can be
7101 // performed in parallel. It's likely that detecting this pattern in a
7102 // bottom-up phase will be simpler and less costly than building a
7103 // full-blown top-down phase beginning at the consecutive loads.
7104 Changed
|= tryToVectorizeList(Bundle
, R
);
7110 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP
&R
) {
7111 bool Changed
= false;
7112 // Attempt to sort and vectorize each of the store-groups.
7113 for (StoreListMap::iterator it
= Stores
.begin(), e
= Stores
.end(); it
!= e
;
7115 if (it
->second
.size() < 2)
7118 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7119 << it
->second
.size() << ".\n");
7121 // Process the stores in chunks of 16.
7122 // TODO: The limit of 16 inhibits greater vectorization factors.
7123 // For example, AVX2 supports v32i8. Increasing this limit, however,
7124 // may cause a significant compile-time increase.
7125 for (unsigned CI
= 0, CE
= it
->second
.size(); CI
< CE
; CI
+= 16) {
7126 unsigned Len
= std::min
<unsigned>(CE
- CI
, 16);
7127 Changed
|= vectorizeStores(makeArrayRef(&it
->second
[CI
], Len
), R
);
7133 char SLPVectorizer::ID
= 0;
7135 static const char lv_name
[] = "SLP Vectorizer";
7137 INITIALIZE_PASS_BEGIN(SLPVectorizer
, SV_NAME
, lv_name
, false, false)
7138 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
7139 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
7140 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
7141 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass
)
7142 INITIALIZE_PASS_DEPENDENCY(LoopSimplify
)
7143 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass
)
7144 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass
)
7145 INITIALIZE_PASS_END(SLPVectorizer
, SV_NAME
, lv_name
, false, false)
7147 Pass
*llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }