1284c1978SDimitry Andric //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2284c1978SDimitry Andric //
3284c1978SDimitry Andric // The LLVM Compiler Infrastructure
4284c1978SDimitry Andric //
5284c1978SDimitry Andric // This file is distributed under the University of Illinois Open Source
6284c1978SDimitry Andric // License. See LICENSE.TXT for details.
7284c1978SDimitry Andric //
8284c1978SDimitry Andric //===----------------------------------------------------------------------===//
92cab237bSDimitry Andric //
10284c1978SDimitry Andric // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
11284c1978SDimitry Andric // stores that can be put together into vector-stores. Next, it attempts to
12284c1978SDimitry Andric // construct vectorizable tree using the use-def chains. If a profitable tree
13284c1978SDimitry Andric // was found, the SLP vectorizer performs vectorization on the tree.
14284c1978SDimitry Andric //
15284c1978SDimitry Andric // The pass is inspired by the work described in the paper:
16284c1978SDimitry Andric // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
17284c1978SDimitry Andric //
18284c1978SDimitry Andric //===----------------------------------------------------------------------===//
192cab237bSDimitry Andric
203ca95b02SDimitry Andric #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
212cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
222cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
232cab237bSDimitry Andric #include "llvm/ADT/DenseSet.h"
242cab237bSDimitry Andric #include "llvm/ADT/MapVector.h"
252cab237bSDimitry Andric #include "llvm/ADT/None.h"
26ff0cc061SDimitry Andric #include "llvm/ADT/Optional.h"
27f785676fSDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
282cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
29f785676fSDimitry Andric #include "llvm/ADT/SetVector.h"
302cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
312cab237bSDimitry Andric #include "llvm/ADT/SmallSet.h"
322cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
3339d628a0SDimitry Andric #include "llvm/ADT/Statistic.h"
342cab237bSDimitry Andric #include "llvm/ADT/iterator.h"
352cab237bSDimitry Andric #include "llvm/ADT/iterator_range.h"
362cab237bSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
3739d628a0SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
382cab237bSDimitry Andric #include "llvm/Analysis/DemandedBits.h"
393ca95b02SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
403ca95b02SDimitry Andric #include "llvm/Analysis/LoopAccessAnalysis.h"
412cab237bSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
422cab237bSDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
432cab237bSDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
442cab237bSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
45f785676fSDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
462cab237bSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
472cab237bSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
48f785676fSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
493ca95b02SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
502cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
512cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
522cab237bSDimitry Andric #include "llvm/IR/Constant.h"
532cab237bSDimitry Andric #include "llvm/IR/Constants.h"
54284c1978SDimitry Andric #include "llvm/IR/DataLayout.h"
552cab237bSDimitry Andric #include "llvm/IR/DebugLoc.h"
562cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
5791bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
582cab237bSDimitry Andric #include "llvm/IR/Function.h"
5991bc56edSDimitry Andric #include "llvm/IR/IRBuilder.h"
602cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
612cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
62284c1978SDimitry Andric #include "llvm/IR/Instructions.h"
63284c1978SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
642cab237bSDimitry Andric #include "llvm/IR/Intrinsics.h"
65284c1978SDimitry Andric #include "llvm/IR/Module.h"
6691bc56edSDimitry Andric #include "llvm/IR/NoFolder.h"
672cab237bSDimitry Andric #include "llvm/IR/Operator.h"
682cab237bSDimitry Andric #include "llvm/IR/PassManager.h"
692cab237bSDimitry Andric #include "llvm/IR/PatternMatch.h"
70284c1978SDimitry Andric #include "llvm/IR/Type.h"
712cab237bSDimitry Andric #include "llvm/IR/Use.h"
722cab237bSDimitry Andric #include "llvm/IR/User.h"
73284c1978SDimitry Andric #include "llvm/IR/Value.h"
742cab237bSDimitry Andric #include "llvm/IR/ValueHandle.h"
7591bc56edSDimitry Andric #include "llvm/IR/Verifier.h"
76284c1978SDimitry Andric #include "llvm/Pass.h"
772cab237bSDimitry Andric #include "llvm/Support/Casting.h"
78284c1978SDimitry Andric #include "llvm/Support/CommandLine.h"
792cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
802cab237bSDimitry Andric #include "llvm/Support/DOTGraphTraits.h"
81284c1978SDimitry Andric #include "llvm/Support/Debug.h"
822cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
837a7e6055SDimitry Andric #include "llvm/Support/GraphWriter.h"
845517e702SDimitry Andric #include "llvm/Support/KnownBits.h"
852cab237bSDimitry Andric #include "llvm/Support/MathExtras.h"
86284c1978SDimitry Andric #include "llvm/Support/raw_ostream.h"
875517e702SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
883ca95b02SDimitry Andric #include "llvm/Transforms/Vectorize.h"
89f785676fSDimitry Andric #include <algorithm>
902cab237bSDimitry Andric #include <cassert>
912cab237bSDimitry Andric #include <cstdint>
922cab237bSDimitry Andric #include <iterator>
9339d628a0SDimitry Andric #include <memory>
942cab237bSDimitry Andric #include <set>
952cab237bSDimitry Andric #include <string>
962cab237bSDimitry Andric #include <tuple>
972cab237bSDimitry Andric #include <utility>
982cab237bSDimitry Andric #include <vector>
99284c1978SDimitry Andric
100284c1978SDimitry Andric using namespace llvm;
1012cab237bSDimitry Andric using namespace llvm::PatternMatch;
1023ca95b02SDimitry Andric using namespace slpvectorizer;
103284c1978SDimitry Andric
10491bc56edSDimitry Andric #define SV_NAME "slp-vectorizer"
10591bc56edSDimitry Andric #define DEBUG_TYPE "SLP"
10691bc56edSDimitry Andric
10739d628a0SDimitry Andric STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
10839d628a0SDimitry Andric
109284c1978SDimitry Andric static cl::opt<int>
110284c1978SDimitry Andric SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
111f785676fSDimitry Andric cl::desc("Only vectorize if you gain more than this "
112f785676fSDimitry Andric "number "));
113f785676fSDimitry Andric
114f785676fSDimitry Andric static cl::opt<bool>
1157d523365SDimitry Andric ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
116f785676fSDimitry Andric cl::desc("Attempt to vectorize horizontal reductions"));
117f785676fSDimitry Andric
118f785676fSDimitry Andric static cl::opt<bool> ShouldStartVectorizeHorAtStore(
119f785676fSDimitry Andric "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
120f785676fSDimitry Andric cl::desc(
121f785676fSDimitry Andric "Attempt to vectorize horizontal reductions feeding into a store"));
122f785676fSDimitry Andric
123875ed548SDimitry Andric static cl::opt<int>
124875ed548SDimitry Andric MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
125875ed548SDimitry Andric cl::desc("Attempt to vectorize for this register size in bits"));
126875ed548SDimitry Andric
1277d523365SDimitry Andric /// Limits the size of scheduling regions in a block.
1287d523365SDimitry Andric /// It avoid long compile times for _very_ large blocks where vector
1297d523365SDimitry Andric /// instructions are spread over a wide range.
1307d523365SDimitry Andric /// This limit is way higher than needed by real-world functions.
1317d523365SDimitry Andric static cl::opt<int>
1327d523365SDimitry Andric ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
1337d523365SDimitry Andric cl::desc("Limit the size of the SLP scheduling region per block"));
1347d523365SDimitry Andric
1353ca95b02SDimitry Andric static cl::opt<int> MinVectorRegSizeOption(
1363ca95b02SDimitry Andric "slp-min-reg-size", cl::init(128), cl::Hidden,
1373ca95b02SDimitry Andric cl::desc("Attempt to vectorize for this register size in bits"));
138284c1978SDimitry Andric
139fccc5558SDimitry Andric static cl::opt<unsigned> RecursionMaxDepth(
140fccc5558SDimitry Andric "slp-recursion-max-depth", cl::init(12), cl::Hidden,
141fccc5558SDimitry Andric cl::desc("Limit the recursion depth when building a vectorizable tree"));
142fccc5558SDimitry Andric
143fccc5558SDimitry Andric static cl::opt<unsigned> MinTreeSize(
144fccc5558SDimitry Andric "slp-min-tree-size", cl::init(3), cl::Hidden,
145fccc5558SDimitry Andric cl::desc("Only vectorize small trees if they are fully vectorizable"));
146f785676fSDimitry Andric
1477a7e6055SDimitry Andric static cl::opt<bool>
1487a7e6055SDimitry Andric ViewSLPTree("view-slp-tree", cl::Hidden,
1497a7e6055SDimitry Andric cl::desc("Display the SLP trees with Graphviz"));
1507a7e6055SDimitry Andric
151ff0cc061SDimitry Andric // Limit the number of alias checks. The limit is chosen so that
152ff0cc061SDimitry Andric // it has no negative effect on the llvm benchmarks.
153ff0cc061SDimitry Andric static const unsigned AliasedCheckLimit = 10;
154ff0cc061SDimitry Andric
155ff0cc061SDimitry Andric // Another limit for the alias checks: The maximum distance between load/store
156ff0cc061SDimitry Andric // instructions where alias checks are done.
157ff0cc061SDimitry Andric // This limit is useful for very large basic blocks.
158ff0cc061SDimitry Andric static const unsigned MaxMemDepDistance = 160;
159ff0cc061SDimitry Andric
1607d523365SDimitry Andric /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
1617d523365SDimitry Andric /// regions to be handled.
1627d523365SDimitry Andric static const int MinScheduleRegionSize = 16;
1637d523365SDimitry Andric
1644ba319b5SDimitry Andric /// Predicate for the element types that the SLP vectorizer supports.
16544f7b0dcSDimitry Andric ///
16644f7b0dcSDimitry Andric /// The most important thing to filter here are types which are invalid in LLVM
16744f7b0dcSDimitry Andric /// vectors. We also filter target specific types which have absolutely no
16844f7b0dcSDimitry Andric /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
16944f7b0dcSDimitry Andric /// avoids spending time checking the cost model and realizing that they will
17044f7b0dcSDimitry Andric /// be inevitably scalarized.
isValidElementType(Type * Ty)17144f7b0dcSDimitry Andric static bool isValidElementType(Type *Ty) {
17244f7b0dcSDimitry Andric return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
17344f7b0dcSDimitry Andric !Ty->isPPC_FP128Ty();
17444f7b0dcSDimitry Andric }
17544f7b0dcSDimitry Andric
176d88c1a5aSDimitry Andric /// \returns true if all of the instructions in \p VL are in the same block or
177d88c1a5aSDimitry Andric /// false otherwise.
allSameBlock(ArrayRef<Value * > VL)178d88c1a5aSDimitry Andric static bool allSameBlock(ArrayRef<Value *> VL) {
179f785676fSDimitry Andric Instruction *I0 = dyn_cast<Instruction>(VL[0]);
180f785676fSDimitry Andric if (!I0)
181d88c1a5aSDimitry Andric return false;
182f785676fSDimitry Andric BasicBlock *BB = I0->getParent();
183f785676fSDimitry Andric for (int i = 1, e = VL.size(); i < e; i++) {
184f785676fSDimitry Andric Instruction *I = dyn_cast<Instruction>(VL[i]);
185f785676fSDimitry Andric if (!I)
186d88c1a5aSDimitry Andric return false;
187f785676fSDimitry Andric
188f785676fSDimitry Andric if (BB != I->getParent())
189d88c1a5aSDimitry Andric return false;
190f785676fSDimitry Andric }
191d88c1a5aSDimitry Andric return true;
192f785676fSDimitry Andric }
193f785676fSDimitry Andric
194f785676fSDimitry Andric /// \returns True if all of the values in \p VL are constants.
allConstant(ArrayRef<Value * > VL)195f785676fSDimitry Andric static bool allConstant(ArrayRef<Value *> VL) {
1963ca95b02SDimitry Andric for (Value *i : VL)
1973ca95b02SDimitry Andric if (!isa<Constant>(i))
198f785676fSDimitry Andric return false;
199f785676fSDimitry Andric return true;
200f785676fSDimitry Andric }
201f785676fSDimitry Andric
202f785676fSDimitry Andric /// \returns True if all of the values in \p VL are identical.
isSplat(ArrayRef<Value * > VL)203f785676fSDimitry Andric static bool isSplat(ArrayRef<Value *> VL) {
204f785676fSDimitry Andric for (unsigned i = 1, e = VL.size(); i < e; ++i)
205f785676fSDimitry Andric if (VL[i] != VL[0])
206f785676fSDimitry Andric return false;
207f785676fSDimitry Andric return true;
208f785676fSDimitry Andric }
209f785676fSDimitry Andric
2102cab237bSDimitry Andric /// Checks if the vector of instructions can be represented as a shuffle, like:
2112cab237bSDimitry Andric /// %x0 = extractelement <4 x i8> %x, i32 0
2122cab237bSDimitry Andric /// %x3 = extractelement <4 x i8> %x, i32 3
2132cab237bSDimitry Andric /// %y1 = extractelement <4 x i8> %y, i32 1
2142cab237bSDimitry Andric /// %y2 = extractelement <4 x i8> %y, i32 2
2152cab237bSDimitry Andric /// %x0x0 = mul i8 %x0, %x0
2162cab237bSDimitry Andric /// %x3x3 = mul i8 %x3, %x3
2172cab237bSDimitry Andric /// %y1y1 = mul i8 %y1, %y1
2182cab237bSDimitry Andric /// %y2y2 = mul i8 %y2, %y2
2192cab237bSDimitry Andric /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
2202cab237bSDimitry Andric /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
2212cab237bSDimitry Andric /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
2222cab237bSDimitry Andric /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
2232cab237bSDimitry Andric /// ret <4 x i8> %ins4
2242cab237bSDimitry Andric /// can be transformed into:
2252cab237bSDimitry Andric /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
2262cab237bSDimitry Andric /// i32 6>
2272cab237bSDimitry Andric /// %2 = mul <4 x i8> %1, %1
2282cab237bSDimitry Andric /// ret <4 x i8> %2
2292cab237bSDimitry Andric /// We convert this initially to something like:
2302cab237bSDimitry Andric /// %x0 = extractelement <4 x i8> %x, i32 0
2312cab237bSDimitry Andric /// %x3 = extractelement <4 x i8> %x, i32 3
2322cab237bSDimitry Andric /// %y1 = extractelement <4 x i8> %y, i32 1
2332cab237bSDimitry Andric /// %y2 = extractelement <4 x i8> %y, i32 2
2342cab237bSDimitry Andric /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
2352cab237bSDimitry Andric /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
2362cab237bSDimitry Andric /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
2372cab237bSDimitry Andric /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
2382cab237bSDimitry Andric /// %5 = mul <4 x i8> %4, %4
2392cab237bSDimitry Andric /// %6 = extractelement <4 x i8> %5, i32 0
2402cab237bSDimitry Andric /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
2412cab237bSDimitry Andric /// %7 = extractelement <4 x i8> %5, i32 1
2422cab237bSDimitry Andric /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
2432cab237bSDimitry Andric /// %8 = extractelement <4 x i8> %5, i32 2
2442cab237bSDimitry Andric /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
2452cab237bSDimitry Andric /// %9 = extractelement <4 x i8> %5, i32 3
2462cab237bSDimitry Andric /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
2472cab237bSDimitry Andric /// ret <4 x i8> %ins4
2482cab237bSDimitry Andric /// InstCombiner transforms this into a shuffle and vector mul
2494ba319b5SDimitry Andric /// TODO: Can we split off and reuse the shuffle mask detection from
2504ba319b5SDimitry Andric /// TargetTransformInfo::getInstructionThroughput?
2512cab237bSDimitry Andric static Optional<TargetTransformInfo::ShuffleKind>
isShuffle(ArrayRef<Value * > VL)2522cab237bSDimitry Andric isShuffle(ArrayRef<Value *> VL) {
2532cab237bSDimitry Andric auto *EI0 = cast<ExtractElementInst>(VL[0]);
2542cab237bSDimitry Andric unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
2552cab237bSDimitry Andric Value *Vec1 = nullptr;
2562cab237bSDimitry Andric Value *Vec2 = nullptr;
2574ba319b5SDimitry Andric enum ShuffleMode { Unknown, Select, Permute };
2582cab237bSDimitry Andric ShuffleMode CommonShuffleMode = Unknown;
2592cab237bSDimitry Andric for (unsigned I = 0, E = VL.size(); I < E; ++I) {
2602cab237bSDimitry Andric auto *EI = cast<ExtractElementInst>(VL[I]);
2612cab237bSDimitry Andric auto *Vec = EI->getVectorOperand();
2622cab237bSDimitry Andric // All vector operands must have the same number of vector elements.
2632cab237bSDimitry Andric if (Vec->getType()->getVectorNumElements() != Size)
2642cab237bSDimitry Andric return None;
2652cab237bSDimitry Andric auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
2662cab237bSDimitry Andric if (!Idx)
2672cab237bSDimitry Andric return None;
2682cab237bSDimitry Andric // Undefined behavior if Idx is negative or >= Size.
2692cab237bSDimitry Andric if (Idx->getValue().uge(Size))
2702cab237bSDimitry Andric continue;
2712cab237bSDimitry Andric unsigned IntIdx = Idx->getValue().getZExtValue();
2722cab237bSDimitry Andric // We can extractelement from undef vector.
2732cab237bSDimitry Andric if (isa<UndefValue>(Vec))
2742cab237bSDimitry Andric continue;
2752cab237bSDimitry Andric // For correct shuffling we have to have at most 2 different vector operands
2762cab237bSDimitry Andric // in all extractelement instructions.
2774ba319b5SDimitry Andric if (!Vec1 || Vec1 == Vec)
2784ba319b5SDimitry Andric Vec1 = Vec;
2794ba319b5SDimitry Andric else if (!Vec2 || Vec2 == Vec)
2804ba319b5SDimitry Andric Vec2 = Vec;
2814ba319b5SDimitry Andric else
2822cab237bSDimitry Andric return None;
2832cab237bSDimitry Andric if (CommonShuffleMode == Permute)
2842cab237bSDimitry Andric continue;
2852cab237bSDimitry Andric // If the extract index is not the same as the operation number, it is a
2862cab237bSDimitry Andric // permutation.
2872cab237bSDimitry Andric if (IntIdx != I) {
2882cab237bSDimitry Andric CommonShuffleMode = Permute;
2892cab237bSDimitry Andric continue;
2902cab237bSDimitry Andric }
2914ba319b5SDimitry Andric CommonShuffleMode = Select;
2922cab237bSDimitry Andric }
2932cab237bSDimitry Andric // If we're not crossing lanes in different vectors, consider it as blending.
2944ba319b5SDimitry Andric if (CommonShuffleMode == Select && Vec2)
2954ba319b5SDimitry Andric return TargetTransformInfo::SK_Select;
2962cab237bSDimitry Andric // If Vec2 was never used, we have a permutation of a single vector, otherwise
2972cab237bSDimitry Andric // we have permutation of 2 vectors.
2982cab237bSDimitry Andric return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
2992cab237bSDimitry Andric : TargetTransformInfo::SK_PermuteSingleSrc;
3002cab237bSDimitry Andric }
3012cab237bSDimitry Andric
3022cab237bSDimitry Andric namespace {
3032cab237bSDimitry Andric
3042cab237bSDimitry Andric /// Main data required for vectorization of instructions.
3052cab237bSDimitry Andric struct InstructionsState {
3062cab237bSDimitry Andric /// The very first instruction in the list with the main opcode.
3072cab237bSDimitry Andric Value *OpValue = nullptr;
3082cab237bSDimitry Andric
3094ba319b5SDimitry Andric /// The main/alternate instruction.
3104ba319b5SDimitry Andric Instruction *MainOp = nullptr;
3114ba319b5SDimitry Andric Instruction *AltOp = nullptr;
3124ba319b5SDimitry Andric
3134ba319b5SDimitry Andric /// The main/alternate opcodes for the list of instructions.
getOpcode__anonfe9ee8d90111::InstructionsState3144ba319b5SDimitry Andric unsigned getOpcode() const {
3154ba319b5SDimitry Andric return MainOp ? MainOp->getOpcode() : 0;
3164ba319b5SDimitry Andric }
3174ba319b5SDimitry Andric
getAltOpcode__anonfe9ee8d90111::InstructionsState3184ba319b5SDimitry Andric unsigned getAltOpcode() const {
3194ba319b5SDimitry Andric return AltOp ? AltOp->getOpcode() : 0;
3204ba319b5SDimitry Andric }
3212cab237bSDimitry Andric
3222cab237bSDimitry Andric /// Some of the instructions in the list have alternate opcodes.
isAltShuffle__anonfe9ee8d90111::InstructionsState3234ba319b5SDimitry Andric bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
3242cab237bSDimitry Andric
isOpcodeOrAlt__anonfe9ee8d90111::InstructionsState3254ba319b5SDimitry Andric bool isOpcodeOrAlt(Instruction *I) const {
3264ba319b5SDimitry Andric unsigned CheckedOpcode = I->getOpcode();
3274ba319b5SDimitry Andric return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
3284ba319b5SDimitry Andric }
3294ba319b5SDimitry Andric
3304ba319b5SDimitry Andric InstructionsState() = delete;
InstructionsState__anonfe9ee8d90111::InstructionsState3314ba319b5SDimitry Andric InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
3324ba319b5SDimitry Andric : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
3332cab237bSDimitry Andric };
3342cab237bSDimitry Andric
3352cab237bSDimitry Andric } // end anonymous namespace
3362cab237bSDimitry Andric
3374ba319b5SDimitry Andric /// Chooses the correct key for scheduling data. If \p Op has the same (or
3384ba319b5SDimitry Andric /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
3394ba319b5SDimitry Andric /// OpValue.
isOneOf(const InstructionsState & S,Value * Op)3404ba319b5SDimitry Andric static Value *isOneOf(const InstructionsState &S, Value *Op) {
3414ba319b5SDimitry Andric auto *I = dyn_cast<Instruction>(Op);
3424ba319b5SDimitry Andric if (I && S.isOpcodeOrAlt(I))
3434ba319b5SDimitry Andric return Op;
3444ba319b5SDimitry Andric return S.OpValue;
3454ba319b5SDimitry Andric }
3464ba319b5SDimitry Andric
3472cab237bSDimitry Andric /// \returns analysis of the Instructions in \p VL described in
3482cab237bSDimitry Andric /// InstructionsState, the Opcode that we suppose the whole list
3492cab237bSDimitry Andric /// could be vectorized even if its structure is diverse.
getSameOpcode(ArrayRef<Value * > VL,unsigned BaseIndex=0)3504ba319b5SDimitry Andric static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
3514ba319b5SDimitry Andric unsigned BaseIndex = 0) {
3524ba319b5SDimitry Andric // Make sure these are all Instructions.
3534ba319b5SDimitry Andric if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
3544ba319b5SDimitry Andric return InstructionsState(VL[BaseIndex], nullptr, nullptr);
3554ba319b5SDimitry Andric
3564ba319b5SDimitry Andric bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
3574ba319b5SDimitry Andric bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
3584ba319b5SDimitry Andric unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
3594ba319b5SDimitry Andric unsigned AltOpcode = Opcode;
3604ba319b5SDimitry Andric unsigned AltIndex = BaseIndex;
3614ba319b5SDimitry Andric
3624ba319b5SDimitry Andric // Check for one alternate opcode from another BinaryOperator.
3634ba319b5SDimitry Andric // TODO - generalize to support all operators (types, calls etc.).
3642cab237bSDimitry Andric for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
3654ba319b5SDimitry Andric unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
3664ba319b5SDimitry Andric if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
3674ba319b5SDimitry Andric if (InstOpcode == Opcode || InstOpcode == AltOpcode)
3684ba319b5SDimitry Andric continue;
3694ba319b5SDimitry Andric if (Opcode == AltOpcode) {
3704ba319b5SDimitry Andric AltOpcode = InstOpcode;
3714ba319b5SDimitry Andric AltIndex = Cnt;
3724ba319b5SDimitry Andric continue;
3734ba319b5SDimitry Andric }
3744ba319b5SDimitry Andric } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
3754ba319b5SDimitry Andric Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
3764ba319b5SDimitry Andric Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
3774ba319b5SDimitry Andric if (Ty0 == Ty1) {
3784ba319b5SDimitry Andric if (InstOpcode == Opcode || InstOpcode == AltOpcode)
3794ba319b5SDimitry Andric continue;
3804ba319b5SDimitry Andric if (Opcode == AltOpcode) {
3814ba319b5SDimitry Andric AltOpcode = InstOpcode;
3824ba319b5SDimitry Andric AltIndex = Cnt;
3834ba319b5SDimitry Andric continue;
384f785676fSDimitry Andric }
38591bc56edSDimitry Andric }
3864ba319b5SDimitry Andric } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
3874ba319b5SDimitry Andric continue;
3884ba319b5SDimitry Andric return InstructionsState(VL[BaseIndex], nullptr, nullptr);
3894ba319b5SDimitry Andric }
3904ba319b5SDimitry Andric
3914ba319b5SDimitry Andric return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
3924ba319b5SDimitry Andric cast<Instruction>(VL[AltIndex]));
393f785676fSDimitry Andric }
394f785676fSDimitry Andric
395d88c1a5aSDimitry Andric /// \returns true if all of the values in \p VL have the same type or false
396d88c1a5aSDimitry Andric /// otherwise.
allSameType(ArrayRef<Value * > VL)397d88c1a5aSDimitry Andric static bool allSameType(ArrayRef<Value *> VL) {
398f785676fSDimitry Andric Type *Ty = VL[0]->getType();
399f785676fSDimitry Andric for (int i = 1, e = VL.size(); i < e; i++)
400f785676fSDimitry Andric if (VL[i]->getType() != Ty)
401d88c1a5aSDimitry Andric return false;
402f785676fSDimitry Andric
403d88c1a5aSDimitry Andric return true;
404f785676fSDimitry Andric }
405f785676fSDimitry Andric
4063ca95b02SDimitry Andric /// \returns True if Extract{Value,Element} instruction extracts element Idx.
getExtractIndex(Instruction * E)4074ba319b5SDimitry Andric static Optional<unsigned> getExtractIndex(Instruction *E) {
4084ba319b5SDimitry Andric unsigned Opcode = E->getOpcode();
4094ba319b5SDimitry Andric assert((Opcode == Instruction::ExtractElement ||
4104ba319b5SDimitry Andric Opcode == Instruction::ExtractValue) &&
4114ba319b5SDimitry Andric "Expected extractelement or extractvalue instruction.");
4123ca95b02SDimitry Andric if (Opcode == Instruction::ExtractElement) {
4134ba319b5SDimitry Andric auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
4144ba319b5SDimitry Andric if (!CI)
4154ba319b5SDimitry Andric return None;
4164ba319b5SDimitry Andric return CI->getZExtValue();
417f785676fSDimitry Andric }
4184ba319b5SDimitry Andric ExtractValueInst *EI = cast<ExtractValueInst>(E);
4194ba319b5SDimitry Andric if (EI->getNumIndices() != 1)
4204ba319b5SDimitry Andric return None;
4214ba319b5SDimitry Andric return *EI->idx_begin();
422f785676fSDimitry Andric }
423f785676fSDimitry Andric
42439d628a0SDimitry Andric /// \returns True if in-tree use also needs extract. This refers to
42539d628a0SDimitry Andric /// possible scalar operand in vectorized instruction.
InTreeUserNeedToExtract(Value * Scalar,Instruction * UserInst,TargetLibraryInfo * TLI)42639d628a0SDimitry Andric static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
42739d628a0SDimitry Andric TargetLibraryInfo *TLI) {
42839d628a0SDimitry Andric unsigned Opcode = UserInst->getOpcode();
42939d628a0SDimitry Andric switch (Opcode) {
43039d628a0SDimitry Andric case Instruction::Load: {
43139d628a0SDimitry Andric LoadInst *LI = cast<LoadInst>(UserInst);
43239d628a0SDimitry Andric return (LI->getPointerOperand() == Scalar);
43339d628a0SDimitry Andric }
43439d628a0SDimitry Andric case Instruction::Store: {
43539d628a0SDimitry Andric StoreInst *SI = cast<StoreInst>(UserInst);
43639d628a0SDimitry Andric return (SI->getPointerOperand() == Scalar);
43739d628a0SDimitry Andric }
43839d628a0SDimitry Andric case Instruction::Call: {
43939d628a0SDimitry Andric CallInst *CI = cast<CallInst>(UserInst);
4403ca95b02SDimitry Andric Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
44139d628a0SDimitry Andric if (hasVectorInstrinsicScalarOpd(ID, 1)) {
44239d628a0SDimitry Andric return (CI->getArgOperand(1) == Scalar);
44339d628a0SDimitry Andric }
4446d97bb29SDimitry Andric LLVM_FALLTHROUGH;
44539d628a0SDimitry Andric }
44639d628a0SDimitry Andric default:
44739d628a0SDimitry Andric return false;
44839d628a0SDimitry Andric }
44939d628a0SDimitry Andric }
45039d628a0SDimitry Andric
45139d628a0SDimitry Andric /// \returns the AA location that is being access by the instruction.
getLocation(Instruction * I,AliasAnalysis * AA)4528f0fd8f6SDimitry Andric static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
45339d628a0SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(I))
45497bc6c73SDimitry Andric return MemoryLocation::get(SI);
45539d628a0SDimitry Andric if (LoadInst *LI = dyn_cast<LoadInst>(I))
45697bc6c73SDimitry Andric return MemoryLocation::get(LI);
4578f0fd8f6SDimitry Andric return MemoryLocation();
45839d628a0SDimitry Andric }
45939d628a0SDimitry Andric
460ff0cc061SDimitry Andric /// \returns True if the instruction is not a volatile or atomic load/store.
isSimple(Instruction * I)461ff0cc061SDimitry Andric static bool isSimple(Instruction *I) {
462ff0cc061SDimitry Andric if (LoadInst *LI = dyn_cast<LoadInst>(I))
463ff0cc061SDimitry Andric return LI->isSimple();
464ff0cc061SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(I))
465ff0cc061SDimitry Andric return SI->isSimple();
466ff0cc061SDimitry Andric if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
467ff0cc061SDimitry Andric return !MI->isVolatile();
468ff0cc061SDimitry Andric return true;
469ff0cc061SDimitry Andric }
470ff0cc061SDimitry Andric
4713ca95b02SDimitry Andric namespace llvm {
4722cab237bSDimitry Andric
4733ca95b02SDimitry Andric namespace slpvectorizer {
4742cab237bSDimitry Andric
475f785676fSDimitry Andric /// Bottom Up SLP Vectorizer.
476f785676fSDimitry Andric class BoUpSLP {
477f785676fSDimitry Andric public:
4782cab237bSDimitry Andric using ValueList = SmallVector<Value *, 8>;
4792cab237bSDimitry Andric using InstrList = SmallVector<Instruction *, 16>;
4802cab237bSDimitry Andric using ValueSet = SmallPtrSet<Value *, 16>;
4812cab237bSDimitry Andric using StoreList = SmallVector<StoreInst *, 8>;
4822cab237bSDimitry Andric using ExtraValueToDebugLocsMap =
4832cab237bSDimitry Andric MapVector<Value *, SmallVector<Instruction *, 2>>;
484f785676fSDimitry Andric
BoUpSLP(Function * Func,ScalarEvolution * Se,TargetTransformInfo * Tti,TargetLibraryInfo * TLi,AliasAnalysis * Aa,LoopInfo * Li,DominatorTree * Dt,AssumptionCache * AC,DemandedBits * DB,const DataLayout * DL,OptimizationRemarkEmitter * ORE)485ff0cc061SDimitry Andric BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
486ff0cc061SDimitry Andric TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
4873ca95b02SDimitry Andric DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
4885517e702SDimitry Andric const DataLayout *DL, OptimizationRemarkEmitter *ORE)
4892cab237bSDimitry Andric : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
4902cab237bSDimitry Andric DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
49139d628a0SDimitry Andric CodeMetrics::collectEphemeralValues(F, AC, EphValues);
4923ca95b02SDimitry Andric // Use the vector register size specified by the target unless overridden
4933ca95b02SDimitry Andric // by a command-line option.
4943ca95b02SDimitry Andric // TODO: It would be better to limit the vectorization factor based on
4953ca95b02SDimitry Andric // data type rather than just register size. For example, x86 AVX has
4963ca95b02SDimitry Andric // 256-bit registers, but it does not support integer operations
4973ca95b02SDimitry Andric // at that width (that requires AVX2).
4983ca95b02SDimitry Andric if (MaxVectorRegSizeOption.getNumOccurrences())
4993ca95b02SDimitry Andric MaxVecRegSize = MaxVectorRegSizeOption;
5003ca95b02SDimitry Andric else
5013ca95b02SDimitry Andric MaxVecRegSize = TTI->getRegisterBitWidth(true);
5023ca95b02SDimitry Andric
5035517e702SDimitry Andric if (MinVectorRegSizeOption.getNumOccurrences())
5043ca95b02SDimitry Andric MinVecRegSize = MinVectorRegSizeOption;
5055517e702SDimitry Andric else
5065517e702SDimitry Andric MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
50739d628a0SDimitry Andric }
508f785676fSDimitry Andric
5094ba319b5SDimitry Andric /// Vectorize the tree that starts with the elements in \p VL.
510f785676fSDimitry Andric /// Returns the vectorized root.
511f785676fSDimitry Andric Value *vectorizeTree();
5122cab237bSDimitry Andric
5137a7e6055SDimitry Andric /// Vectorize the tree but with the list of externally used values \p
5147a7e6055SDimitry Andric /// ExternallyUsedValues. Values in this MapVector can be replaced but the
5157a7e6055SDimitry Andric /// generated extractvalue instructions.
5167a7e6055SDimitry Andric Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
517f785676fSDimitry Andric
51839d628a0SDimitry Andric /// \returns the cost incurred by unwanted spills and fills, caused by
51939d628a0SDimitry Andric /// holding live values over call sites.
52039d628a0SDimitry Andric int getSpillCost();
52139d628a0SDimitry Andric
522f785676fSDimitry Andric /// \returns the vectorization cost of the subtree that starts at \p VL.
523f785676fSDimitry Andric /// A negative number means that this is profitable.
524f785676fSDimitry Andric int getTreeCost();
525f785676fSDimitry Andric
52691bc56edSDimitry Andric /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
52791bc56edSDimitry Andric /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
52891bc56edSDimitry Andric void buildTree(ArrayRef<Value *> Roots,
52991bc56edSDimitry Andric ArrayRef<Value *> UserIgnoreLst = None);
5302cab237bSDimitry Andric
5317a7e6055SDimitry Andric /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
5327a7e6055SDimitry Andric /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
5337a7e6055SDimitry Andric /// into account (anf updating it, if required) list of externally used
5347a7e6055SDimitry Andric /// values stored in \p ExternallyUsedValues.
5357a7e6055SDimitry Andric void buildTree(ArrayRef<Value *> Roots,
5367a7e6055SDimitry Andric ExtraValueToDebugLocsMap &ExternallyUsedValues,
5377a7e6055SDimitry Andric ArrayRef<Value *> UserIgnoreLst = None);
538f785676fSDimitry Andric
539f785676fSDimitry Andric /// Clear the internal data structures that are created by 'buildTree'.
deleteTree()540f785676fSDimitry Andric void deleteTree() {
541f785676fSDimitry Andric VectorizableTree.clear();
542f785676fSDimitry Andric ScalarToTreeEntry.clear();
543f785676fSDimitry Andric MustGather.clear();
544f785676fSDimitry Andric ExternalUses.clear();
5454ba319b5SDimitry Andric NumOpsWantToKeepOrder.clear();
5464ba319b5SDimitry Andric NumOpsWantToKeepOriginalOrder = 0;
54739d628a0SDimitry Andric for (auto &Iter : BlocksSchedules) {
54839d628a0SDimitry Andric BlockScheduling *BS = Iter.second.get();
54939d628a0SDimitry Andric BS->clear();
55039d628a0SDimitry Andric }
5513ca95b02SDimitry Andric MinBWs.clear();
552f785676fSDimitry Andric }
553f785676fSDimitry Andric
getTreeSize() const5545517e702SDimitry Andric unsigned getTreeSize() const { return VectorizableTree.size(); }
5555517e702SDimitry Andric
5564ba319b5SDimitry Andric /// Perform LICM and CSE on the newly generated gather sequences.
5574ba319b5SDimitry Andric void optimizeGatherSequence();
55891bc56edSDimitry Andric
5594ba319b5SDimitry Andric /// \returns The best order of instructions for vectorization.
bestOrder() const5604ba319b5SDimitry Andric Optional<ArrayRef<unsigned>> bestOrder() const {
5614ba319b5SDimitry Andric auto I = std::max_element(
5624ba319b5SDimitry Andric NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
5634ba319b5SDimitry Andric [](const decltype(NumOpsWantToKeepOrder)::value_type &D1,
5644ba319b5SDimitry Andric const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
5654ba319b5SDimitry Andric return D1.second < D2.second;
5664ba319b5SDimitry Andric });
5674ba319b5SDimitry Andric if (I == NumOpsWantToKeepOrder.end() ||
5684ba319b5SDimitry Andric I->getSecond() <= NumOpsWantToKeepOriginalOrder)
5694ba319b5SDimitry Andric return None;
5704ba319b5SDimitry Andric
5714ba319b5SDimitry Andric return makeArrayRef(I->getFirst());
57239d628a0SDimitry Andric }
57339d628a0SDimitry Andric
5743ca95b02SDimitry Andric /// \return The vector element size in bits to use when vectorizing the
5753ca95b02SDimitry Andric /// expression tree ending at \p V. If V is a store, the size is the width of
5763ca95b02SDimitry Andric /// the stored value. Otherwise, the size is the width of the largest loaded
5773ca95b02SDimitry Andric /// value reaching V. This method is used by the vectorizer to calculate
5783ca95b02SDimitry Andric /// vectorization factors.
5793ca95b02SDimitry Andric unsigned getVectorElementSize(Value *V);
5803ca95b02SDimitry Andric
5813ca95b02SDimitry Andric /// Compute the minimum type sizes required to represent the entries in a
5823ca95b02SDimitry Andric /// vectorizable tree.
5833ca95b02SDimitry Andric void computeMinimumValueSizes();
5843ca95b02SDimitry Andric
5853ca95b02SDimitry Andric // \returns maximum vector register size as set by TTI or overridden by cl::opt.
getMaxVecRegSize() const5863ca95b02SDimitry Andric unsigned getMaxVecRegSize() const {
5873ca95b02SDimitry Andric return MaxVecRegSize;
5883ca95b02SDimitry Andric }
5893ca95b02SDimitry Andric
5903ca95b02SDimitry Andric // \returns minimum vector register size as set by cl::opt.
getMinVecRegSize() const5913ca95b02SDimitry Andric unsigned getMinVecRegSize() const {
5923ca95b02SDimitry Andric return MinVecRegSize;
5933ca95b02SDimitry Andric }
5943ca95b02SDimitry Andric
5954ba319b5SDimitry Andric /// Check if ArrayType or StructType is isomorphic to some VectorType.
5963ca95b02SDimitry Andric ///
5973ca95b02SDimitry Andric /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
5983ca95b02SDimitry Andric unsigned canMapToVector(Type *T, const DataLayout &DL) const;
5993ca95b02SDimitry Andric
600d88c1a5aSDimitry Andric /// \returns True if the VectorizableTree is both tiny and not fully
601d88c1a5aSDimitry Andric /// vectorizable. We do not vectorize such trees.
602d88c1a5aSDimitry Andric bool isTreeTinyAndNotFullyVectorizable();
603d88c1a5aSDimitry Andric
getORE()6045517e702SDimitry Andric OptimizationRemarkEmitter *getORE() { return ORE; }
6055517e702SDimitry Andric
606f785676fSDimitry Andric private:
607f785676fSDimitry Andric struct TreeEntry;
608f785676fSDimitry Andric
6092cab237bSDimitry Andric /// Checks if all users of \p I are the part of the vectorization tree.
6102cab237bSDimitry Andric bool areAllUsersVectorized(Instruction *I) const;
6112cab237bSDimitry Andric
612f785676fSDimitry Andric /// \returns the cost of the vectorizable entry.
613f785676fSDimitry Andric int getEntryCost(TreeEntry *E);
614f785676fSDimitry Andric
615f785676fSDimitry Andric /// This is the recursive part of buildTree.
616da09e106SDimitry Andric void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, int);
617f785676fSDimitry Andric
6184ba319b5SDimitry Andric /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
6194ba319b5SDimitry Andric /// be vectorized to use the original vector (or aggregate "bitcast" to a
6204ba319b5SDimitry Andric /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
6214ba319b5SDimitry Andric /// returns false, setting \p CurrentOrder to either an empty vector or a
6224ba319b5SDimitry Andric /// non-identity permutation that allows to reuse extract instructions.
6234ba319b5SDimitry Andric bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
6244ba319b5SDimitry Andric SmallVectorImpl<unsigned> &CurrentOrder) const;
6253ca95b02SDimitry Andric
626da09e106SDimitry Andric /// Vectorize a single entry in the tree.
627da09e106SDimitry Andric Value *vectorizeTree(TreeEntry *E);
628f785676fSDimitry Andric
629da09e106SDimitry Andric /// Vectorize a single entry in the tree, starting in \p VL.
630da09e106SDimitry Andric Value *vectorizeTree(ArrayRef<Value *> VL);
631f785676fSDimitry Andric
632f785676fSDimitry Andric /// \returns the scalarization cost for this type. Scalarization in this
633f785676fSDimitry Andric /// context means the creation of vectors from a group of scalars.
6344ba319b5SDimitry Andric int getGatherCost(Type *Ty, const DenseSet<unsigned> &ShuffledIndices);
635f785676fSDimitry Andric
636f785676fSDimitry Andric /// \returns the scalarization cost for this list of values. Assuming that
637f785676fSDimitry Andric /// this subtree gets vectorized, we may need to extract the values from the
638f785676fSDimitry Andric /// roots. This method calculates the cost of extracting the values.
639f785676fSDimitry Andric int getGatherCost(ArrayRef<Value *> VL);
640f785676fSDimitry Andric
6414ba319b5SDimitry Andric /// Set the Builder insert point to one after the last instruction in
642f785676fSDimitry Andric /// the bundle
6434ba319b5SDimitry Andric void setInsertPointAfterBundle(ArrayRef<Value *> VL,
6444ba319b5SDimitry Andric const InstructionsState &S);
645f785676fSDimitry Andric
646f785676fSDimitry Andric /// \returns a vector from a collection of scalars in \p VL.
647f785676fSDimitry Andric Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
648f785676fSDimitry Andric
6497d523365SDimitry Andric /// \returns whether the VectorizableTree is fully vectorizable and will
650f785676fSDimitry Andric /// be beneficial even the tree height is tiny.
651f785676fSDimitry Andric bool isFullyVectorizableTinyTree();
652f785676fSDimitry Andric
653ff0cc061SDimitry Andric /// \reorder commutative operands in alt shuffle if they result in
654ff0cc061SDimitry Andric /// vectorized code.
6554ba319b5SDimitry Andric void reorderAltShuffleOperands(const InstructionsState &S,
6564ba319b5SDimitry Andric ArrayRef<Value *> VL,
657ff0cc061SDimitry Andric SmallVectorImpl<Value *> &Left,
658ff0cc061SDimitry Andric SmallVectorImpl<Value *> &Right);
6592cab237bSDimitry Andric
660ff0cc061SDimitry Andric /// \reorder commutative operands to get better probability of
661ff0cc061SDimitry Andric /// generating vectorized code.
6622cab237bSDimitry Andric void reorderInputsAccordingToOpcode(unsigned Opcode, ArrayRef<Value *> VL,
663ff0cc061SDimitry Andric SmallVectorImpl<Value *> &Left,
664ff0cc061SDimitry Andric SmallVectorImpl<Value *> &Right);
665f785676fSDimitry Andric struct TreeEntry {
TreeEntryllvm::slpvectorizer::BoUpSLP::TreeEntry6662cab237bSDimitry Andric TreeEntry(std::vector<TreeEntry> &Container) : Container(Container) {}
667f785676fSDimitry Andric
668f785676fSDimitry Andric /// \returns true if the scalars in VL are equal to this entry.
isSamellvm::slpvectorizer::BoUpSLP::TreeEntry669f785676fSDimitry Andric bool isSame(ArrayRef<Value *> VL) const {
6704ba319b5SDimitry Andric if (VL.size() == Scalars.size())
671f785676fSDimitry Andric return std::equal(VL.begin(), VL.end(), Scalars.begin());
6724ba319b5SDimitry Andric return VL.size() == ReuseShuffleIndices.size() &&
6734ba319b5SDimitry Andric std::equal(
6744ba319b5SDimitry Andric VL.begin(), VL.end(), ReuseShuffleIndices.begin(),
6754ba319b5SDimitry Andric [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; });
676f785676fSDimitry Andric }
677f785676fSDimitry Andric
678f785676fSDimitry Andric /// A vector of scalars.
679f785676fSDimitry Andric ValueList Scalars;
680f785676fSDimitry Andric
681f785676fSDimitry Andric /// The Scalars are vectorized into this value. It is initialized to Null.
6822cab237bSDimitry Andric Value *VectorizedValue = nullptr;
683f785676fSDimitry Andric
684f785676fSDimitry Andric /// Do we need to gather this sequence ?
6852cab237bSDimitry Andric bool NeedToGather = false;
6862cab237bSDimitry Andric
6874ba319b5SDimitry Andric /// Does this sequence require some shuffling?
6884ba319b5SDimitry Andric SmallVector<unsigned, 4> ReuseShuffleIndices;
6894ba319b5SDimitry Andric
6904ba319b5SDimitry Andric /// Does this entry require reordering?
6914ba319b5SDimitry Andric ArrayRef<unsigned> ReorderIndices;
6924ba319b5SDimitry Andric
6937a7e6055SDimitry Andric /// Points back to the VectorizableTree.
6947a7e6055SDimitry Andric ///
6957a7e6055SDimitry Andric /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
6967a7e6055SDimitry Andric /// to be a pointer and needs to be able to initialize the child iterator.
6977a7e6055SDimitry Andric /// Thus we need a reference back to the container to translate the indices
6987a7e6055SDimitry Andric /// to entries.
6997a7e6055SDimitry Andric std::vector<TreeEntry> &Container;
7007a7e6055SDimitry Andric
7017a7e6055SDimitry Andric /// The TreeEntry index containing the user of this entry. We can actually
7027a7e6055SDimitry Andric /// have multiple users so the data structure is not truly a tree.
7037a7e6055SDimitry Andric SmallVector<int, 1> UserTreeIndices;
704f785676fSDimitry Andric };
705f785676fSDimitry Andric
706f785676fSDimitry Andric /// Create a new VectorizableTree entry.
newTreeEntry(ArrayRef<Value * > VL,bool Vectorized,int & UserTreeIdx,ArrayRef<unsigned> ReuseShuffleIndices=None,ArrayRef<unsigned> ReorderIndices=None)7074ba319b5SDimitry Andric void newTreeEntry(ArrayRef<Value *> VL, bool Vectorized, int &UserTreeIdx,
7084ba319b5SDimitry Andric ArrayRef<unsigned> ReuseShuffleIndices = None,
7094ba319b5SDimitry Andric ArrayRef<unsigned> ReorderIndices = None) {
7107a7e6055SDimitry Andric VectorizableTree.emplace_back(VectorizableTree);
711f785676fSDimitry Andric int idx = VectorizableTree.size() - 1;
712f785676fSDimitry Andric TreeEntry *Last = &VectorizableTree[idx];
713f785676fSDimitry Andric Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
714f785676fSDimitry Andric Last->NeedToGather = !Vectorized;
7154ba319b5SDimitry Andric Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
7164ba319b5SDimitry Andric ReuseShuffleIndices.end());
7174ba319b5SDimitry Andric Last->ReorderIndices = ReorderIndices;
718f785676fSDimitry Andric if (Vectorized) {
719f785676fSDimitry Andric for (int i = 0, e = VL.size(); i != e; ++i) {
720a580b014SDimitry Andric assert(!getTreeEntry(VL[i]) && "Scalar already in tree!");
721f785676fSDimitry Andric ScalarToTreeEntry[VL[i]] = idx;
722f785676fSDimitry Andric }
723f785676fSDimitry Andric } else {
724f785676fSDimitry Andric MustGather.insert(VL.begin(), VL.end());
725f785676fSDimitry Andric }
7267a7e6055SDimitry Andric
7277a7e6055SDimitry Andric if (UserTreeIdx >= 0)
7287a7e6055SDimitry Andric Last->UserTreeIndices.push_back(UserTreeIdx);
7297a7e6055SDimitry Andric UserTreeIdx = idx;
730f785676fSDimitry Andric }
731f785676fSDimitry Andric
732f785676fSDimitry Andric /// -- Vectorization State --
733f785676fSDimitry Andric /// Holds all of the tree entries.
734f785676fSDimitry Andric std::vector<TreeEntry> VectorizableTree;
735f785676fSDimitry Andric
getTreeEntry(Value * V)736a580b014SDimitry Andric TreeEntry *getTreeEntry(Value *V) {
737a580b014SDimitry Andric auto I = ScalarToTreeEntry.find(V);
738a580b014SDimitry Andric if (I != ScalarToTreeEntry.end())
739a580b014SDimitry Andric return &VectorizableTree[I->second];
740a580b014SDimitry Andric return nullptr;
741a580b014SDimitry Andric }
742a580b014SDimitry Andric
743f785676fSDimitry Andric /// Maps a specific scalar to its tree entry.
744f785676fSDimitry Andric SmallDenseMap<Value*, int> ScalarToTreeEntry;
745f785676fSDimitry Andric
746f785676fSDimitry Andric /// A list of scalars that we found that we need to keep as scalars.
747f785676fSDimitry Andric ValueSet MustGather;
748f785676fSDimitry Andric
749f785676fSDimitry Andric /// This POD struct describes one external user in the vectorized tree.
750f785676fSDimitry Andric struct ExternalUser {
ExternalUserllvm::slpvectorizer::BoUpSLP::ExternalUser7512cab237bSDimitry Andric ExternalUser(Value *S, llvm::User *U, int L)
7522cab237bSDimitry Andric : Scalar(S), User(U), Lane(L) {}
7532cab237bSDimitry Andric
754f785676fSDimitry Andric // Which scalar in our function.
755f785676fSDimitry Andric Value *Scalar;
7562cab237bSDimitry Andric
757f785676fSDimitry Andric // Which user that uses the scalar.
758f785676fSDimitry Andric llvm::User *User;
7592cab237bSDimitry Andric
760f785676fSDimitry Andric // Which lane does the scalar belong to.
761f785676fSDimitry Andric int Lane;
762f785676fSDimitry Andric };
7632cab237bSDimitry Andric using UserList = SmallVector<ExternalUser, 16>;
764f785676fSDimitry Andric
76539d628a0SDimitry Andric /// Checks if two instructions may access the same memory.
76639d628a0SDimitry Andric ///
76739d628a0SDimitry Andric /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
76839d628a0SDimitry Andric /// is invariant in the calling loop.
isAliased(const MemoryLocation & Loc1,Instruction * Inst1,Instruction * Inst2)7698f0fd8f6SDimitry Andric bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
77039d628a0SDimitry Andric Instruction *Inst2) {
77139d628a0SDimitry Andric // First check if the result is already in the cache.
77239d628a0SDimitry Andric AliasCacheKey key = std::make_pair(Inst1, Inst2);
77339d628a0SDimitry Andric Optional<bool> &result = AliasCache[key];
77439d628a0SDimitry Andric if (result.hasValue()) {
77539d628a0SDimitry Andric return result.getValue();
77639d628a0SDimitry Andric }
7778f0fd8f6SDimitry Andric MemoryLocation Loc2 = getLocation(Inst2, AA);
77839d628a0SDimitry Andric bool aliased = true;
779ff0cc061SDimitry Andric if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
78039d628a0SDimitry Andric // Do the alias check.
78139d628a0SDimitry Andric aliased = AA->alias(Loc1, Loc2);
78239d628a0SDimitry Andric }
78339d628a0SDimitry Andric // Store the result in the cache.
78439d628a0SDimitry Andric result = aliased;
78539d628a0SDimitry Andric return aliased;
78639d628a0SDimitry Andric }
78739d628a0SDimitry Andric
7882cab237bSDimitry Andric using AliasCacheKey = std::pair<Instruction *, Instruction *>;
78939d628a0SDimitry Andric
79039d628a0SDimitry Andric /// Cache for alias results.
79139d628a0SDimitry Andric /// TODO: consider moving this to the AliasAnalysis itself.
79239d628a0SDimitry Andric DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
79339d628a0SDimitry Andric
79439d628a0SDimitry Andric /// Removes an instruction from its block and eventually deletes it.
79539d628a0SDimitry Andric /// It's like Instruction::eraseFromParent() except that the actual deletion
79639d628a0SDimitry Andric /// is delayed until BoUpSLP is destructed.
79739d628a0SDimitry Andric /// This is required to ensure that there are no incorrect collisions in the
79839d628a0SDimitry Andric /// AliasCache, which can happen if a new instruction is allocated at the
79939d628a0SDimitry Andric /// same address as a previously deleted instruction.
eraseInstruction(Instruction * I)80039d628a0SDimitry Andric void eraseInstruction(Instruction *I) {
80139d628a0SDimitry Andric I->removeFromParent();
80239d628a0SDimitry Andric I->dropAllReferences();
803d8866befSDimitry Andric DeletedInstructions.emplace_back(I);
80439d628a0SDimitry Andric }
80539d628a0SDimitry Andric
80639d628a0SDimitry Andric /// Temporary store for deleted instructions. Instructions will be deleted
80739d628a0SDimitry Andric /// eventually when the BoUpSLP is destructed.
808d8866befSDimitry Andric SmallVector<unique_value, 8> DeletedInstructions;
80939d628a0SDimitry Andric
810f785676fSDimitry Andric /// A list of values that need to extracted out of the tree.
8117a7e6055SDimitry Andric /// This list holds pairs of (Internal Scalar : External User). External User
8127a7e6055SDimitry Andric /// can be nullptr, it means that this Internal Scalar will be used later,
8137a7e6055SDimitry Andric /// after vectorization.
814f785676fSDimitry Andric UserList ExternalUses;
815f785676fSDimitry Andric
81639d628a0SDimitry Andric /// Values used only by @llvm.assume calls.
81739d628a0SDimitry Andric SmallPtrSet<const Value *, 32> EphValues;
818f785676fSDimitry Andric
819f785676fSDimitry Andric /// Holds all of the instructions that we gathered.
820f785676fSDimitry Andric SetVector<Instruction *> GatherSeq;
8212cab237bSDimitry Andric
822f785676fSDimitry Andric /// A list of blocks that we are going to CSE.
82391bc56edSDimitry Andric SetVector<BasicBlock *> CSEBlocks;
824f785676fSDimitry Andric
82539d628a0SDimitry Andric /// Contains all scheduling relevant data for an instruction.
82639d628a0SDimitry Andric /// A ScheduleData either represents a single instruction or a member of an
82739d628a0SDimitry Andric /// instruction bundle (= a group of instructions which is combined into a
82839d628a0SDimitry Andric /// vector instruction).
82939d628a0SDimitry Andric struct ScheduleData {
83039d628a0SDimitry Andric // The initial value for the dependency counters. It means that the
83139d628a0SDimitry Andric // dependencies are not calculated yet.
83239d628a0SDimitry Andric enum { InvalidDeps = -1 };
83339d628a0SDimitry Andric
8342cab237bSDimitry Andric ScheduleData() = default;
83539d628a0SDimitry Andric
initllvm::slpvectorizer::BoUpSLP::ScheduleData8362cab237bSDimitry Andric void init(int BlockSchedulingRegionID, Value *OpVal) {
83739d628a0SDimitry Andric FirstInBundle = this;
83839d628a0SDimitry Andric NextInBundle = nullptr;
83939d628a0SDimitry Andric NextLoadStore = nullptr;
84039d628a0SDimitry Andric IsScheduled = false;
84139d628a0SDimitry Andric SchedulingRegionID = BlockSchedulingRegionID;
84239d628a0SDimitry Andric UnscheduledDepsInBundle = UnscheduledDeps;
84339d628a0SDimitry Andric clearDependencies();
8442cab237bSDimitry Andric OpValue = OpVal;
84591bc56edSDimitry Andric }
84691bc56edSDimitry Andric
84739d628a0SDimitry Andric /// Returns true if the dependency information has been calculated.
hasValidDependenciesllvm::slpvectorizer::BoUpSLP::ScheduleData84839d628a0SDimitry Andric bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
84939d628a0SDimitry Andric
85039d628a0SDimitry Andric /// Returns true for single instructions and for bundle representatives
85139d628a0SDimitry Andric /// (= the head of a bundle).
isSchedulingEntityllvm::slpvectorizer::BoUpSLP::ScheduleData85239d628a0SDimitry Andric bool isSchedulingEntity() const { return FirstInBundle == this; }
85339d628a0SDimitry Andric
85439d628a0SDimitry Andric /// Returns true if it represents an instruction bundle and not only a
85539d628a0SDimitry Andric /// single instruction.
isPartOfBundlellvm::slpvectorizer::BoUpSLP::ScheduleData85639d628a0SDimitry Andric bool isPartOfBundle() const {
85739d628a0SDimitry Andric return NextInBundle != nullptr || FirstInBundle != this;
85839d628a0SDimitry Andric }
85939d628a0SDimitry Andric
86039d628a0SDimitry Andric /// Returns true if it is ready for scheduling, i.e. it has no more
86139d628a0SDimitry Andric /// unscheduled depending instructions/bundles.
isReadyllvm::slpvectorizer::BoUpSLP::ScheduleData86239d628a0SDimitry Andric bool isReady() const {
86339d628a0SDimitry Andric assert(isSchedulingEntity() &&
86439d628a0SDimitry Andric "can't consider non-scheduling entity for ready list");
86539d628a0SDimitry Andric return UnscheduledDepsInBundle == 0 && !IsScheduled;
86639d628a0SDimitry Andric }
86739d628a0SDimitry Andric
86839d628a0SDimitry Andric /// Modifies the number of unscheduled dependencies, also updating it for
86939d628a0SDimitry Andric /// the whole bundle.
incrementUnscheduledDepsllvm::slpvectorizer::BoUpSLP::ScheduleData87039d628a0SDimitry Andric int incrementUnscheduledDeps(int Incr) {
87139d628a0SDimitry Andric UnscheduledDeps += Incr;
87239d628a0SDimitry Andric return FirstInBundle->UnscheduledDepsInBundle += Incr;
87339d628a0SDimitry Andric }
87439d628a0SDimitry Andric
87539d628a0SDimitry Andric /// Sets the number of unscheduled dependencies to the number of
87639d628a0SDimitry Andric /// dependencies.
resetUnscheduledDepsllvm::slpvectorizer::BoUpSLP::ScheduleData87739d628a0SDimitry Andric void resetUnscheduledDeps() {
87839d628a0SDimitry Andric incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
87939d628a0SDimitry Andric }
88039d628a0SDimitry Andric
88139d628a0SDimitry Andric /// Clears all dependency information.
clearDependenciesllvm::slpvectorizer::BoUpSLP::ScheduleData88239d628a0SDimitry Andric void clearDependencies() {
88339d628a0SDimitry Andric Dependencies = InvalidDeps;
88439d628a0SDimitry Andric resetUnscheduledDeps();
88539d628a0SDimitry Andric MemoryDependencies.clear();
88639d628a0SDimitry Andric }
88739d628a0SDimitry Andric
dumpllvm::slpvectorizer::BoUpSLP::ScheduleData88839d628a0SDimitry Andric void dump(raw_ostream &os) const {
88939d628a0SDimitry Andric if (!isSchedulingEntity()) {
89039d628a0SDimitry Andric os << "/ " << *Inst;
89139d628a0SDimitry Andric } else if (NextInBundle) {
89239d628a0SDimitry Andric os << '[' << *Inst;
89339d628a0SDimitry Andric ScheduleData *SD = NextInBundle;
89439d628a0SDimitry Andric while (SD) {
89539d628a0SDimitry Andric os << ';' << *SD->Inst;
89639d628a0SDimitry Andric SD = SD->NextInBundle;
89739d628a0SDimitry Andric }
89839d628a0SDimitry Andric os << ']';
89939d628a0SDimitry Andric } else {
90039d628a0SDimitry Andric os << *Inst;
90139d628a0SDimitry Andric }
90239d628a0SDimitry Andric }
90339d628a0SDimitry Andric
9042cab237bSDimitry Andric Instruction *Inst = nullptr;
90539d628a0SDimitry Andric
90639d628a0SDimitry Andric /// Points to the head in an instruction bundle (and always to this for
90739d628a0SDimitry Andric /// single instructions).
9082cab237bSDimitry Andric ScheduleData *FirstInBundle = nullptr;
90939d628a0SDimitry Andric
91039d628a0SDimitry Andric /// Single linked list of all instructions in a bundle. Null if it is a
91139d628a0SDimitry Andric /// single instruction.
9122cab237bSDimitry Andric ScheduleData *NextInBundle = nullptr;
91339d628a0SDimitry Andric
91439d628a0SDimitry Andric /// Single linked list of all memory instructions (e.g. load, store, call)
91539d628a0SDimitry Andric /// in the block - until the end of the scheduling region.
9162cab237bSDimitry Andric ScheduleData *NextLoadStore = nullptr;
91739d628a0SDimitry Andric
91839d628a0SDimitry Andric /// The dependent memory instructions.
91939d628a0SDimitry Andric /// This list is derived on demand in calculateDependencies().
92039d628a0SDimitry Andric SmallVector<ScheduleData *, 4> MemoryDependencies;
92139d628a0SDimitry Andric
92239d628a0SDimitry Andric /// This ScheduleData is in the current scheduling region if this matches
92339d628a0SDimitry Andric /// the current SchedulingRegionID of BlockScheduling.
9242cab237bSDimitry Andric int SchedulingRegionID = 0;
92539d628a0SDimitry Andric
92639d628a0SDimitry Andric /// Used for getting a "good" final ordering of instructions.
9272cab237bSDimitry Andric int SchedulingPriority = 0;
92839d628a0SDimitry Andric
92939d628a0SDimitry Andric /// The number of dependencies. Constitutes of the number of users of the
93039d628a0SDimitry Andric /// instruction plus the number of dependent memory instructions (if any).
93139d628a0SDimitry Andric /// This value is calculated on demand.
93239d628a0SDimitry Andric /// If InvalidDeps, the number of dependencies is not calculated yet.
9332cab237bSDimitry Andric int Dependencies = InvalidDeps;
93439d628a0SDimitry Andric
93539d628a0SDimitry Andric /// The number of dependencies minus the number of dependencies of scheduled
93639d628a0SDimitry Andric /// instructions. As soon as this is zero, the instruction/bundle gets ready
93739d628a0SDimitry Andric /// for scheduling.
93839d628a0SDimitry Andric /// Note that this is negative as long as Dependencies is not calculated.
9392cab237bSDimitry Andric int UnscheduledDeps = InvalidDeps;
94039d628a0SDimitry Andric
94139d628a0SDimitry Andric /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
94239d628a0SDimitry Andric /// single instructions.
9432cab237bSDimitry Andric int UnscheduledDepsInBundle = InvalidDeps;
94439d628a0SDimitry Andric
94539d628a0SDimitry Andric /// True if this instruction is scheduled (or considered as scheduled in the
94639d628a0SDimitry Andric /// dry-run).
9472cab237bSDimitry Andric bool IsScheduled = false;
9482cab237bSDimitry Andric
9492cab237bSDimitry Andric /// Opcode of the current instruction in the schedule data.
9502cab237bSDimitry Andric Value *OpValue = nullptr;
95139d628a0SDimitry Andric };
95239d628a0SDimitry Andric
95339d628a0SDimitry Andric #ifndef NDEBUG
operator <<(raw_ostream & os,const BoUpSLP::ScheduleData & SD)9543ca95b02SDimitry Andric friend inline raw_ostream &operator<<(raw_ostream &os,
9553ca95b02SDimitry Andric const BoUpSLP::ScheduleData &SD) {
9563ca95b02SDimitry Andric SD.dump(os);
9573ca95b02SDimitry Andric return os;
9583ca95b02SDimitry Andric }
95939d628a0SDimitry Andric #endif
9602cab237bSDimitry Andric
9617a7e6055SDimitry Andric friend struct GraphTraits<BoUpSLP *>;
9627a7e6055SDimitry Andric friend struct DOTGraphTraits<BoUpSLP *>;
96339d628a0SDimitry Andric
96439d628a0SDimitry Andric /// Contains all scheduling data for a basic block.
96539d628a0SDimitry Andric struct BlockScheduling {
BlockSchedulingllvm::slpvectorizer::BoUpSLP::BlockScheduling96639d628a0SDimitry Andric BlockScheduling(BasicBlock *BB)
9672cab237bSDimitry Andric : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
96839d628a0SDimitry Andric
clearllvm::slpvectorizer::BoUpSLP::BlockScheduling96939d628a0SDimitry Andric void clear() {
97039d628a0SDimitry Andric ReadyInsts.clear();
97139d628a0SDimitry Andric ScheduleStart = nullptr;
97239d628a0SDimitry Andric ScheduleEnd = nullptr;
97339d628a0SDimitry Andric FirstLoadStoreInRegion = nullptr;
97439d628a0SDimitry Andric LastLoadStoreInRegion = nullptr;
97539d628a0SDimitry Andric
9767d523365SDimitry Andric // Reduce the maximum schedule region size by the size of the
9777d523365SDimitry Andric // previous scheduling run.
9787d523365SDimitry Andric ScheduleRegionSizeLimit -= ScheduleRegionSize;
9797d523365SDimitry Andric if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
9807d523365SDimitry Andric ScheduleRegionSizeLimit = MinScheduleRegionSize;
9817d523365SDimitry Andric ScheduleRegionSize = 0;
9827d523365SDimitry Andric
98339d628a0SDimitry Andric // Make a new scheduling region, i.e. all existing ScheduleData is not
98439d628a0SDimitry Andric // in the new region yet.
98539d628a0SDimitry Andric ++SchedulingRegionID;
98639d628a0SDimitry Andric }
98739d628a0SDimitry Andric
getScheduleDatallvm::slpvectorizer::BoUpSLP::BlockScheduling98839d628a0SDimitry Andric ScheduleData *getScheduleData(Value *V) {
98939d628a0SDimitry Andric ScheduleData *SD = ScheduleDataMap[V];
99039d628a0SDimitry Andric if (SD && SD->SchedulingRegionID == SchedulingRegionID)
99139d628a0SDimitry Andric return SD;
99239d628a0SDimitry Andric return nullptr;
99339d628a0SDimitry Andric }
99439d628a0SDimitry Andric
getScheduleDatallvm::slpvectorizer::BoUpSLP::BlockScheduling9952cab237bSDimitry Andric ScheduleData *getScheduleData(Value *V, Value *Key) {
9962cab237bSDimitry Andric if (V == Key)
9972cab237bSDimitry Andric return getScheduleData(V);
9982cab237bSDimitry Andric auto I = ExtraScheduleDataMap.find(V);
9992cab237bSDimitry Andric if (I != ExtraScheduleDataMap.end()) {
10002cab237bSDimitry Andric ScheduleData *SD = I->second[Key];
10012cab237bSDimitry Andric if (SD && SD->SchedulingRegionID == SchedulingRegionID)
10022cab237bSDimitry Andric return SD;
10032cab237bSDimitry Andric }
10042cab237bSDimitry Andric return nullptr;
10052cab237bSDimitry Andric }
10062cab237bSDimitry Andric
isInSchedulingRegionllvm::slpvectorizer::BoUpSLP::BlockScheduling100739d628a0SDimitry Andric bool isInSchedulingRegion(ScheduleData *SD) {
100839d628a0SDimitry Andric return SD->SchedulingRegionID == SchedulingRegionID;
100939d628a0SDimitry Andric }
101039d628a0SDimitry Andric
101139d628a0SDimitry Andric /// Marks an instruction as scheduled and puts all dependent ready
101239d628a0SDimitry Andric /// instructions into the ready-list.
101339d628a0SDimitry Andric template <typename ReadyListType>
schedulellvm::slpvectorizer::BoUpSLP::BlockScheduling101439d628a0SDimitry Andric void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
101539d628a0SDimitry Andric SD->IsScheduled = true;
10164ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
101739d628a0SDimitry Andric
101839d628a0SDimitry Andric ScheduleData *BundleMember = SD;
101939d628a0SDimitry Andric while (BundleMember) {
10202cab237bSDimitry Andric if (BundleMember->Inst != BundleMember->OpValue) {
10212cab237bSDimitry Andric BundleMember = BundleMember->NextInBundle;
10222cab237bSDimitry Andric continue;
10232cab237bSDimitry Andric }
102439d628a0SDimitry Andric // Handle the def-use chain dependencies.
102539d628a0SDimitry Andric for (Use &U : BundleMember->Inst->operands()) {
10262cab237bSDimitry Andric auto *I = dyn_cast<Instruction>(U.get());
10272cab237bSDimitry Andric if (!I)
10282cab237bSDimitry Andric continue;
10292cab237bSDimitry Andric doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
103039d628a0SDimitry Andric if (OpDef && OpDef->hasValidDependencies() &&
103139d628a0SDimitry Andric OpDef->incrementUnscheduledDeps(-1) == 0) {
10322cab237bSDimitry Andric // There are no more unscheduled dependencies after
10332cab237bSDimitry Andric // decrementing, so we can put the dependent instruction
10342cab237bSDimitry Andric // into the ready list.
103539d628a0SDimitry Andric ScheduleData *DepBundle = OpDef->FirstInBundle;
103639d628a0SDimitry Andric assert(!DepBundle->IsScheduled &&
103739d628a0SDimitry Andric "already scheduled bundle gets ready");
103839d628a0SDimitry Andric ReadyList.insert(DepBundle);
10394ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
10402cab237bSDimitry Andric << "SLP: gets ready (def): " << *DepBundle << "\n");
104139d628a0SDimitry Andric }
10422cab237bSDimitry Andric });
104339d628a0SDimitry Andric }
104439d628a0SDimitry Andric // Handle the memory dependencies.
104539d628a0SDimitry Andric for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
104639d628a0SDimitry Andric if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
104739d628a0SDimitry Andric // There are no more unscheduled dependencies after decrementing,
104839d628a0SDimitry Andric // so we can put the dependent instruction into the ready list.
104939d628a0SDimitry Andric ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
105039d628a0SDimitry Andric assert(!DepBundle->IsScheduled &&
105139d628a0SDimitry Andric "already scheduled bundle gets ready");
105239d628a0SDimitry Andric ReadyList.insert(DepBundle);
10534ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
10544ba319b5SDimitry Andric << "SLP: gets ready (mem): " << *DepBundle << "\n");
105539d628a0SDimitry Andric }
105639d628a0SDimitry Andric }
105739d628a0SDimitry Andric BundleMember = BundleMember->NextInBundle;
105839d628a0SDimitry Andric }
105939d628a0SDimitry Andric }
106039d628a0SDimitry Andric
doForAllOpcodesllvm::slpvectorizer::BoUpSLP::BlockScheduling10612cab237bSDimitry Andric void doForAllOpcodes(Value *V,
10622cab237bSDimitry Andric function_ref<void(ScheduleData *SD)> Action) {
10632cab237bSDimitry Andric if (ScheduleData *SD = getScheduleData(V))
10642cab237bSDimitry Andric Action(SD);
10652cab237bSDimitry Andric auto I = ExtraScheduleDataMap.find(V);
10662cab237bSDimitry Andric if (I != ExtraScheduleDataMap.end())
10672cab237bSDimitry Andric for (auto &P : I->second)
10682cab237bSDimitry Andric if (P.second->SchedulingRegionID == SchedulingRegionID)
10692cab237bSDimitry Andric Action(P.second);
10702cab237bSDimitry Andric }
10712cab237bSDimitry Andric
107239d628a0SDimitry Andric /// Put all instructions into the ReadyList which are ready for scheduling.
107339d628a0SDimitry Andric template <typename ReadyListType>
initialFillReadyListllvm::slpvectorizer::BoUpSLP::BlockScheduling107439d628a0SDimitry Andric void initialFillReadyList(ReadyListType &ReadyList) {
107539d628a0SDimitry Andric for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
10762cab237bSDimitry Andric doForAllOpcodes(I, [&](ScheduleData *SD) {
107739d628a0SDimitry Andric if (SD->isSchedulingEntity() && SD->isReady()) {
107839d628a0SDimitry Andric ReadyList.insert(SD);
10794ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
10804ba319b5SDimitry Andric << "SLP: initially in ready list: " << *I << "\n");
108139d628a0SDimitry Andric }
10822cab237bSDimitry Andric });
108339d628a0SDimitry Andric }
108439d628a0SDimitry Andric }
108539d628a0SDimitry Andric
108639d628a0SDimitry Andric /// Checks if a bundle of instructions can be scheduled, i.e. has no
108739d628a0SDimitry Andric /// cyclic dependencies. This is only a dry-run, no instructions are
108839d628a0SDimitry Andric /// actually moved at this stage.
10894ba319b5SDimitry Andric bool tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
10904ba319b5SDimitry Andric const InstructionsState &S);
109139d628a0SDimitry Andric
109239d628a0SDimitry Andric /// Un-bundles a group of instructions.
1093c4394386SDimitry Andric void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
109439d628a0SDimitry Andric
10952cab237bSDimitry Andric /// Allocates schedule data chunk.
10962cab237bSDimitry Andric ScheduleData *allocateScheduleDataChunks();
10972cab237bSDimitry Andric
109839d628a0SDimitry Andric /// Extends the scheduling region so that V is inside the region.
10997d523365SDimitry Andric /// \returns true if the region size is within the limit.
11004ba319b5SDimitry Andric bool extendSchedulingRegion(Value *V, const InstructionsState &S);
110139d628a0SDimitry Andric
110239d628a0SDimitry Andric /// Initialize the ScheduleData structures for new instructions in the
110339d628a0SDimitry Andric /// scheduling region.
110439d628a0SDimitry Andric void initScheduleData(Instruction *FromI, Instruction *ToI,
110539d628a0SDimitry Andric ScheduleData *PrevLoadStore,
110639d628a0SDimitry Andric ScheduleData *NextLoadStore);
110739d628a0SDimitry Andric
110839d628a0SDimitry Andric /// Updates the dependency information of a bundle and of all instructions/
110939d628a0SDimitry Andric /// bundles which depend on the original bundle.
111039d628a0SDimitry Andric void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
111139d628a0SDimitry Andric BoUpSLP *SLP);
111239d628a0SDimitry Andric
111339d628a0SDimitry Andric /// Sets all instruction in the scheduling region to un-scheduled.
111439d628a0SDimitry Andric void resetSchedule();
111539d628a0SDimitry Andric
111639d628a0SDimitry Andric BasicBlock *BB;
111739d628a0SDimitry Andric
111839d628a0SDimitry Andric /// Simple memory allocation for ScheduleData.
111939d628a0SDimitry Andric std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
112039d628a0SDimitry Andric
112139d628a0SDimitry Andric /// The size of a ScheduleData array in ScheduleDataChunks.
112239d628a0SDimitry Andric int ChunkSize;
112339d628a0SDimitry Andric
112439d628a0SDimitry Andric /// The allocator position in the current chunk, which is the last entry
112539d628a0SDimitry Andric /// of ScheduleDataChunks.
112639d628a0SDimitry Andric int ChunkPos;
112739d628a0SDimitry Andric
112839d628a0SDimitry Andric /// Attaches ScheduleData to Instruction.
112939d628a0SDimitry Andric /// Note that the mapping survives during all vectorization iterations, i.e.
113039d628a0SDimitry Andric /// ScheduleData structures are recycled.
113139d628a0SDimitry Andric DenseMap<Value *, ScheduleData *> ScheduleDataMap;
113239d628a0SDimitry Andric
11332cab237bSDimitry Andric /// Attaches ScheduleData to Instruction with the leading key.
11342cab237bSDimitry Andric DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
11352cab237bSDimitry Andric ExtraScheduleDataMap;
11362cab237bSDimitry Andric
113739d628a0SDimitry Andric struct ReadyList : SmallVector<ScheduleData *, 8> {
insertllvm::slpvectorizer::BoUpSLP::BlockScheduling::ReadyList113839d628a0SDimitry Andric void insert(ScheduleData *SD) { push_back(SD); }
113939d628a0SDimitry Andric };
114039d628a0SDimitry Andric
114139d628a0SDimitry Andric /// The ready-list for scheduling (only used for the dry-run).
114239d628a0SDimitry Andric ReadyList ReadyInsts;
114339d628a0SDimitry Andric
114439d628a0SDimitry Andric /// The first instruction of the scheduling region.
11452cab237bSDimitry Andric Instruction *ScheduleStart = nullptr;
114639d628a0SDimitry Andric
114739d628a0SDimitry Andric /// The first instruction _after_ the scheduling region.
11482cab237bSDimitry Andric Instruction *ScheduleEnd = nullptr;
114939d628a0SDimitry Andric
115039d628a0SDimitry Andric /// The first memory accessing instruction in the scheduling region
115139d628a0SDimitry Andric /// (can be null).
11522cab237bSDimitry Andric ScheduleData *FirstLoadStoreInRegion = nullptr;
115339d628a0SDimitry Andric
115439d628a0SDimitry Andric /// The last memory accessing instruction in the scheduling region
115539d628a0SDimitry Andric /// (can be null).
11562cab237bSDimitry Andric ScheduleData *LastLoadStoreInRegion = nullptr;
115739d628a0SDimitry Andric
11587d523365SDimitry Andric /// The current size of the scheduling region.
11592cab237bSDimitry Andric int ScheduleRegionSize = 0;
11607d523365SDimitry Andric
11617d523365SDimitry Andric /// The maximum size allowed for the scheduling region.
11622cab237bSDimitry Andric int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
11637d523365SDimitry Andric
116439d628a0SDimitry Andric /// The ID of the scheduling region. For a new vectorization iteration this
116539d628a0SDimitry Andric /// is incremented which "removes" all ScheduleData from the region.
11662cab237bSDimitry Andric // Make sure that the initial SchedulingRegionID is greater than the
11672cab237bSDimitry Andric // initial SchedulingRegionID in ScheduleData (which is 0).
11682cab237bSDimitry Andric int SchedulingRegionID = 1;
116939d628a0SDimitry Andric };
117039d628a0SDimitry Andric
117139d628a0SDimitry Andric /// Attaches the BlockScheduling structures to basic blocks.
117239d628a0SDimitry Andric MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
117339d628a0SDimitry Andric
117439d628a0SDimitry Andric /// Performs the "real" scheduling. Done before vectorization is actually
117539d628a0SDimitry Andric /// performed in a basic block.
117639d628a0SDimitry Andric void scheduleBlock(BlockScheduling *BS);
117739d628a0SDimitry Andric
117891bc56edSDimitry Andric /// List of users to ignore during scheduling and that don't need extracting.
117991bc56edSDimitry Andric ArrayRef<Value *> UserIgnoreList;
1180f785676fSDimitry Andric
11814ba319b5SDimitry Andric using OrdersType = SmallVector<unsigned, 4>;
11824ba319b5SDimitry Andric /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
11834ba319b5SDimitry Andric /// sorted SmallVectors of unsigned.
11844ba319b5SDimitry Andric struct OrdersTypeDenseMapInfo {
getEmptyKeyllvm::slpvectorizer::BoUpSLP::OrdersTypeDenseMapInfo11854ba319b5SDimitry Andric static OrdersType getEmptyKey() {
11864ba319b5SDimitry Andric OrdersType V;
11874ba319b5SDimitry Andric V.push_back(~1U);
11884ba319b5SDimitry Andric return V;
11894ba319b5SDimitry Andric }
119039d628a0SDimitry Andric
getTombstoneKeyllvm::slpvectorizer::BoUpSLP::OrdersTypeDenseMapInfo11914ba319b5SDimitry Andric static OrdersType getTombstoneKey() {
11924ba319b5SDimitry Andric OrdersType V;
11934ba319b5SDimitry Andric V.push_back(~2U);
11944ba319b5SDimitry Andric return V;
11954ba319b5SDimitry Andric }
11964ba319b5SDimitry Andric
getHashValuellvm::slpvectorizer::BoUpSLP::OrdersTypeDenseMapInfo11974ba319b5SDimitry Andric static unsigned getHashValue(const OrdersType &V) {
11984ba319b5SDimitry Andric return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
11994ba319b5SDimitry Andric }
12004ba319b5SDimitry Andric
isEqualllvm::slpvectorizer::BoUpSLP::OrdersTypeDenseMapInfo12014ba319b5SDimitry Andric static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
12024ba319b5SDimitry Andric return LHS == RHS;
12034ba319b5SDimitry Andric }
12044ba319b5SDimitry Andric };
12054ba319b5SDimitry Andric
12064ba319b5SDimitry Andric /// Contains orders of operations along with the number of bundles that have
12074ba319b5SDimitry Andric /// operations in this order. It stores only those orders that require
12084ba319b5SDimitry Andric /// reordering, if reordering is not required it is counted using \a
12094ba319b5SDimitry Andric /// NumOpsWantToKeepOriginalOrder.
12104ba319b5SDimitry Andric DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
12114ba319b5SDimitry Andric /// Number of bundles that do not require reordering.
12124ba319b5SDimitry Andric unsigned NumOpsWantToKeepOriginalOrder = 0;
121339d628a0SDimitry Andric
1214f785676fSDimitry Andric // Analysis and block reference.
1215f785676fSDimitry Andric Function *F;
1216f785676fSDimitry Andric ScalarEvolution *SE;
1217f785676fSDimitry Andric TargetTransformInfo *TTI;
121891bc56edSDimitry Andric TargetLibraryInfo *TLI;
1219f785676fSDimitry Andric AliasAnalysis *AA;
1220f785676fSDimitry Andric LoopInfo *LI;
1221f785676fSDimitry Andric DominatorTree *DT;
12223ca95b02SDimitry Andric AssumptionCache *AC;
12233ca95b02SDimitry Andric DemandedBits *DB;
12243ca95b02SDimitry Andric const DataLayout *DL;
12255517e702SDimitry Andric OptimizationRemarkEmitter *ORE;
12265517e702SDimitry Andric
12273ca95b02SDimitry Andric unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
12283ca95b02SDimitry Andric unsigned MinVecRegSize; // Set by cl::opt (default: 128).
12292cab237bSDimitry Andric
1230f785676fSDimitry Andric /// Instruction builder to construct the vectorized tree.
1231f785676fSDimitry Andric IRBuilder<> Builder;
12323ca95b02SDimitry Andric
12333ca95b02SDimitry Andric /// A map of scalar integer values to the smallest bit width with which they
1234d88c1a5aSDimitry Andric /// can legally be represented. The values map to (width, signed) pairs,
1235d88c1a5aSDimitry Andric /// where "width" indicates the minimum bit width and "signed" is True if the
1236d88c1a5aSDimitry Andric /// value must be signed-extended, rather than zero-extended, back to its
1237d88c1a5aSDimitry Andric /// original width.
1238d88c1a5aSDimitry Andric MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
1239f785676fSDimitry Andric };
12402cab237bSDimitry Andric
12413ca95b02SDimitry Andric } // end namespace slpvectorizer
124239d628a0SDimitry Andric
12437a7e6055SDimitry Andric template <> struct GraphTraits<BoUpSLP *> {
12442cab237bSDimitry Andric using TreeEntry = BoUpSLP::TreeEntry;
12457a7e6055SDimitry Andric
12467a7e6055SDimitry Andric /// NodeRef has to be a pointer per the GraphWriter.
12472cab237bSDimitry Andric using NodeRef = TreeEntry *;
12487a7e6055SDimitry Andric
12494ba319b5SDimitry Andric /// Add the VectorizableTree to the index iterator to be able to return
12507a7e6055SDimitry Andric /// TreeEntry pointers.
12517a7e6055SDimitry Andric struct ChildIteratorType
12527a7e6055SDimitry Andric : public iterator_adaptor_base<ChildIteratorType,
12537a7e6055SDimitry Andric SmallVector<int, 1>::iterator> {
12547a7e6055SDimitry Andric std::vector<TreeEntry> &VectorizableTree;
12557a7e6055SDimitry Andric
ChildIteratorTypellvm::GraphTraits::ChildIteratorType12567a7e6055SDimitry Andric ChildIteratorType(SmallVector<int, 1>::iterator W,
12577a7e6055SDimitry Andric std::vector<TreeEntry> &VT)
12587a7e6055SDimitry Andric : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
12597a7e6055SDimitry Andric
operator *llvm::GraphTraits::ChildIteratorType12607a7e6055SDimitry Andric NodeRef operator*() { return &VectorizableTree[*I]; }
12617a7e6055SDimitry Andric };
12627a7e6055SDimitry Andric
getEntryNodellvm::GraphTraits12637a7e6055SDimitry Andric static NodeRef getEntryNode(BoUpSLP &R) { return &R.VectorizableTree[0]; }
12647a7e6055SDimitry Andric
child_beginllvm::GraphTraits12657a7e6055SDimitry Andric static ChildIteratorType child_begin(NodeRef N) {
12667a7e6055SDimitry Andric return {N->UserTreeIndices.begin(), N->Container};
12677a7e6055SDimitry Andric }
12682cab237bSDimitry Andric
child_endllvm::GraphTraits12697a7e6055SDimitry Andric static ChildIteratorType child_end(NodeRef N) {
12707a7e6055SDimitry Andric return {N->UserTreeIndices.end(), N->Container};
12717a7e6055SDimitry Andric }
12727a7e6055SDimitry Andric
12737a7e6055SDimitry Andric /// For the node iterator we just need to turn the TreeEntry iterator into a
12747a7e6055SDimitry Andric /// TreeEntry* iterator so that it dereferences to NodeRef.
12752cab237bSDimitry Andric using nodes_iterator = pointer_iterator<std::vector<TreeEntry>::iterator>;
12767a7e6055SDimitry Andric
nodes_beginllvm::GraphTraits12777a7e6055SDimitry Andric static nodes_iterator nodes_begin(BoUpSLP *R) {
12787a7e6055SDimitry Andric return nodes_iterator(R->VectorizableTree.begin());
12797a7e6055SDimitry Andric }
12802cab237bSDimitry Andric
nodes_endllvm::GraphTraits12817a7e6055SDimitry Andric static nodes_iterator nodes_end(BoUpSLP *R) {
12827a7e6055SDimitry Andric return nodes_iterator(R->VectorizableTree.end());
12837a7e6055SDimitry Andric }
12847a7e6055SDimitry Andric
sizellvm::GraphTraits12857a7e6055SDimitry Andric static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
12867a7e6055SDimitry Andric };
12877a7e6055SDimitry Andric
12887a7e6055SDimitry Andric template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
12892cab237bSDimitry Andric using TreeEntry = BoUpSLP::TreeEntry;
12907a7e6055SDimitry Andric
DOTGraphTraitsllvm::DOTGraphTraits12917a7e6055SDimitry Andric DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
12927a7e6055SDimitry Andric
getNodeLabelllvm::DOTGraphTraits12937a7e6055SDimitry Andric std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
12947a7e6055SDimitry Andric std::string Str;
12957a7e6055SDimitry Andric raw_string_ostream OS(Str);
12967a7e6055SDimitry Andric if (isSplat(Entry->Scalars)) {
12977a7e6055SDimitry Andric OS << "<splat> " << *Entry->Scalars[0];
12987a7e6055SDimitry Andric return Str;
12997a7e6055SDimitry Andric }
13007a7e6055SDimitry Andric for (auto V : Entry->Scalars) {
13017a7e6055SDimitry Andric OS << *V;
13027a7e6055SDimitry Andric if (std::any_of(
13037a7e6055SDimitry Andric R->ExternalUses.begin(), R->ExternalUses.end(),
13047a7e6055SDimitry Andric [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
13057a7e6055SDimitry Andric OS << " <extract>";
13067a7e6055SDimitry Andric OS << "\n";
13077a7e6055SDimitry Andric }
13087a7e6055SDimitry Andric return Str;
13097a7e6055SDimitry Andric }
13107a7e6055SDimitry Andric
getNodeAttributesllvm::DOTGraphTraits13117a7e6055SDimitry Andric static std::string getNodeAttributes(const TreeEntry *Entry,
13127a7e6055SDimitry Andric const BoUpSLP *) {
13137a7e6055SDimitry Andric if (Entry->NeedToGather)
13147a7e6055SDimitry Andric return "color=red";
13157a7e6055SDimitry Andric return "";
13167a7e6055SDimitry Andric }
13177a7e6055SDimitry Andric };
13187a7e6055SDimitry Andric
13197a7e6055SDimitry Andric } // end namespace llvm
13207a7e6055SDimitry Andric
buildTree(ArrayRef<Value * > Roots,ArrayRef<Value * > UserIgnoreLst)132191bc56edSDimitry Andric void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
132291bc56edSDimitry Andric ArrayRef<Value *> UserIgnoreLst) {
13237a7e6055SDimitry Andric ExtraValueToDebugLocsMap ExternallyUsedValues;
13247a7e6055SDimitry Andric buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
13257a7e6055SDimitry Andric }
13262cab237bSDimitry Andric
buildTree(ArrayRef<Value * > Roots,ExtraValueToDebugLocsMap & ExternallyUsedValues,ArrayRef<Value * > UserIgnoreLst)13277a7e6055SDimitry Andric void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
13287a7e6055SDimitry Andric ExtraValueToDebugLocsMap &ExternallyUsedValues,
13297a7e6055SDimitry Andric ArrayRef<Value *> UserIgnoreLst) {
1330f785676fSDimitry Andric deleteTree();
133191bc56edSDimitry Andric UserIgnoreList = UserIgnoreLst;
1332d88c1a5aSDimitry Andric if (!allSameType(Roots))
1333f785676fSDimitry Andric return;
13347a7e6055SDimitry Andric buildTree_rec(Roots, 0, -1);
1335f785676fSDimitry Andric
1336f785676fSDimitry Andric // Collect the values that we need to extract from the tree.
13373ca95b02SDimitry Andric for (TreeEntry &EIdx : VectorizableTree) {
13383ca95b02SDimitry Andric TreeEntry *Entry = &EIdx;
1339f785676fSDimitry Andric
1340f785676fSDimitry Andric // No need to handle users of gathered values.
1341f785676fSDimitry Andric if (Entry->NeedToGather)
1342f785676fSDimitry Andric continue;
1343f785676fSDimitry Andric
1344a580b014SDimitry Andric // For each lane:
1345a580b014SDimitry Andric for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
1346a580b014SDimitry Andric Value *Scalar = Entry->Scalars[Lane];
13474ba319b5SDimitry Andric int FoundLane = Lane;
13484ba319b5SDimitry Andric if (!Entry->ReuseShuffleIndices.empty()) {
13494ba319b5SDimitry Andric FoundLane =
13504ba319b5SDimitry Andric std::distance(Entry->ReuseShuffleIndices.begin(),
13514ba319b5SDimitry Andric llvm::find(Entry->ReuseShuffleIndices, FoundLane));
13524ba319b5SDimitry Andric }
1353a580b014SDimitry Andric
13547a7e6055SDimitry Andric // Check if the scalar is externally used as an extra arg.
13557a7e6055SDimitry Andric auto ExtI = ExternallyUsedValues.find(Scalar);
13567a7e6055SDimitry Andric if (ExtI != ExternallyUsedValues.end()) {
13574ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
13584ba319b5SDimitry Andric << Lane << " from " << *Scalar << ".\n");
13594ba319b5SDimitry Andric ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
13607a7e6055SDimitry Andric }
136191bc56edSDimitry Andric for (User *U : Scalar->users()) {
13624ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
1363f785676fSDimitry Andric
136491bc56edSDimitry Andric Instruction *UserInst = dyn_cast<Instruction>(U);
1365f785676fSDimitry Andric if (!UserInst)
1366f785676fSDimitry Andric continue;
1367f785676fSDimitry Andric
136839d628a0SDimitry Andric // Skip in-tree scalars that become vectors
1369a580b014SDimitry Andric if (TreeEntry *UseEntry = getTreeEntry(U)) {
137039d628a0SDimitry Andric Value *UseScalar = UseEntry->Scalars[0];
137139d628a0SDimitry Andric // Some in-tree scalars will remain as scalar in vectorized
137239d628a0SDimitry Andric // instructions. If that is the case, the one in Lane 0 will
137339d628a0SDimitry Andric // be used.
137439d628a0SDimitry Andric if (UseScalar != U ||
137539d628a0SDimitry Andric !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
13764ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
137739d628a0SDimitry Andric << ".\n");
1378a580b014SDimitry Andric assert(!UseEntry->NeedToGather && "Bad state");
137939d628a0SDimitry Andric continue;
138039d628a0SDimitry Andric }
138139d628a0SDimitry Andric }
138239d628a0SDimitry Andric
138391bc56edSDimitry Andric // Ignore users in the user ignore list.
1384d88c1a5aSDimitry Andric if (is_contained(UserIgnoreList, UserInst))
1385f785676fSDimitry Andric continue;
1386f785676fSDimitry Andric
13874ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
13884ba319b5SDimitry Andric << Lane << " from " << *Scalar << ".\n");
13894ba319b5SDimitry Andric ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
1390f785676fSDimitry Andric }
1391f785676fSDimitry Andric }
1392f785676fSDimitry Andric }
1393f785676fSDimitry Andric }
1394f785676fSDimitry Andric
buildTree_rec(ArrayRef<Value * > VL,unsigned Depth,int UserTreeIdx)13957a7e6055SDimitry Andric void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
1396da09e106SDimitry Andric int UserTreeIdx) {
1397d88c1a5aSDimitry Andric assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
1398f785676fSDimitry Andric
13992cab237bSDimitry Andric InstructionsState S = getSameOpcode(VL);
1400f785676fSDimitry Andric if (Depth == RecursionMaxDepth) {
14014ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
1402da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1403f785676fSDimitry Andric return;
1404f785676fSDimitry Andric }
1405f785676fSDimitry Andric
1406f785676fSDimitry Andric // Don't handle vectors.
14072cab237bSDimitry Andric if (S.OpValue->getType()->isVectorTy()) {
14084ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
1409da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1410f785676fSDimitry Andric return;
1411f785676fSDimitry Andric }
1412f785676fSDimitry Andric
14132cab237bSDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
1414f785676fSDimitry Andric if (SI->getValueOperand()->getType()->isVectorTy()) {
14154ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
1416da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1417f785676fSDimitry Andric return;
1418f785676fSDimitry Andric }
1419f785676fSDimitry Andric
1420f785676fSDimitry Andric // If all of the operands are identical or constant we have a simple solution.
14214ba319b5SDimitry Andric if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
14224ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
1423da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1424f785676fSDimitry Andric return;
1425f785676fSDimitry Andric }
1426f785676fSDimitry Andric
1427f785676fSDimitry Andric // We now know that this is a vector of instructions of the same type from
1428f785676fSDimitry Andric // the same block.
1429f785676fSDimitry Andric
143039d628a0SDimitry Andric // Don't vectorize ephemeral values.
143139d628a0SDimitry Andric for (unsigned i = 0, e = VL.size(); i != e; ++i) {
143239d628a0SDimitry Andric if (EphValues.count(VL[i])) {
14334ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *VL[i]
14344ba319b5SDimitry Andric << ") is ephemeral.\n");
1435da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
143639d628a0SDimitry Andric return;
143739d628a0SDimitry Andric }
143839d628a0SDimitry Andric }
143939d628a0SDimitry Andric
1440f785676fSDimitry Andric // Check if this is a duplicate of another entry.
14412cab237bSDimitry Andric if (TreeEntry *E = getTreeEntry(S.OpValue)) {
14424ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
14434ba319b5SDimitry Andric if (!E->isSame(VL)) {
14444ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
1445da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1446f785676fSDimitry Andric return;
1447f785676fSDimitry Andric }
14487a7e6055SDimitry Andric // Record the reuse of the tree node. FIXME, currently this is only used to
14497a7e6055SDimitry Andric // properly draw the graph rather than for the actual vectorization.
14507a7e6055SDimitry Andric E->UserTreeIndices.push_back(UserTreeIdx);
14514ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
14524ba319b5SDimitry Andric << ".\n");
1453f785676fSDimitry Andric return;
1454f785676fSDimitry Andric }
1455f785676fSDimitry Andric
1456f785676fSDimitry Andric // Check that none of the instructions in the bundle are already in the tree.
1457f785676fSDimitry Andric for (unsigned i = 0, e = VL.size(); i != e; ++i) {
14582cab237bSDimitry Andric auto *I = dyn_cast<Instruction>(VL[i]);
14592cab237bSDimitry Andric if (!I)
14602cab237bSDimitry Andric continue;
14612cab237bSDimitry Andric if (getTreeEntry(I)) {
14624ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *VL[i]
14634ba319b5SDimitry Andric << ") is already in tree.\n");
1464da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1465f785676fSDimitry Andric return;
1466f785676fSDimitry Andric }
1467f785676fSDimitry Andric }
1468f785676fSDimitry Andric
14692cab237bSDimitry Andric // If any of the scalars is marked as a value that needs to stay scalar, then
147039d628a0SDimitry Andric // we need to gather the scalars.
1471*b5893f02SDimitry Andric // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
1472f785676fSDimitry Andric for (unsigned i = 0, e = VL.size(); i != e; ++i) {
1473*b5893f02SDimitry Andric if (MustGather.count(VL[i]) || is_contained(UserIgnoreList, VL[i])) {
14744ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
1475da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1476f785676fSDimitry Andric return;
1477f785676fSDimitry Andric }
1478f785676fSDimitry Andric }
1479f785676fSDimitry Andric
1480f785676fSDimitry Andric // Check that all of the users of the scalars that we want to vectorize are
1481f785676fSDimitry Andric // schedulable.
14822cab237bSDimitry Andric auto *VL0 = cast<Instruction>(S.OpValue);
1483b40b48b8SDimitry Andric BasicBlock *BB = VL0->getParent();
1484f785676fSDimitry Andric
148539d628a0SDimitry Andric if (!DT->isReachableFromEntry(BB)) {
148639d628a0SDimitry Andric // Don't go into unreachable blocks. They may contain instructions with
148739d628a0SDimitry Andric // dependency cycles which confuse the final scheduling.
14884ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
1489da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1490f785676fSDimitry Andric return;
1491f785676fSDimitry Andric }
1492f785676fSDimitry Andric
14932cab237bSDimitry Andric // Check that every instruction appears once in this bundle.
14944ba319b5SDimitry Andric SmallVector<unsigned, 4> ReuseShuffleIndicies;
14954ba319b5SDimitry Andric SmallVector<Value *, 4> UniqueValues;
14964ba319b5SDimitry Andric DenseMap<Value *, unsigned> UniquePositions;
14974ba319b5SDimitry Andric for (Value *V : VL) {
14984ba319b5SDimitry Andric auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
14994ba319b5SDimitry Andric ReuseShuffleIndicies.emplace_back(Res.first->second);
15004ba319b5SDimitry Andric if (Res.second)
15014ba319b5SDimitry Andric UniqueValues.emplace_back(V);
15024ba319b5SDimitry Andric }
15034ba319b5SDimitry Andric if (UniqueValues.size() == VL.size()) {
15044ba319b5SDimitry Andric ReuseShuffleIndicies.clear();
15054ba319b5SDimitry Andric } else {
15064ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
15074ba319b5SDimitry Andric if (UniqueValues.size() <= 1 || !llvm::isPowerOf2_32(UniqueValues.size())) {
15084ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
1509da09e106SDimitry Andric newTreeEntry(VL, false, UserTreeIdx);
1510f785676fSDimitry Andric return;
1511f785676fSDimitry Andric }
15124ba319b5SDimitry Andric VL = UniqueValues;
15134ba319b5SDimitry Andric }
1514f785676fSDimitry Andric
151539d628a0SDimitry Andric auto &BSRef = BlocksSchedules[BB];
15162cab237bSDimitry Andric if (!BSRef)
151739d628a0SDimitry Andric BSRef = llvm::make_unique<BlockScheduling>(BB);
15182cab237bSDimitry Andric
151939d628a0SDimitry Andric BlockScheduling &BS = *BSRef.get();
152039d628a0SDimitry Andric
15214ba319b5SDimitry Andric if (!BS.tryScheduleBundle(VL, this, S)) {
15224ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
15232cab237bSDimitry Andric assert((!BS.getScheduleData(VL0) ||
15242cab237bSDimitry Andric !BS.getScheduleData(VL0)->isPartOfBundle()) &&
15257d523365SDimitry Andric "tryScheduleBundle should cancelScheduling on failure");
15264ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1527f785676fSDimitry Andric return;
1528f785676fSDimitry Andric }
15294ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
1530f785676fSDimitry Andric
15314ba319b5SDimitry Andric unsigned ShuffleOrOp = S.isAltShuffle() ?
15324ba319b5SDimitry Andric (unsigned) Instruction::ShuffleVector : S.getOpcode();
15332cab237bSDimitry Andric switch (ShuffleOrOp) {
1534f785676fSDimitry Andric case Instruction::PHI: {
1535f785676fSDimitry Andric PHINode *PH = dyn_cast<PHINode>(VL0);
1536f785676fSDimitry Andric
1537f785676fSDimitry Andric // Check for terminator values (e.g. invoke).
1538f785676fSDimitry Andric for (unsigned j = 0; j < VL.size(); ++j)
1539f785676fSDimitry Andric for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1540*b5893f02SDimitry Andric Instruction *Term = dyn_cast<Instruction>(
1541*b5893f02SDimitry Andric cast<PHINode>(VL[j])->getIncomingValueForBlock(
1542*b5893f02SDimitry Andric PH->getIncomingBlock(i)));
1543*b5893f02SDimitry Andric if (Term && Term->isTerminator()) {
1544*b5893f02SDimitry Andric LLVM_DEBUG(dbgs()
1545*b5893f02SDimitry Andric << "SLP: Need to swizzle PHINodes (terminator use).\n");
1546c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
15474ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1548f785676fSDimitry Andric return;
1549f785676fSDimitry Andric }
1550f785676fSDimitry Andric }
1551f785676fSDimitry Andric
15524ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
15534ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
1554f785676fSDimitry Andric
1555f785676fSDimitry Andric for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
1556f785676fSDimitry Andric ValueList Operands;
1557f785676fSDimitry Andric // Prepare the operand vector.
15583ca95b02SDimitry Andric for (Value *j : VL)
15593ca95b02SDimitry Andric Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
156091bc56edSDimitry Andric PH->getIncomingBlock(i)));
1561f785676fSDimitry Andric
1562da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1563f785676fSDimitry Andric }
1564f785676fSDimitry Andric return;
1565f785676fSDimitry Andric }
15663ca95b02SDimitry Andric case Instruction::ExtractValue:
1567f785676fSDimitry Andric case Instruction::ExtractElement: {
15684ba319b5SDimitry Andric OrdersType CurrentOrder;
15694ba319b5SDimitry Andric bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
1570f785676fSDimitry Andric if (Reuse) {
15714ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
15724ba319b5SDimitry Andric ++NumOpsWantToKeepOriginalOrder;
15734ba319b5SDimitry Andric newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx,
15744ba319b5SDimitry Andric ReuseShuffleIndicies);
15754ba319b5SDimitry Andric return;
1576f785676fSDimitry Andric }
15774ba319b5SDimitry Andric if (!CurrentOrder.empty()) {
15784ba319b5SDimitry Andric LLVM_DEBUG({
15794ba319b5SDimitry Andric dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
15804ba319b5SDimitry Andric "with order";
15814ba319b5SDimitry Andric for (unsigned Idx : CurrentOrder)
15824ba319b5SDimitry Andric dbgs() << " " << Idx;
15834ba319b5SDimitry Andric dbgs() << "\n";
15844ba319b5SDimitry Andric });
15854ba319b5SDimitry Andric // Insert new order with initial value 0, if it does not exist,
15864ba319b5SDimitry Andric // otherwise return the iterator to the existing one.
15874ba319b5SDimitry Andric auto StoredCurrentOrderAndNum =
15884ba319b5SDimitry Andric NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
15894ba319b5SDimitry Andric ++StoredCurrentOrderAndNum->getSecond();
15904ba319b5SDimitry Andric newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx, ReuseShuffleIndicies,
15914ba319b5SDimitry Andric StoredCurrentOrderAndNum->getFirst());
15924ba319b5SDimitry Andric return;
15934ba319b5SDimitry Andric }
15944ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
15954ba319b5SDimitry Andric newTreeEntry(VL, /*Vectorized=*/false, UserTreeIdx, ReuseShuffleIndicies);
15964ba319b5SDimitry Andric BS.cancelScheduling(VL, VL0);
1597f785676fSDimitry Andric return;
1598f785676fSDimitry Andric }
1599f785676fSDimitry Andric case Instruction::Load: {
16007d523365SDimitry Andric // Check that a vectorized load would load the same memory as a scalar
16012cab237bSDimitry Andric // load. For example, we don't want to vectorize loads that are smaller
16022cab237bSDimitry Andric // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
16032cab237bSDimitry Andric // treats loading/storing it as an i8 struct. If we vectorize loads/stores
16042cab237bSDimitry Andric // from such a struct, we read/write packed bits disagreeing with the
16057d523365SDimitry Andric // unvectorized version.
16062cab237bSDimitry Andric Type *ScalarTy = VL0->getType();
16077d523365SDimitry Andric
16083ca95b02SDimitry Andric if (DL->getTypeSizeInBits(ScalarTy) !=
16093ca95b02SDimitry Andric DL->getTypeAllocSizeInBits(ScalarTy)) {
1610c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
16114ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
16124ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
16137d523365SDimitry Andric return;
16147d523365SDimitry Andric }
1615d88c1a5aSDimitry Andric
1616d88c1a5aSDimitry Andric // Make sure all loads in the bundle are simple - we can't vectorize
1617d88c1a5aSDimitry Andric // atomic or volatile loads.
16184ba319b5SDimitry Andric SmallVector<Value *, 4> PointerOps(VL.size());
16194ba319b5SDimitry Andric auto POIter = PointerOps.begin();
16204ba319b5SDimitry Andric for (Value *V : VL) {
16214ba319b5SDimitry Andric auto *L = cast<LoadInst>(V);
162239d628a0SDimitry Andric if (!L->isSimple()) {
1623c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
16244ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
16254ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
162639d628a0SDimitry Andric return;
162739d628a0SDimitry Andric }
16284ba319b5SDimitry Andric *POIter = L->getPointerOperand();
16294ba319b5SDimitry Andric ++POIter;
1630d88c1a5aSDimitry Andric }
16317d523365SDimitry Andric
16324ba319b5SDimitry Andric OrdersType CurrentOrder;
16334ba319b5SDimitry Andric // Check the order of pointer operands.
16344ba319b5SDimitry Andric if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
16354ba319b5SDimitry Andric Value *Ptr0;
16364ba319b5SDimitry Andric Value *PtrN;
16374ba319b5SDimitry Andric if (CurrentOrder.empty()) {
16384ba319b5SDimitry Andric Ptr0 = PointerOps.front();
16394ba319b5SDimitry Andric PtrN = PointerOps.back();
1640d88c1a5aSDimitry Andric } else {
16414ba319b5SDimitry Andric Ptr0 = PointerOps[CurrentOrder.front()];
16424ba319b5SDimitry Andric PtrN = PointerOps[CurrentOrder.back()];
1643f785676fSDimitry Andric }
16444ba319b5SDimitry Andric const SCEV *Scev0 = SE->getSCEV(Ptr0);
16454ba319b5SDimitry Andric const SCEV *ScevN = SE->getSCEV(PtrN);
16464ba319b5SDimitry Andric const auto *Diff =
16474ba319b5SDimitry Andric dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
16484ba319b5SDimitry Andric uint64_t Size = DL->getTypeAllocSize(ScalarTy);
16494ba319b5SDimitry Andric // Check that the sorted loads are consecutive.
16504ba319b5SDimitry Andric if (Diff && Diff->getAPInt().getZExtValue() == (VL.size() - 1) * Size) {
16514ba319b5SDimitry Andric if (CurrentOrder.empty()) {
16524ba319b5SDimitry Andric // Original loads are consecutive and does not require reordering.
16534ba319b5SDimitry Andric ++NumOpsWantToKeepOriginalOrder;
16544ba319b5SDimitry Andric newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx,
16554ba319b5SDimitry Andric ReuseShuffleIndicies);
16564ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
16574ba319b5SDimitry Andric } else {
16584ba319b5SDimitry Andric // Need to reorder.
16594ba319b5SDimitry Andric auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
16604ba319b5SDimitry Andric ++I->getSecond();
16614ba319b5SDimitry Andric newTreeEntry(VL, /*Vectorized=*/true, UserTreeIdx,
16624ba319b5SDimitry Andric ReuseShuffleIndicies, I->getFirst());
16634ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
1664f785676fSDimitry Andric }
1665f785676fSDimitry Andric return;
1666f785676fSDimitry Andric }
1667d88c1a5aSDimitry Andric }
1668d88c1a5aSDimitry Andric
16694ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
1670da09e106SDimitry Andric BS.cancelScheduling(VL, VL0);
16714ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
1672d88c1a5aSDimitry Andric return;
1673d88c1a5aSDimitry Andric }
1674f785676fSDimitry Andric case Instruction::ZExt:
1675f785676fSDimitry Andric case Instruction::SExt:
1676f785676fSDimitry Andric case Instruction::FPToUI:
1677f785676fSDimitry Andric case Instruction::FPToSI:
1678f785676fSDimitry Andric case Instruction::FPExt:
1679f785676fSDimitry Andric case Instruction::PtrToInt:
1680f785676fSDimitry Andric case Instruction::IntToPtr:
1681f785676fSDimitry Andric case Instruction::SIToFP:
1682f785676fSDimitry Andric case Instruction::UIToFP:
1683f785676fSDimitry Andric case Instruction::Trunc:
1684f785676fSDimitry Andric case Instruction::FPTrunc:
1685f785676fSDimitry Andric case Instruction::BitCast: {
1686f785676fSDimitry Andric Type *SrcTy = VL0->getOperand(0)->getType();
1687f785676fSDimitry Andric for (unsigned i = 0; i < VL.size(); ++i) {
1688f785676fSDimitry Andric Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
168944f7b0dcSDimitry Andric if (Ty != SrcTy || !isValidElementType(Ty)) {
1690c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
16914ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
16924ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
16934ba319b5SDimitry Andric << "SLP: Gathering casts with different src types.\n");
1694f785676fSDimitry Andric return;
1695f785676fSDimitry Andric }
1696f785676fSDimitry Andric }
16974ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
16984ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
1699f785676fSDimitry Andric
1700f785676fSDimitry Andric for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1701f785676fSDimitry Andric ValueList Operands;
1702f785676fSDimitry Andric // Prepare the operand vector.
17033ca95b02SDimitry Andric for (Value *j : VL)
17043ca95b02SDimitry Andric Operands.push_back(cast<Instruction>(j)->getOperand(i));
1705f785676fSDimitry Andric
1706da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1707f785676fSDimitry Andric }
1708f785676fSDimitry Andric return;
1709f785676fSDimitry Andric }
1710f785676fSDimitry Andric case Instruction::ICmp:
1711f785676fSDimitry Andric case Instruction::FCmp: {
1712f785676fSDimitry Andric // Check that all of the compares have the same predicate.
1713ff0cc061SDimitry Andric CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
17142cab237bSDimitry Andric Type *ComparedTy = VL0->getOperand(0)->getType();
1715f785676fSDimitry Andric for (unsigned i = 1, e = VL.size(); i < e; ++i) {
1716f785676fSDimitry Andric CmpInst *Cmp = cast<CmpInst>(VL[i]);
1717f785676fSDimitry Andric if (Cmp->getPredicate() != P0 ||
1718f785676fSDimitry Andric Cmp->getOperand(0)->getType() != ComparedTy) {
1719c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
17204ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
17214ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
17224ba319b5SDimitry Andric << "SLP: Gathering cmp with different predicate.\n");
1723f785676fSDimitry Andric return;
1724f785676fSDimitry Andric }
1725f785676fSDimitry Andric }
1726f785676fSDimitry Andric
17274ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
17284ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
1729f785676fSDimitry Andric
1730f785676fSDimitry Andric for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1731f785676fSDimitry Andric ValueList Operands;
1732f785676fSDimitry Andric // Prepare the operand vector.
17333ca95b02SDimitry Andric for (Value *j : VL)
17343ca95b02SDimitry Andric Operands.push_back(cast<Instruction>(j)->getOperand(i));
1735f785676fSDimitry Andric
1736da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1737f785676fSDimitry Andric }
1738f785676fSDimitry Andric return;
1739f785676fSDimitry Andric }
1740f785676fSDimitry Andric case Instruction::Select:
1741f785676fSDimitry Andric case Instruction::Add:
1742f785676fSDimitry Andric case Instruction::FAdd:
1743f785676fSDimitry Andric case Instruction::Sub:
1744f785676fSDimitry Andric case Instruction::FSub:
1745f785676fSDimitry Andric case Instruction::Mul:
1746f785676fSDimitry Andric case Instruction::FMul:
1747f785676fSDimitry Andric case Instruction::UDiv:
1748f785676fSDimitry Andric case Instruction::SDiv:
1749f785676fSDimitry Andric case Instruction::FDiv:
1750f785676fSDimitry Andric case Instruction::URem:
1751f785676fSDimitry Andric case Instruction::SRem:
1752f785676fSDimitry Andric case Instruction::FRem:
1753f785676fSDimitry Andric case Instruction::Shl:
1754f785676fSDimitry Andric case Instruction::LShr:
1755f785676fSDimitry Andric case Instruction::AShr:
1756f785676fSDimitry Andric case Instruction::And:
1757f785676fSDimitry Andric case Instruction::Or:
17582cab237bSDimitry Andric case Instruction::Xor:
17594ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
17604ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of bin op.\n");
1761f785676fSDimitry Andric
1762f785676fSDimitry Andric // Sort operands of the instructions so that each side is more likely to
1763f785676fSDimitry Andric // have the same opcode.
1764f785676fSDimitry Andric if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
1765f785676fSDimitry Andric ValueList Left, Right;
17664ba319b5SDimitry Andric reorderInputsAccordingToOpcode(S.getOpcode(), VL, Left, Right);
17677a7e6055SDimitry Andric buildTree_rec(Left, Depth + 1, UserTreeIdx);
1768da09e106SDimitry Andric buildTree_rec(Right, Depth + 1, UserTreeIdx);
1769f785676fSDimitry Andric return;
1770f785676fSDimitry Andric }
1771f785676fSDimitry Andric
1772f785676fSDimitry Andric for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
1773f785676fSDimitry Andric ValueList Operands;
1774f785676fSDimitry Andric // Prepare the operand vector.
17753ca95b02SDimitry Andric for (Value *j : VL)
17763ca95b02SDimitry Andric Operands.push_back(cast<Instruction>(j)->getOperand(i));
1777f785676fSDimitry Andric
1778da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1779f785676fSDimitry Andric }
1780f785676fSDimitry Andric return;
17812cab237bSDimitry Andric
178291bc56edSDimitry Andric case Instruction::GetElementPtr: {
178391bc56edSDimitry Andric // We don't combine GEPs with complicated (nested) indexing.
178491bc56edSDimitry Andric for (unsigned j = 0; j < VL.size(); ++j) {
178591bc56edSDimitry Andric if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
17864ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
1787c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
17884ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
178991bc56edSDimitry Andric return;
179091bc56edSDimitry Andric }
179191bc56edSDimitry Andric }
179291bc56edSDimitry Andric
179391bc56edSDimitry Andric // We can't combine several GEPs into one vector if they operate on
179491bc56edSDimitry Andric // different types.
17952cab237bSDimitry Andric Type *Ty0 = VL0->getOperand(0)->getType();
179691bc56edSDimitry Andric for (unsigned j = 0; j < VL.size(); ++j) {
179791bc56edSDimitry Andric Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
179891bc56edSDimitry Andric if (Ty0 != CurTy) {
17994ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
18004ba319b5SDimitry Andric << "SLP: not-vectorizable GEP (different types).\n");
1801c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18024ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
180391bc56edSDimitry Andric return;
180491bc56edSDimitry Andric }
180591bc56edSDimitry Andric }
180691bc56edSDimitry Andric
180791bc56edSDimitry Andric // We don't combine GEPs with non-constant indexes.
180891bc56edSDimitry Andric for (unsigned j = 0; j < VL.size(); ++j) {
180991bc56edSDimitry Andric auto Op = cast<Instruction>(VL[j])->getOperand(1);
181091bc56edSDimitry Andric if (!isa<ConstantInt>(Op)) {
18114ba319b5SDimitry Andric LLVM_DEBUG(dbgs()
18124ba319b5SDimitry Andric << "SLP: not-vectorizable GEP (non-constant indexes).\n");
1813c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18144ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
181591bc56edSDimitry Andric return;
181691bc56edSDimitry Andric }
181791bc56edSDimitry Andric }
181891bc56edSDimitry Andric
18194ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
18204ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
182191bc56edSDimitry Andric for (unsigned i = 0, e = 2; i < e; ++i) {
182291bc56edSDimitry Andric ValueList Operands;
182391bc56edSDimitry Andric // Prepare the operand vector.
18243ca95b02SDimitry Andric for (Value *j : VL)
18253ca95b02SDimitry Andric Operands.push_back(cast<Instruction>(j)->getOperand(i));
182691bc56edSDimitry Andric
1827da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
182891bc56edSDimitry Andric }
182991bc56edSDimitry Andric return;
183091bc56edSDimitry Andric }
1831f785676fSDimitry Andric case Instruction::Store: {
1832f785676fSDimitry Andric // Check if the stores are consecutive or of we need to swizzle them.
1833f785676fSDimitry Andric for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
18343ca95b02SDimitry Andric if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
1835c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18364ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
18374ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
1838f785676fSDimitry Andric return;
1839f785676fSDimitry Andric }
1840f785676fSDimitry Andric
18414ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
18424ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
1843f785676fSDimitry Andric
1844f785676fSDimitry Andric ValueList Operands;
18453ca95b02SDimitry Andric for (Value *j : VL)
18463ca95b02SDimitry Andric Operands.push_back(cast<Instruction>(j)->getOperand(0));
1847f785676fSDimitry Andric
18487a7e6055SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
1849f785676fSDimitry Andric return;
1850f785676fSDimitry Andric }
185191bc56edSDimitry Andric case Instruction::Call: {
185291bc56edSDimitry Andric // Check if the calls are all to the same vectorizable intrinsic.
18532cab237bSDimitry Andric CallInst *CI = cast<CallInst>(VL0);
185491bc56edSDimitry Andric // Check if this is an Intrinsic call or something that can be
185591bc56edSDimitry Andric // represented by an intrinsic call
18563ca95b02SDimitry Andric Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
185791bc56edSDimitry Andric if (!isTriviallyVectorizable(ID)) {
1858c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18594ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
18604ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
186191bc56edSDimitry Andric return;
186291bc56edSDimitry Andric }
186391bc56edSDimitry Andric Function *Int = CI->getCalledFunction();
186491bc56edSDimitry Andric Value *A1I = nullptr;
186591bc56edSDimitry Andric if (hasVectorInstrinsicScalarOpd(ID, 1))
186691bc56edSDimitry Andric A1I = CI->getArgOperand(1);
186791bc56edSDimitry Andric for (unsigned i = 1, e = VL.size(); i != e; ++i) {
186891bc56edSDimitry Andric CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
186991bc56edSDimitry Andric if (!CI2 || CI2->getCalledFunction() != Int ||
18703ca95b02SDimitry Andric getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
18713ca95b02SDimitry Andric !CI->hasIdenticalOperandBundleSchema(*CI2)) {
1872c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18734ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
18744ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
187591bc56edSDimitry Andric << "\n");
187691bc56edSDimitry Andric return;
187791bc56edSDimitry Andric }
187891bc56edSDimitry Andric // ctlz,cttz and powi are special intrinsics whose second argument
187991bc56edSDimitry Andric // should be same in order for them to be vectorized.
188091bc56edSDimitry Andric if (hasVectorInstrinsicScalarOpd(ID, 1)) {
188191bc56edSDimitry Andric Value *A1J = CI2->getArgOperand(1);
188291bc56edSDimitry Andric if (A1I != A1J) {
1883c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18844ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
18854ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
18864ba319b5SDimitry Andric << " argument " << A1I << "!=" << A1J << "\n");
188791bc56edSDimitry Andric return;
188891bc56edSDimitry Andric }
188991bc56edSDimitry Andric }
18903ca95b02SDimitry Andric // Verify that the bundle operands are identical between the two calls.
18913ca95b02SDimitry Andric if (CI->hasOperandBundles() &&
18923ca95b02SDimitry Andric !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
18933ca95b02SDimitry Andric CI->op_begin() + CI->getBundleOperandsEndIndex(),
18943ca95b02SDimitry Andric CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
1895c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
18964ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
18974ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
18984ba319b5SDimitry Andric << *CI << "!=" << *VL[i] << '\n');
18993ca95b02SDimitry Andric return;
19003ca95b02SDimitry Andric }
190191bc56edSDimitry Andric }
190291bc56edSDimitry Andric
19034ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
190491bc56edSDimitry Andric for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
190591bc56edSDimitry Andric ValueList Operands;
190691bc56edSDimitry Andric // Prepare the operand vector.
19073ca95b02SDimitry Andric for (Value *j : VL) {
19083ca95b02SDimitry Andric CallInst *CI2 = dyn_cast<CallInst>(j);
190991bc56edSDimitry Andric Operands.push_back(CI2->getArgOperand(i));
191091bc56edSDimitry Andric }
1911da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
191291bc56edSDimitry Andric }
191391bc56edSDimitry Andric return;
191491bc56edSDimitry Andric }
19152cab237bSDimitry Andric case Instruction::ShuffleVector:
191691bc56edSDimitry Andric // If this is not an alternate sequence of opcode like add-sub
191791bc56edSDimitry Andric // then do not vectorize this instruction.
19184ba319b5SDimitry Andric if (!S.isAltShuffle()) {
1919c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
19204ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
19214ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
192291bc56edSDimitry Andric return;
192391bc56edSDimitry Andric }
19244ba319b5SDimitry Andric newTreeEntry(VL, true, UserTreeIdx, ReuseShuffleIndicies);
19254ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
1926ff0cc061SDimitry Andric
1927ff0cc061SDimitry Andric // Reorder operands if reordering would enable vectorization.
1928ff0cc061SDimitry Andric if (isa<BinaryOperator>(VL0)) {
1929ff0cc061SDimitry Andric ValueList Left, Right;
19304ba319b5SDimitry Andric reorderAltShuffleOperands(S, VL, Left, Right);
19317a7e6055SDimitry Andric buildTree_rec(Left, Depth + 1, UserTreeIdx);
1932da09e106SDimitry Andric buildTree_rec(Right, Depth + 1, UserTreeIdx);
1933ff0cc061SDimitry Andric return;
1934ff0cc061SDimitry Andric }
1935ff0cc061SDimitry Andric
193691bc56edSDimitry Andric for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
193791bc56edSDimitry Andric ValueList Operands;
193891bc56edSDimitry Andric // Prepare the operand vector.
19393ca95b02SDimitry Andric for (Value *j : VL)
19403ca95b02SDimitry Andric Operands.push_back(cast<Instruction>(j)->getOperand(i));
194191bc56edSDimitry Andric
1942da09e106SDimitry Andric buildTree_rec(Operands, Depth + 1, UserTreeIdx);
194391bc56edSDimitry Andric }
194491bc56edSDimitry Andric return;
19452cab237bSDimitry Andric
1946f785676fSDimitry Andric default:
1947c4394386SDimitry Andric BS.cancelScheduling(VL, VL0);
19484ba319b5SDimitry Andric newTreeEntry(VL, false, UserTreeIdx, ReuseShuffleIndicies);
19494ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
1950f785676fSDimitry Andric return;
1951f785676fSDimitry Andric }
1952f785676fSDimitry Andric }
1953f785676fSDimitry Andric
canMapToVector(Type * T,const DataLayout & DL) const19543ca95b02SDimitry Andric unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
19553ca95b02SDimitry Andric unsigned N;
19563ca95b02SDimitry Andric Type *EltTy;
19573ca95b02SDimitry Andric auto *ST = dyn_cast<StructType>(T);
19583ca95b02SDimitry Andric if (ST) {
19593ca95b02SDimitry Andric N = ST->getNumElements();
19603ca95b02SDimitry Andric EltTy = *ST->element_begin();
19613ca95b02SDimitry Andric } else {
19623ca95b02SDimitry Andric N = cast<ArrayType>(T)->getNumElements();
19633ca95b02SDimitry Andric EltTy = cast<ArrayType>(T)->getElementType();
19643ca95b02SDimitry Andric }
19653ca95b02SDimitry Andric if (!isValidElementType(EltTy))
19663ca95b02SDimitry Andric return 0;
19673ca95b02SDimitry Andric uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
19683ca95b02SDimitry Andric if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
19693ca95b02SDimitry Andric return 0;
19703ca95b02SDimitry Andric if (ST) {
19713ca95b02SDimitry Andric // Check that struct is homogeneous.
19723ca95b02SDimitry Andric for (const auto *Ty : ST->elements())
19733ca95b02SDimitry Andric if (Ty != EltTy)
19743ca95b02SDimitry Andric return 0;
19753ca95b02SDimitry Andric }
19763ca95b02SDimitry Andric return N;
19773ca95b02SDimitry Andric }
19783ca95b02SDimitry Andric
canReuseExtract(ArrayRef<Value * > VL,Value * OpValue,SmallVectorImpl<unsigned> & CurrentOrder) const19794ba319b5SDimitry Andric bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
19804ba319b5SDimitry Andric SmallVectorImpl<unsigned> &CurrentOrder) const {
19812cab237bSDimitry Andric Instruction *E0 = cast<Instruction>(OpValue);
19822cab237bSDimitry Andric assert(E0->getOpcode() == Instruction::ExtractElement ||
19832cab237bSDimitry Andric E0->getOpcode() == Instruction::ExtractValue);
19844ba319b5SDimitry Andric assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
19853ca95b02SDimitry Andric // Check if all of the extracts come from the same vector and from the
19863ca95b02SDimitry Andric // correct offset.
19873ca95b02SDimitry Andric Value *Vec = E0->getOperand(0);
19883ca95b02SDimitry Andric
19894ba319b5SDimitry Andric CurrentOrder.clear();
19904ba319b5SDimitry Andric
19913ca95b02SDimitry Andric // We have to extract from a vector/aggregate with the same number of elements.
19923ca95b02SDimitry Andric unsigned NElts;
19932cab237bSDimitry Andric if (E0->getOpcode() == Instruction::ExtractValue) {
19943ca95b02SDimitry Andric const DataLayout &DL = E0->getModule()->getDataLayout();
19953ca95b02SDimitry Andric NElts = canMapToVector(Vec->getType(), DL);
19963ca95b02SDimitry Andric if (!NElts)
19973ca95b02SDimitry Andric return false;
19983ca95b02SDimitry Andric // Check if load can be rewritten as load of vector.
19993ca95b02SDimitry Andric LoadInst *LI = dyn_cast<LoadInst>(Vec);
20003ca95b02SDimitry Andric if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
20013ca95b02SDimitry Andric return false;
20023ca95b02SDimitry Andric } else {
20033ca95b02SDimitry Andric NElts = Vec->getType()->getVectorNumElements();
20043ca95b02SDimitry Andric }
20053ca95b02SDimitry Andric
20063ca95b02SDimitry Andric if (NElts != VL.size())
20073ca95b02SDimitry Andric return false;
20083ca95b02SDimitry Andric
20093ca95b02SDimitry Andric // Check that all of the indices extract from the correct offset.
20104ba319b5SDimitry Andric bool ShouldKeepOrder = true;
20114ba319b5SDimitry Andric unsigned E = VL.size();
20124ba319b5SDimitry Andric // Assign to all items the initial value E + 1 so we can check if the extract
20134ba319b5SDimitry Andric // instruction index was used already.
20144ba319b5SDimitry Andric // Also, later we can check that all the indices are used and we have a
20154ba319b5SDimitry Andric // consecutive access in the extract instructions, by checking that no
20164ba319b5SDimitry Andric // element of CurrentOrder still has value E + 1.
20174ba319b5SDimitry Andric CurrentOrder.assign(E, E + 1);
20184ba319b5SDimitry Andric unsigned I = 0;
20194ba319b5SDimitry Andric for (; I < E; ++I) {
20204ba319b5SDimitry Andric auto *Inst = cast<Instruction>(VL[I]);
20212cab237bSDimitry Andric if (Inst->getOperand(0) != Vec)
20224ba319b5SDimitry Andric break;
20234ba319b5SDimitry Andric Optional<unsigned> Idx = getExtractIndex(Inst);
20244ba319b5SDimitry Andric if (!Idx)
20254ba319b5SDimitry Andric break;
20264ba319b5SDimitry Andric const unsigned ExtIdx = *Idx;
20274ba319b5SDimitry Andric if (ExtIdx != I) {
20284ba319b5SDimitry Andric if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
20294ba319b5SDimitry Andric break;
20304ba319b5SDimitry Andric ShouldKeepOrder = false;
20314ba319b5SDimitry Andric CurrentOrder[ExtIdx] = I;
20324ba319b5SDimitry Andric } else {
20334ba319b5SDimitry Andric if (CurrentOrder[I] != E + 1)
20344ba319b5SDimitry Andric break;
20354ba319b5SDimitry Andric CurrentOrder[I] = I;
20364ba319b5SDimitry Andric }
20374ba319b5SDimitry Andric }
20384ba319b5SDimitry Andric if (I < E) {
20394ba319b5SDimitry Andric CurrentOrder.clear();
20403ca95b02SDimitry Andric return false;
20413ca95b02SDimitry Andric }
20423ca95b02SDimitry Andric
20434ba319b5SDimitry Andric return ShouldKeepOrder;
20443ca95b02SDimitry Andric }
20453ca95b02SDimitry Andric
areAllUsersVectorized(Instruction * I) const20462cab237bSDimitry Andric bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
20472cab237bSDimitry Andric return I->hasOneUse() ||
20482cab237bSDimitry Andric std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
20492cab237bSDimitry Andric return ScalarToTreeEntry.count(U) > 0;
20502cab237bSDimitry Andric });
20512cab237bSDimitry Andric }
20522cab237bSDimitry Andric
getEntryCost(TreeEntry * E)2053f785676fSDimitry Andric int BoUpSLP::getEntryCost(TreeEntry *E) {
2054f785676fSDimitry Andric ArrayRef<Value*> VL = E->Scalars;
2055f785676fSDimitry Andric
2056f785676fSDimitry Andric Type *ScalarTy = VL[0]->getType();
2057f785676fSDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2058f785676fSDimitry Andric ScalarTy = SI->getValueOperand()->getType();
20597a7e6055SDimitry Andric else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
20607a7e6055SDimitry Andric ScalarTy = CI->getOperand(0)->getType();
2061f785676fSDimitry Andric VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2062f785676fSDimitry Andric
20633ca95b02SDimitry Andric // If we have computed a smaller type for the expression, update VecTy so
20643ca95b02SDimitry Andric // that the costs will be accurate.
20653ca95b02SDimitry Andric if (MinBWs.count(VL[0]))
2066d88c1a5aSDimitry Andric VecTy = VectorType::get(
2067d88c1a5aSDimitry Andric IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
20683ca95b02SDimitry Andric
20694ba319b5SDimitry Andric unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
20704ba319b5SDimitry Andric bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
20714ba319b5SDimitry Andric int ReuseShuffleCost = 0;
20724ba319b5SDimitry Andric if (NeedToShuffleReuses) {
20734ba319b5SDimitry Andric ReuseShuffleCost =
20744ba319b5SDimitry Andric TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
20754ba319b5SDimitry Andric }
2076f785676fSDimitry Andric if (E->NeedToGather) {
2077f785676fSDimitry Andric if (allConstant(VL))
2078f785676fSDimitry Andric return 0;
2079f785676fSDimitry Andric if (isSplat(VL)) {
20804ba319b5SDimitry Andric return ReuseShuffleCost +
20814ba319b5SDimitry Andric TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
2082f785676fSDimitry Andric }
20834ba319b5SDimitry Andric if (getSameOpcode(VL).getOpcode() == Instruction::ExtractElement &&
20844ba319b5SDimitry Andric allSameType(VL) && allSameBlock(VL)) {
20852cab237bSDimitry Andric Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
20862cab237bSDimitry Andric if (ShuffleKind.hasValue()) {
20872cab237bSDimitry Andric int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
20882cab237bSDimitry Andric for (auto *V : VL) {
20892cab237bSDimitry Andric // If all users of instruction are going to be vectorized and this
20902cab237bSDimitry Andric // instruction itself is not going to be vectorized, consider this
20912cab237bSDimitry Andric // instruction as dead and remove its cost from the final cost of the
20922cab237bSDimitry Andric // vectorized tree.
20932cab237bSDimitry Andric if (areAllUsersVectorized(cast<Instruction>(V)) &&
20942cab237bSDimitry Andric !ScalarToTreeEntry.count(V)) {
20952cab237bSDimitry Andric auto *IO = cast<ConstantInt>(
20962cab237bSDimitry Andric cast<ExtractElementInst>(V)->getIndexOperand());
20972cab237bSDimitry Andric Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
20982cab237bSDimitry Andric IO->getZExtValue());
20992cab237bSDimitry Andric }
21002cab237bSDimitry Andric }
21014ba319b5SDimitry Andric return ReuseShuffleCost + Cost;
21022cab237bSDimitry Andric }
21032cab237bSDimitry Andric }
21044ba319b5SDimitry Andric return ReuseShuffleCost + getGatherCost(VL);
2105f785676fSDimitry Andric }
21062cab237bSDimitry Andric InstructionsState S = getSameOpcode(VL);
21074ba319b5SDimitry Andric assert(S.getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
21082cab237bSDimitry Andric Instruction *VL0 = cast<Instruction>(S.OpValue);
21094ba319b5SDimitry Andric unsigned ShuffleOrOp = S.isAltShuffle() ?
21104ba319b5SDimitry Andric (unsigned) Instruction::ShuffleVector : S.getOpcode();
21112cab237bSDimitry Andric switch (ShuffleOrOp) {
21122cab237bSDimitry Andric case Instruction::PHI:
2113f785676fSDimitry Andric return 0;
21142cab237bSDimitry Andric
21153ca95b02SDimitry Andric case Instruction::ExtractValue:
21162cab237bSDimitry Andric case Instruction::ExtractElement:
21174ba319b5SDimitry Andric if (NeedToShuffleReuses) {
21184ba319b5SDimitry Andric unsigned Idx = 0;
21194ba319b5SDimitry Andric for (unsigned I : E->ReuseShuffleIndices) {
21204ba319b5SDimitry Andric if (ShuffleOrOp == Instruction::ExtractElement) {
21214ba319b5SDimitry Andric auto *IO = cast<ConstantInt>(
21224ba319b5SDimitry Andric cast<ExtractElementInst>(VL[I])->getIndexOperand());
21234ba319b5SDimitry Andric Idx = IO->getZExtValue();
21244ba319b5SDimitry Andric ReuseShuffleCost -= TTI->getVectorInstrCost(
21254ba319b5SDimitry Andric Instruction::ExtractElement, VecTy, Idx);
21264ba319b5SDimitry Andric } else {
21274ba319b5SDimitry Andric ReuseShuffleCost -= TTI->getVectorInstrCost(
21284ba319b5SDimitry Andric Instruction::ExtractElement, VecTy, Idx);
21294ba319b5SDimitry Andric ++Idx;
21304ba319b5SDimitry Andric }
21314ba319b5SDimitry Andric }
21324ba319b5SDimitry Andric Idx = ReuseShuffleNumbers;
21334ba319b5SDimitry Andric for (Value *V : VL) {
21344ba319b5SDimitry Andric if (ShuffleOrOp == Instruction::ExtractElement) {
21354ba319b5SDimitry Andric auto *IO = cast<ConstantInt>(
21364ba319b5SDimitry Andric cast<ExtractElementInst>(V)->getIndexOperand());
21374ba319b5SDimitry Andric Idx = IO->getZExtValue();
21384ba319b5SDimitry Andric } else {
21394ba319b5SDimitry Andric --Idx;
21404ba319b5SDimitry Andric }
21414ba319b5SDimitry Andric ReuseShuffleCost +=
21424ba319b5SDimitry Andric TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
21434ba319b5SDimitry Andric }
21444ba319b5SDimitry Andric }
21454ba319b5SDimitry Andric if (!E->NeedToGather) {
21464ba319b5SDimitry Andric int DeadCost = ReuseShuffleCost;
21474ba319b5SDimitry Andric if (!E->ReorderIndices.empty()) {
21484ba319b5SDimitry Andric // TODO: Merge this shuffle with the ReuseShuffleCost.
21494ba319b5SDimitry Andric DeadCost += TTI->getShuffleCost(
21504ba319b5SDimitry Andric TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
21514ba319b5SDimitry Andric }
215291bc56edSDimitry Andric for (unsigned i = 0, e = VL.size(); i < e; ++i) {
21533ca95b02SDimitry Andric Instruction *E = cast<Instruction>(VL[i]);
21547a7e6055SDimitry Andric // If all users are going to be vectorized, instruction can be
21557a7e6055SDimitry Andric // considered as dead.
21567a7e6055SDimitry Andric // The same, if have only one user, it will be vectorized for sure.
21574ba319b5SDimitry Andric if (areAllUsersVectorized(E)) {
215891bc56edSDimitry Andric // Take credit for instruction that will become dead.
21594ba319b5SDimitry Andric if (E->hasOneUse()) {
21604ba319b5SDimitry Andric Instruction *Ext = E->user_back();
21614ba319b5SDimitry Andric if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
21624ba319b5SDimitry Andric all_of(Ext->users(),
21634ba319b5SDimitry Andric [](User *U) { return isa<GetElementPtrInst>(U); })) {
21644ba319b5SDimitry Andric // Use getExtractWithExtendCost() to calculate the cost of
21654ba319b5SDimitry Andric // extractelement/ext pair.
21664ba319b5SDimitry Andric DeadCost -= TTI->getExtractWithExtendCost(
21674ba319b5SDimitry Andric Ext->getOpcode(), Ext->getType(), VecTy, i);
2168*b5893f02SDimitry Andric // Add back the cost of s|zext which is subtracted separately.
21694ba319b5SDimitry Andric DeadCost += TTI->getCastInstrCost(
21704ba319b5SDimitry Andric Ext->getOpcode(), Ext->getType(), E->getType(), Ext);
21714ba319b5SDimitry Andric continue;
21724ba319b5SDimitry Andric }
21734ba319b5SDimitry Andric }
21744ba319b5SDimitry Andric DeadCost -=
217591bc56edSDimitry Andric TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
217691bc56edSDimitry Andric }
217791bc56edSDimitry Andric }
21784ba319b5SDimitry Andric return DeadCost;
21794ba319b5SDimitry Andric }
21804ba319b5SDimitry Andric return ReuseShuffleCost + getGatherCost(VL);
21812cab237bSDimitry Andric
2182f785676fSDimitry Andric case Instruction::ZExt:
2183f785676fSDimitry Andric case Instruction::SExt:
2184f785676fSDimitry Andric case Instruction::FPToUI:
2185f785676fSDimitry Andric case Instruction::FPToSI:
2186f785676fSDimitry Andric case Instruction::FPExt:
2187f785676fSDimitry Andric case Instruction::PtrToInt:
2188f785676fSDimitry Andric case Instruction::IntToPtr:
2189f785676fSDimitry Andric case Instruction::SIToFP:
2190f785676fSDimitry Andric case Instruction::UIToFP:
2191f785676fSDimitry Andric case Instruction::Trunc:
2192f785676fSDimitry Andric case Instruction::FPTrunc:
2193f785676fSDimitry Andric case Instruction::BitCast: {
2194f785676fSDimitry Andric Type *SrcTy = VL0->getOperand(0)->getType();
21954ba319b5SDimitry Andric int ScalarEltCost =
21964ba319b5SDimitry Andric TTI->getCastInstrCost(S.getOpcode(), ScalarTy, SrcTy, VL0);
21974ba319b5SDimitry Andric if (NeedToShuffleReuses) {
21984ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
21994ba319b5SDimitry Andric }
2200f785676fSDimitry Andric
2201f785676fSDimitry Andric // Calculate the cost of this instruction.
22024ba319b5SDimitry Andric int ScalarCost = VL.size() * ScalarEltCost;
2203f785676fSDimitry Andric
2204f785676fSDimitry Andric VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
22054ba319b5SDimitry Andric int VecCost = 0;
22064ba319b5SDimitry Andric // Check if the values are candidates to demote.
22074ba319b5SDimitry Andric if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
22084ba319b5SDimitry Andric VecCost = ReuseShuffleCost +
22094ba319b5SDimitry Andric TTI->getCastInstrCost(S.getOpcode(), VecTy, SrcVecTy, VL0);
22104ba319b5SDimitry Andric }
2211f785676fSDimitry Andric return VecCost - ScalarCost;
2212f785676fSDimitry Andric }
2213f785676fSDimitry Andric case Instruction::FCmp:
2214f785676fSDimitry Andric case Instruction::ICmp:
22153ca95b02SDimitry Andric case Instruction::Select: {
22163ca95b02SDimitry Andric // Calculate the cost of this instruction.
22174ba319b5SDimitry Andric int ScalarEltCost = TTI->getCmpSelInstrCost(S.getOpcode(), ScalarTy,
22184ba319b5SDimitry Andric Builder.getInt1Ty(), VL0);
22194ba319b5SDimitry Andric if (NeedToShuffleReuses) {
22204ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
22214ba319b5SDimitry Andric }
22223ca95b02SDimitry Andric VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
22234ba319b5SDimitry Andric int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
22244ba319b5SDimitry Andric int VecCost = TTI->getCmpSelInstrCost(S.getOpcode(), VecTy, MaskTy, VL0);
22254ba319b5SDimitry Andric return ReuseShuffleCost + VecCost - ScalarCost;
22263ca95b02SDimitry Andric }
2227f785676fSDimitry Andric case Instruction::Add:
2228f785676fSDimitry Andric case Instruction::FAdd:
2229f785676fSDimitry Andric case Instruction::Sub:
2230f785676fSDimitry Andric case Instruction::FSub:
2231f785676fSDimitry Andric case Instruction::Mul:
2232f785676fSDimitry Andric case Instruction::FMul:
2233f785676fSDimitry Andric case Instruction::UDiv:
2234f785676fSDimitry Andric case Instruction::SDiv:
2235f785676fSDimitry Andric case Instruction::FDiv:
2236f785676fSDimitry Andric case Instruction::URem:
2237f785676fSDimitry Andric case Instruction::SRem:
2238f785676fSDimitry Andric case Instruction::FRem:
2239f785676fSDimitry Andric case Instruction::Shl:
2240f785676fSDimitry Andric case Instruction::LShr:
2241f785676fSDimitry Andric case Instruction::AShr:
2242f785676fSDimitry Andric case Instruction::And:
2243f785676fSDimitry Andric case Instruction::Or:
2244f785676fSDimitry Andric case Instruction::Xor: {
2245f785676fSDimitry Andric // Certain instructions can be cheaper to vectorize if they have a
2246f785676fSDimitry Andric // constant second vector operand.
2247f785676fSDimitry Andric TargetTransformInfo::OperandValueKind Op1VK =
2248f785676fSDimitry Andric TargetTransformInfo::OK_AnyValue;
2249f785676fSDimitry Andric TargetTransformInfo::OperandValueKind Op2VK =
2250f785676fSDimitry Andric TargetTransformInfo::OK_UniformConstantValue;
225139d628a0SDimitry Andric TargetTransformInfo::OperandValueProperties Op1VP =
225239d628a0SDimitry Andric TargetTransformInfo::OP_None;
225339d628a0SDimitry Andric TargetTransformInfo::OperandValueProperties Op2VP =
22544ba319b5SDimitry Andric TargetTransformInfo::OP_PowerOf2;
2255f785676fSDimitry Andric
225691bc56edSDimitry Andric // If all operands are exactly the same ConstantInt then set the
225791bc56edSDimitry Andric // operand kind to OK_UniformConstantValue.
225891bc56edSDimitry Andric // If instead not all operands are constants, then set the operand kind
225991bc56edSDimitry Andric // to OK_AnyValue. If all operands are constants but not the same,
226091bc56edSDimitry Andric // then set the operand kind to OK_NonUniformConstantValue.
22614ba319b5SDimitry Andric ConstantInt *CInt0 = nullptr;
22624ba319b5SDimitry Andric for (unsigned i = 0, e = VL.size(); i < e; ++i) {
226391bc56edSDimitry Andric const Instruction *I = cast<Instruction>(VL[i]);
22644ba319b5SDimitry Andric ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(1));
22654ba319b5SDimitry Andric if (!CInt) {
2266f785676fSDimitry Andric Op2VK = TargetTransformInfo::OK_AnyValue;
22674ba319b5SDimitry Andric Op2VP = TargetTransformInfo::OP_None;
2268f785676fSDimitry Andric break;
2269f785676fSDimitry Andric }
22704ba319b5SDimitry Andric if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
22714ba319b5SDimitry Andric !CInt->getValue().isPowerOf2())
22724ba319b5SDimitry Andric Op2VP = TargetTransformInfo::OP_None;
227391bc56edSDimitry Andric if (i == 0) {
22744ba319b5SDimitry Andric CInt0 = CInt;
227591bc56edSDimitry Andric continue;
227691bc56edSDimitry Andric }
22774ba319b5SDimitry Andric if (CInt0 != CInt)
227891bc56edSDimitry Andric Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
227991bc56edSDimitry Andric }
2280f785676fSDimitry Andric
22815517e702SDimitry Andric SmallVector<const Value *, 4> Operands(VL0->operand_values());
22824ba319b5SDimitry Andric int ScalarEltCost = TTI->getArithmeticInstrCost(
22834ba319b5SDimitry Andric S.getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands);
22844ba319b5SDimitry Andric if (NeedToShuffleReuses) {
22854ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
22864ba319b5SDimitry Andric }
22874ba319b5SDimitry Andric int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
22884ba319b5SDimitry Andric int VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy, Op1VK,
22894ba319b5SDimitry Andric Op2VK, Op1VP, Op2VP, Operands);
22904ba319b5SDimitry Andric return ReuseShuffleCost + VecCost - ScalarCost;
2291f785676fSDimitry Andric }
229291bc56edSDimitry Andric case Instruction::GetElementPtr: {
229391bc56edSDimitry Andric TargetTransformInfo::OperandValueKind Op1VK =
229491bc56edSDimitry Andric TargetTransformInfo::OK_AnyValue;
229591bc56edSDimitry Andric TargetTransformInfo::OperandValueKind Op2VK =
229691bc56edSDimitry Andric TargetTransformInfo::OK_UniformConstantValue;
229791bc56edSDimitry Andric
22984ba319b5SDimitry Andric int ScalarEltCost =
229991bc56edSDimitry Andric TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
23004ba319b5SDimitry Andric if (NeedToShuffleReuses) {
23014ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
23024ba319b5SDimitry Andric }
23034ba319b5SDimitry Andric int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
230491bc56edSDimitry Andric int VecCost =
230591bc56edSDimitry Andric TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
23064ba319b5SDimitry Andric return ReuseShuffleCost + VecCost - ScalarCost;
230791bc56edSDimitry Andric }
2308f785676fSDimitry Andric case Instruction::Load: {
2309f785676fSDimitry Andric // Cost of wide load - cost of scalar loads.
23104ba319b5SDimitry Andric unsigned alignment = cast<LoadInst>(VL0)->getAlignment();
23114ba319b5SDimitry Andric int ScalarEltCost =
23127a7e6055SDimitry Andric TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
23134ba319b5SDimitry Andric if (NeedToShuffleReuses) {
23144ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
23154ba319b5SDimitry Andric }
23164ba319b5SDimitry Andric int ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
23174ba319b5SDimitry Andric int VecLdCost =
23184ba319b5SDimitry Andric TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0, VL0);
23194ba319b5SDimitry Andric if (!E->ReorderIndices.empty()) {
23204ba319b5SDimitry Andric // TODO: Merge this shuffle with the ReuseShuffleCost.
23214ba319b5SDimitry Andric VecLdCost += TTI->getShuffleCost(
23224ba319b5SDimitry Andric TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
23234ba319b5SDimitry Andric }
23244ba319b5SDimitry Andric return ReuseShuffleCost + VecLdCost - ScalarLdCost;
2325f785676fSDimitry Andric }
2326f785676fSDimitry Andric case Instruction::Store: {
2327f785676fSDimitry Andric // We know that we can merge the stores. Calculate the cost.
23284ba319b5SDimitry Andric unsigned alignment = cast<StoreInst>(VL0)->getAlignment();
23294ba319b5SDimitry Andric int ScalarEltCost =
23307a7e6055SDimitry Andric TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
23314ba319b5SDimitry Andric if (NeedToShuffleReuses) {
23324ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
23334ba319b5SDimitry Andric }
23344ba319b5SDimitry Andric int ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
23354ba319b5SDimitry Andric int VecStCost =
23364ba319b5SDimitry Andric TTI->getMemoryOpCost(Instruction::Store, VecTy, alignment, 0, VL0);
23374ba319b5SDimitry Andric return ReuseShuffleCost + VecStCost - ScalarStCost;
2338f785676fSDimitry Andric }
233991bc56edSDimitry Andric case Instruction::Call: {
234091bc56edSDimitry Andric CallInst *CI = cast<CallInst>(VL0);
23413ca95b02SDimitry Andric Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
234291bc56edSDimitry Andric
234391bc56edSDimitry Andric // Calculate the cost of the scalar and vector calls.
23447a7e6055SDimitry Andric SmallVector<Type *, 4> ScalarTys;
23457a7e6055SDimitry Andric for (unsigned op = 0, opc = CI->getNumArgOperands(); op != opc; ++op)
234691bc56edSDimitry Andric ScalarTys.push_back(CI->getArgOperand(op)->getType());
234791bc56edSDimitry Andric
23483ca95b02SDimitry Andric FastMathFlags FMF;
23493ca95b02SDimitry Andric if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
23503ca95b02SDimitry Andric FMF = FPMO->getFastMathFlags();
235191bc56edSDimitry Andric
23524ba319b5SDimitry Andric int ScalarEltCost =
23533ca95b02SDimitry Andric TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
23544ba319b5SDimitry Andric if (NeedToShuffleReuses) {
23554ba319b5SDimitry Andric ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
23564ba319b5SDimitry Andric }
23574ba319b5SDimitry Andric int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
23583ca95b02SDimitry Andric
23597a7e6055SDimitry Andric SmallVector<Value *, 4> Args(CI->arg_operands());
23607a7e6055SDimitry Andric int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
23617a7e6055SDimitry Andric VecTy->getNumElements());
236291bc56edSDimitry Andric
23634ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
236491bc56edSDimitry Andric << " (" << VecCallCost << "-" << ScalarCallCost << ")"
236591bc56edSDimitry Andric << " for " << *CI << "\n");
236691bc56edSDimitry Andric
23674ba319b5SDimitry Andric return ReuseShuffleCost + VecCallCost - ScalarCallCost;
236891bc56edSDimitry Andric }
236991bc56edSDimitry Andric case Instruction::ShuffleVector: {
23704ba319b5SDimitry Andric assert(S.isAltShuffle() &&
23714ba319b5SDimitry Andric ((Instruction::isBinaryOp(S.getOpcode()) &&
23724ba319b5SDimitry Andric Instruction::isBinaryOp(S.getAltOpcode())) ||
23734ba319b5SDimitry Andric (Instruction::isCast(S.getOpcode()) &&
23744ba319b5SDimitry Andric Instruction::isCast(S.getAltOpcode()))) &&
23754ba319b5SDimitry Andric "Invalid Shuffle Vector Operand");
237691bc56edSDimitry Andric int ScalarCost = 0;
23774ba319b5SDimitry Andric if (NeedToShuffleReuses) {
23784ba319b5SDimitry Andric for (unsigned Idx : E->ReuseShuffleIndices) {
23794ba319b5SDimitry Andric Instruction *I = cast<Instruction>(VL[Idx]);
23804ba319b5SDimitry Andric ReuseShuffleCost -= TTI->getInstructionCost(
23814ba319b5SDimitry Andric I, TargetTransformInfo::TCK_RecipThroughput);
23824ba319b5SDimitry Andric }
23834ba319b5SDimitry Andric for (Value *V : VL) {
23844ba319b5SDimitry Andric Instruction *I = cast<Instruction>(V);
23854ba319b5SDimitry Andric ReuseShuffleCost += TTI->getInstructionCost(
23864ba319b5SDimitry Andric I, TargetTransformInfo::TCK_RecipThroughput);
23874ba319b5SDimitry Andric }
23884ba319b5SDimitry Andric }
23893ca95b02SDimitry Andric for (Value *i : VL) {
23903ca95b02SDimitry Andric Instruction *I = cast<Instruction>(i);
23914ba319b5SDimitry Andric assert(S.isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
23924ba319b5SDimitry Andric ScalarCost += TTI->getInstructionCost(
23934ba319b5SDimitry Andric I, TargetTransformInfo::TCK_RecipThroughput);
239491bc56edSDimitry Andric }
239591bc56edSDimitry Andric // VecCost is equal to sum of the cost of creating 2 vectors
239691bc56edSDimitry Andric // and the cost of creating shuffle.
23974ba319b5SDimitry Andric int VecCost = 0;
23984ba319b5SDimitry Andric if (Instruction::isBinaryOp(S.getOpcode())) {
23994ba319b5SDimitry Andric VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy);
24004ba319b5SDimitry Andric VecCost += TTI->getArithmeticInstrCost(S.getAltOpcode(), VecTy);
24014ba319b5SDimitry Andric } else {
24024ba319b5SDimitry Andric Type *Src0SclTy = S.MainOp->getOperand(0)->getType();
24034ba319b5SDimitry Andric Type *Src1SclTy = S.AltOp->getOperand(0)->getType();
24044ba319b5SDimitry Andric VectorType *Src0Ty = VectorType::get(Src0SclTy, VL.size());
24054ba319b5SDimitry Andric VectorType *Src1Ty = VectorType::get(Src1SclTy, VL.size());
24064ba319b5SDimitry Andric VecCost = TTI->getCastInstrCost(S.getOpcode(), VecTy, Src0Ty);
24074ba319b5SDimitry Andric VecCost += TTI->getCastInstrCost(S.getAltOpcode(), VecTy, Src1Ty);
24084ba319b5SDimitry Andric }
24094ba319b5SDimitry Andric VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
24104ba319b5SDimitry Andric return ReuseShuffleCost + VecCost - ScalarCost;
241191bc56edSDimitry Andric }
2412f785676fSDimitry Andric default:
2413f785676fSDimitry Andric llvm_unreachable("Unknown instruction");
2414f785676fSDimitry Andric }
2415f785676fSDimitry Andric }
2416f785676fSDimitry Andric
isFullyVectorizableTinyTree()2417f785676fSDimitry Andric bool BoUpSLP::isFullyVectorizableTinyTree() {
24184ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
24194ba319b5SDimitry Andric << VectorizableTree.size() << " is fully vectorizable .\n");
2420f785676fSDimitry Andric
2421d88c1a5aSDimitry Andric // We only handle trees of heights 1 and 2.
2422d88c1a5aSDimitry Andric if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
2423d88c1a5aSDimitry Andric return true;
2424d88c1a5aSDimitry Andric
2425f785676fSDimitry Andric if (VectorizableTree.size() != 2)
2426f785676fSDimitry Andric return false;
2427f785676fSDimitry Andric
24285673a0f9SDimitry Andric // Handle splat and all-constants stores.
24295673a0f9SDimitry Andric if (!VectorizableTree[0].NeedToGather &&
24305673a0f9SDimitry Andric (allConstant(VectorizableTree[1].Scalars) ||
24315673a0f9SDimitry Andric isSplat(VectorizableTree[1].Scalars)))
243291bc56edSDimitry Andric return true;
243391bc56edSDimitry Andric
2434f785676fSDimitry Andric // Gathering cost would be too much for tiny trees.
2435f785676fSDimitry Andric if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
2436f785676fSDimitry Andric return false;
2437f785676fSDimitry Andric
2438f785676fSDimitry Andric return true;
2439f785676fSDimitry Andric }
2440f785676fSDimitry Andric
isTreeTinyAndNotFullyVectorizable()2441d88c1a5aSDimitry Andric bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
2442d88c1a5aSDimitry Andric // We can vectorize the tree if its size is greater than or equal to the
2443d88c1a5aSDimitry Andric // minimum size specified by the MinTreeSize command line option.
2444d88c1a5aSDimitry Andric if (VectorizableTree.size() >= MinTreeSize)
2445d88c1a5aSDimitry Andric return false;
2446d88c1a5aSDimitry Andric
2447d88c1a5aSDimitry Andric // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
2448d88c1a5aSDimitry Andric // can vectorize it if we can prove it fully vectorizable.
2449d88c1a5aSDimitry Andric if (isFullyVectorizableTinyTree())
2450d88c1a5aSDimitry Andric return false;
2451d88c1a5aSDimitry Andric
2452d88c1a5aSDimitry Andric assert(VectorizableTree.empty()
2453d88c1a5aSDimitry Andric ? ExternalUses.empty()
2454d88c1a5aSDimitry Andric : true && "We shouldn't have any external users");
2455d88c1a5aSDimitry Andric
2456d88c1a5aSDimitry Andric // Otherwise, we can't vectorize the tree. It is both tiny and not fully
2457d88c1a5aSDimitry Andric // vectorizable.
2458d88c1a5aSDimitry Andric return true;
2459d88c1a5aSDimitry Andric }
2460d88c1a5aSDimitry Andric
getSpillCost()246139d628a0SDimitry Andric int BoUpSLP::getSpillCost() {
246239d628a0SDimitry Andric // Walk from the bottom of the tree to the top, tracking which values are
246339d628a0SDimitry Andric // live. When we see a call instruction that is not part of our tree,
246439d628a0SDimitry Andric // query TTI to see if there is a cost to keeping values live over it
246539d628a0SDimitry Andric // (for example, if spills and fills are required).
246639d628a0SDimitry Andric unsigned BundleWidth = VectorizableTree.front().Scalars.size();
246739d628a0SDimitry Andric int Cost = 0;
246839d628a0SDimitry Andric
246939d628a0SDimitry Andric SmallPtrSet<Instruction*, 4> LiveValues;
247039d628a0SDimitry Andric Instruction *PrevInst = nullptr;
247139d628a0SDimitry Andric
24723ca95b02SDimitry Andric for (const auto &N : VectorizableTree) {
24733ca95b02SDimitry Andric Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
247439d628a0SDimitry Andric if (!Inst)
247539d628a0SDimitry Andric continue;
247639d628a0SDimitry Andric
247739d628a0SDimitry Andric if (!PrevInst) {
247839d628a0SDimitry Andric PrevInst = Inst;
247939d628a0SDimitry Andric continue;
248039d628a0SDimitry Andric }
248139d628a0SDimitry Andric
24823ca95b02SDimitry Andric // Update LiveValues.
24833ca95b02SDimitry Andric LiveValues.erase(PrevInst);
24843ca95b02SDimitry Andric for (auto &J : PrevInst->operands()) {
2485a580b014SDimitry Andric if (isa<Instruction>(&*J) && getTreeEntry(&*J))
24863ca95b02SDimitry Andric LiveValues.insert(cast<Instruction>(&*J));
24873ca95b02SDimitry Andric }
24883ca95b02SDimitry Andric
24894ba319b5SDimitry Andric LLVM_DEBUG({
249039d628a0SDimitry Andric dbgs() << "SLP: #LV: " << LiveValues.size();
249139d628a0SDimitry Andric for (auto *X : LiveValues)
249239d628a0SDimitry Andric dbgs() << " " << X->getName();
249339d628a0SDimitry Andric dbgs() << ", Looking at ";
249439d628a0SDimitry Andric Inst->dump();
24954ba319b5SDimitry Andric });
249639d628a0SDimitry Andric
249739d628a0SDimitry Andric // Now find the sequence of instructions between PrevInst and Inst.
2498d88c1a5aSDimitry Andric BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2499d88c1a5aSDimitry Andric PrevInstIt =
2500d88c1a5aSDimitry Andric PrevInst->getIterator().getReverse();
250139d628a0SDimitry Andric while (InstIt != PrevInstIt) {
250239d628a0SDimitry Andric if (PrevInstIt == PrevInst->getParent()->rend()) {
250339d628a0SDimitry Andric PrevInstIt = Inst->getParent()->rbegin();
250439d628a0SDimitry Andric continue;
250539d628a0SDimitry Andric }
250639d628a0SDimitry Andric
25074ba319b5SDimitry Andric // Debug informations don't impact spill cost.
25084ba319b5SDimitry Andric if ((isa<CallInst>(&*PrevInstIt) &&
25094ba319b5SDimitry Andric !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
25104ba319b5SDimitry Andric &*PrevInstIt != PrevInst) {
251139d628a0SDimitry Andric SmallVector<Type*, 4> V;
251239d628a0SDimitry Andric for (auto *II : LiveValues)
251339d628a0SDimitry Andric V.push_back(VectorType::get(II->getType(), BundleWidth));
251439d628a0SDimitry Andric Cost += TTI->getCostOfKeepingLiveOverCall(V);
251539d628a0SDimitry Andric }
251639d628a0SDimitry Andric
251739d628a0SDimitry Andric ++PrevInstIt;
251839d628a0SDimitry Andric }
251939d628a0SDimitry Andric
252039d628a0SDimitry Andric PrevInst = Inst;
252139d628a0SDimitry Andric }
252239d628a0SDimitry Andric
252339d628a0SDimitry Andric return Cost;
252439d628a0SDimitry Andric }
252539d628a0SDimitry Andric
getTreeCost()2526f785676fSDimitry Andric int BoUpSLP::getTreeCost() {
2527f785676fSDimitry Andric int Cost = 0;
25284ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
25294ba319b5SDimitry Andric << VectorizableTree.size() << ".\n");
2530f785676fSDimitry Andric
2531f785676fSDimitry Andric unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2532f785676fSDimitry Andric
25334ba319b5SDimitry Andric for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
25344ba319b5SDimitry Andric TreeEntry &TE = VectorizableTree[I];
25354ba319b5SDimitry Andric
25364ba319b5SDimitry Andric // We create duplicate tree entries for gather sequences that have multiple
25374ba319b5SDimitry Andric // uses. However, we should not compute the cost of duplicate sequences.
25384ba319b5SDimitry Andric // For example, if we have a build vector (i.e., insertelement sequence)
25394ba319b5SDimitry Andric // that is used by more than one vector instruction, we only need to
2540*b5893f02SDimitry Andric // compute the cost of the insertelement instructions once. The redundant
25414ba319b5SDimitry Andric // instructions will be eliminated by CSE.
25424ba319b5SDimitry Andric //
25434ba319b5SDimitry Andric // We should consider not creating duplicate tree entries for gather
25444ba319b5SDimitry Andric // sequences, and instead add additional edges to the tree representing
25454ba319b5SDimitry Andric // their uses. Since such an approach results in fewer total entries,
2546*b5893f02SDimitry Andric // existing heuristics based on tree size may yield different results.
25474ba319b5SDimitry Andric //
25484ba319b5SDimitry Andric if (TE.NeedToGather &&
25494ba319b5SDimitry Andric std::any_of(std::next(VectorizableTree.begin(), I + 1),
25504ba319b5SDimitry Andric VectorizableTree.end(), [TE](TreeEntry &Entry) {
25514ba319b5SDimitry Andric return Entry.NeedToGather && Entry.isSame(TE.Scalars);
25524ba319b5SDimitry Andric }))
25534ba319b5SDimitry Andric continue;
25544ba319b5SDimitry Andric
2555444ed5c5SDimitry Andric int C = getEntryCost(&TE);
25564ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
25574ba319b5SDimitry Andric << " for bundle that starts with " << *TE.Scalars[0]
25584ba319b5SDimitry Andric << ".\n");
2559f785676fSDimitry Andric Cost += C;
2560f785676fSDimitry Andric }
2561f785676fSDimitry Andric
25624ba319b5SDimitry Andric SmallPtrSet<Value *, 16> ExtractCostCalculated;
2563f785676fSDimitry Andric int ExtractCost = 0;
2564444ed5c5SDimitry Andric for (ExternalUser &EU : ExternalUses) {
256591bc56edSDimitry Andric // We only add extract cost once for the same scalar.
2566444ed5c5SDimitry Andric if (!ExtractCostCalculated.insert(EU.Scalar).second)
256739d628a0SDimitry Andric continue;
256839d628a0SDimitry Andric
256939d628a0SDimitry Andric // Uses by ephemeral values are free (because the ephemeral value will be
257039d628a0SDimitry Andric // removed prior to code generation, and so the extraction will be
257139d628a0SDimitry Andric // removed as well).
2572444ed5c5SDimitry Andric if (EphValues.count(EU.User))
257391bc56edSDimitry Andric continue;
2574f785676fSDimitry Andric
25753ca95b02SDimitry Andric // If we plan to rewrite the tree in a smaller type, we will need to sign
25763ca95b02SDimitry Andric // extend the extracted value back to the original type. Here, we account
25773ca95b02SDimitry Andric // for the extract and the added cost of the sign extend if needed.
25783ca95b02SDimitry Andric auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
25793ca95b02SDimitry Andric auto *ScalarRoot = VectorizableTree[0].Scalars[0];
25803ca95b02SDimitry Andric if (MinBWs.count(ScalarRoot)) {
2581d88c1a5aSDimitry Andric auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2582d88c1a5aSDimitry Andric auto Extend =
2583d88c1a5aSDimitry Andric MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
25843ca95b02SDimitry Andric VecTy = VectorType::get(MinTy, BundleWidth);
2585d88c1a5aSDimitry Andric ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2586d88c1a5aSDimitry Andric VecTy, EU.Lane);
25873ca95b02SDimitry Andric } else {
25883ca95b02SDimitry Andric ExtractCost +=
25893ca95b02SDimitry Andric TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
25903ca95b02SDimitry Andric }
2591f785676fSDimitry Andric }
2592f785676fSDimitry Andric
25933ca95b02SDimitry Andric int SpillCost = getSpillCost();
25943ca95b02SDimitry Andric Cost += SpillCost + ExtractCost;
259539d628a0SDimitry Andric
25967a7e6055SDimitry Andric std::string Str;
25977a7e6055SDimitry Andric {
25987a7e6055SDimitry Andric raw_string_ostream OS(Str);
25997a7e6055SDimitry Andric OS << "SLP: Spill Cost = " << SpillCost << ".\n"
26003ca95b02SDimitry Andric << "SLP: Extract Cost = " << ExtractCost << ".\n"
26017a7e6055SDimitry Andric << "SLP: Total Cost = " << Cost << ".\n";
26027a7e6055SDimitry Andric }
26034ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << Str);
26047a7e6055SDimitry Andric
26057a7e6055SDimitry Andric if (ViewSLPTree)
26067a7e6055SDimitry Andric ViewGraph(this, "SLP" + F->getName(), false, Str);
26077a7e6055SDimitry Andric
26083ca95b02SDimitry Andric return Cost;
2609f785676fSDimitry Andric }
2610f785676fSDimitry Andric
getGatherCost(Type * Ty,const DenseSet<unsigned> & ShuffledIndices)26114ba319b5SDimitry Andric int BoUpSLP::getGatherCost(Type *Ty,
26124ba319b5SDimitry Andric const DenseSet<unsigned> &ShuffledIndices) {
2613f785676fSDimitry Andric int Cost = 0;
2614f785676fSDimitry Andric for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
26154ba319b5SDimitry Andric if (!ShuffledIndices.count(i))
2616f785676fSDimitry Andric Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
26174ba319b5SDimitry Andric if (!ShuffledIndices.empty())
26184ba319b5SDimitry Andric Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
2619f785676fSDimitry Andric return Cost;
2620f785676fSDimitry Andric }
2621f785676fSDimitry Andric
getGatherCost(ArrayRef<Value * > VL)2622f785676fSDimitry Andric int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2623f785676fSDimitry Andric // Find the type of the operands in VL.
2624f785676fSDimitry Andric Type *ScalarTy = VL[0]->getType();
2625f785676fSDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2626f785676fSDimitry Andric ScalarTy = SI->getValueOperand()->getType();
2627f785676fSDimitry Andric VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2628f785676fSDimitry Andric // Find the cost of inserting/extracting values from the vector.
26294ba319b5SDimitry Andric // Check if the same elements are inserted several times and count them as
26304ba319b5SDimitry Andric // shuffle candidates.
26314ba319b5SDimitry Andric DenseSet<unsigned> ShuffledElements;
26324ba319b5SDimitry Andric DenseSet<Value *> UniqueElements;
26334ba319b5SDimitry Andric // Iterate in reverse order to consider insert elements with the high cost.
26344ba319b5SDimitry Andric for (unsigned I = VL.size(); I > 0; --I) {
26354ba319b5SDimitry Andric unsigned Idx = I - 1;
26364ba319b5SDimitry Andric if (!UniqueElements.insert(VL[Idx]).second)
26374ba319b5SDimitry Andric ShuffledElements.insert(Idx);
26384ba319b5SDimitry Andric }
26394ba319b5SDimitry Andric return getGatherCost(VecTy, ShuffledElements);
2640f785676fSDimitry Andric }
2641f785676fSDimitry Andric
2642ff0cc061SDimitry Andric // Reorder commutative operations in alternate shuffle if the resulting vectors
2643ff0cc061SDimitry Andric // are consecutive loads. This would allow us to vectorize the tree.
2644ff0cc061SDimitry Andric // If we have something like-
2645ff0cc061SDimitry Andric // load a[0] - load b[0]
2646ff0cc061SDimitry Andric // load b[1] + load a[1]
2647ff0cc061SDimitry Andric // load a[2] - load b[2]
2648ff0cc061SDimitry Andric // load a[3] + load b[3]
2649ff0cc061SDimitry Andric // Reordering the second load b[1] load a[1] would allow us to vectorize this
2650ff0cc061SDimitry Andric // code.
reorderAltShuffleOperands(const InstructionsState & S,ArrayRef<Value * > VL,SmallVectorImpl<Value * > & Left,SmallVectorImpl<Value * > & Right)26514ba319b5SDimitry Andric void BoUpSLP::reorderAltShuffleOperands(const InstructionsState &S,
26524ba319b5SDimitry Andric ArrayRef<Value *> VL,
2653ff0cc061SDimitry Andric SmallVectorImpl<Value *> &Left,
2654ff0cc061SDimitry Andric SmallVectorImpl<Value *> &Right) {
2655ff0cc061SDimitry Andric // Push left and right operands of binary operation into Left and Right
26562cab237bSDimitry Andric for (Value *V : VL) {
26572cab237bSDimitry Andric auto *I = cast<Instruction>(V);
26584ba319b5SDimitry Andric assert(S.isOpcodeOrAlt(I) && "Incorrect instruction in vector");
26592cab237bSDimitry Andric Left.push_back(I->getOperand(0));
26602cab237bSDimitry Andric Right.push_back(I->getOperand(1));
2661ff0cc061SDimitry Andric }
2662ff0cc061SDimitry Andric
2663ff0cc061SDimitry Andric // Reorder if we have a commutative operation and consecutive access
2664ff0cc061SDimitry Andric // are on either side of the alternate instructions.
2665ff0cc061SDimitry Andric for (unsigned j = 0; j < VL.size() - 1; ++j) {
2666ff0cc061SDimitry Andric if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2667ff0cc061SDimitry Andric if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2668ff0cc061SDimitry Andric Instruction *VL1 = cast<Instruction>(VL[j]);
2669ff0cc061SDimitry Andric Instruction *VL2 = cast<Instruction>(VL[j + 1]);
26703ca95b02SDimitry Andric if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2671ff0cc061SDimitry Andric std::swap(Left[j], Right[j]);
2672ff0cc061SDimitry Andric continue;
26733ca95b02SDimitry Andric } else if (VL2->isCommutative() &&
26743ca95b02SDimitry Andric isConsecutiveAccess(L, L1, *DL, *SE)) {
2675ff0cc061SDimitry Andric std::swap(Left[j + 1], Right[j + 1]);
2676ff0cc061SDimitry Andric continue;
2677ff0cc061SDimitry Andric }
2678ff0cc061SDimitry Andric // else unchanged
2679ff0cc061SDimitry Andric }
2680ff0cc061SDimitry Andric }
2681ff0cc061SDimitry Andric if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2682ff0cc061SDimitry Andric if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2683ff0cc061SDimitry Andric Instruction *VL1 = cast<Instruction>(VL[j]);
2684ff0cc061SDimitry Andric Instruction *VL2 = cast<Instruction>(VL[j + 1]);
26853ca95b02SDimitry Andric if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2686ff0cc061SDimitry Andric std::swap(Left[j], Right[j]);
2687ff0cc061SDimitry Andric continue;
26883ca95b02SDimitry Andric } else if (VL2->isCommutative() &&
26893ca95b02SDimitry Andric isConsecutiveAccess(L, L1, *DL, *SE)) {
2690ff0cc061SDimitry Andric std::swap(Left[j + 1], Right[j + 1]);
2691ff0cc061SDimitry Andric continue;
2692ff0cc061SDimitry Andric }
2693ff0cc061SDimitry Andric // else unchanged
2694ff0cc061SDimitry Andric }
2695ff0cc061SDimitry Andric }
2696ff0cc061SDimitry Andric }
2697ff0cc061SDimitry Andric }
2698ff0cc061SDimitry Andric
26997d523365SDimitry Andric // Return true if I should be commuted before adding it's left and right
27007d523365SDimitry Andric // operands to the arrays Left and Right.
27017d523365SDimitry Andric //
27027d523365SDimitry Andric // The vectorizer is trying to either have all elements one side being
27037d523365SDimitry Andric // instruction with the same opcode to enable further vectorization, or having
27047d523365SDimitry Andric // a splat to lower the vectorizing cost.
shouldReorderOperands(int i,unsigned Opcode,Instruction & I,ArrayRef<Value * > Left,ArrayRef<Value * > Right,bool AllSameOpcodeLeft,bool AllSameOpcodeRight,bool SplatLeft,bool SplatRight,Value * & VLeft,Value * & VRight)27052cab237bSDimitry Andric static bool shouldReorderOperands(
27062cab237bSDimitry Andric int i, unsigned Opcode, Instruction &I, ArrayRef<Value *> Left,
27072cab237bSDimitry Andric ArrayRef<Value *> Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight,
27082cab237bSDimitry Andric bool SplatLeft, bool SplatRight, Value *&VLeft, Value *&VRight) {
27092cab237bSDimitry Andric VLeft = I.getOperand(0);
27102cab237bSDimitry Andric VRight = I.getOperand(1);
27117d523365SDimitry Andric // If we have "SplatRight", try to see if commuting is needed to preserve it.
27127d523365SDimitry Andric if (SplatRight) {
27137d523365SDimitry Andric if (VRight == Right[i - 1])
27147d523365SDimitry Andric // Preserve SplatRight
27157d523365SDimitry Andric return false;
27167d523365SDimitry Andric if (VLeft == Right[i - 1]) {
27177d523365SDimitry Andric // Commuting would preserve SplatRight, but we don't want to break
27187d523365SDimitry Andric // SplatLeft either, i.e. preserve the original order if possible.
27197d523365SDimitry Andric // (FIXME: why do we care?)
27207d523365SDimitry Andric if (SplatLeft && VLeft == Left[i - 1])
27217d523365SDimitry Andric return false;
27227d523365SDimitry Andric return true;
27237d523365SDimitry Andric }
27247d523365SDimitry Andric }
27257d523365SDimitry Andric // Symmetrically handle Right side.
27267d523365SDimitry Andric if (SplatLeft) {
27277d523365SDimitry Andric if (VLeft == Left[i - 1])
27287d523365SDimitry Andric // Preserve SplatLeft
27297d523365SDimitry Andric return false;
27307d523365SDimitry Andric if (VRight == Left[i - 1])
27317d523365SDimitry Andric return true;
27327d523365SDimitry Andric }
2733ff0cc061SDimitry Andric
2734ff0cc061SDimitry Andric Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2735ff0cc061SDimitry Andric Instruction *IRight = dyn_cast<Instruction>(VRight);
2736ff0cc061SDimitry Andric
27377d523365SDimitry Andric // If we have "AllSameOpcodeRight", try to see if the left operands preserves
27387d523365SDimitry Andric // it and not the right, in this case we want to commute.
27397d523365SDimitry Andric if (AllSameOpcodeRight) {
27407d523365SDimitry Andric unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
27417d523365SDimitry Andric if (IRight && RightPrevOpcode == IRight->getOpcode())
27427d523365SDimitry Andric // Do not commute, a match on the right preserves AllSameOpcodeRight
27437d523365SDimitry Andric return false;
27447d523365SDimitry Andric if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
27457d523365SDimitry Andric // We have a match and may want to commute, but first check if there is
27467d523365SDimitry Andric // not also a match on the existing operands on the Left to preserve
27477d523365SDimitry Andric // AllSameOpcodeLeft, i.e. preserve the original order if possible.
27487d523365SDimitry Andric // (FIXME: why do we care?)
27497d523365SDimitry Andric if (AllSameOpcodeLeft && ILeft &&
27507d523365SDimitry Andric cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
27517d523365SDimitry Andric return false;
27527d523365SDimitry Andric return true;
2753ff0cc061SDimitry Andric }
27547d523365SDimitry Andric }
27557d523365SDimitry Andric // Symmetrically handle Left side.
27567d523365SDimitry Andric if (AllSameOpcodeLeft) {
27577d523365SDimitry Andric unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
27587d523365SDimitry Andric if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
27597d523365SDimitry Andric return false;
27607d523365SDimitry Andric if (IRight && LeftPrevOpcode == IRight->getOpcode())
27617d523365SDimitry Andric return true;
27627d523365SDimitry Andric }
27637d523365SDimitry Andric return false;
2764ff0cc061SDimitry Andric }
2765ff0cc061SDimitry Andric
reorderInputsAccordingToOpcode(unsigned Opcode,ArrayRef<Value * > VL,SmallVectorImpl<Value * > & Left,SmallVectorImpl<Value * > & Right)27662cab237bSDimitry Andric void BoUpSLP::reorderInputsAccordingToOpcode(unsigned Opcode,
27672cab237bSDimitry Andric ArrayRef<Value *> VL,
27687d523365SDimitry Andric SmallVectorImpl<Value *> &Left,
27697d523365SDimitry Andric SmallVectorImpl<Value *> &Right) {
27702cab237bSDimitry Andric if (!VL.empty()) {
27717d523365SDimitry Andric // Peel the first iteration out of the loop since there's nothing
27727d523365SDimitry Andric // interesting to do anyway and it simplifies the checks in the loop.
27732cab237bSDimitry Andric auto *I = cast<Instruction>(VL[0]);
27742cab237bSDimitry Andric Value *VLeft = I->getOperand(0);
27752cab237bSDimitry Andric Value *VRight = I->getOperand(1);
27767d523365SDimitry Andric if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
27777d523365SDimitry Andric // Favor having instruction to the right. FIXME: why?
27787d523365SDimitry Andric std::swap(VLeft, VRight);
2779ff0cc061SDimitry Andric Left.push_back(VLeft);
2780ff0cc061SDimitry Andric Right.push_back(VRight);
2781ff0cc061SDimitry Andric }
2782ff0cc061SDimitry Andric
27837d523365SDimitry Andric // Keep track if we have instructions with all the same opcode on one side.
27847d523365SDimitry Andric bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
27857d523365SDimitry Andric bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
27867d523365SDimitry Andric // Keep track if we have one side with all the same value (broadcast).
27877d523365SDimitry Andric bool SplatLeft = true;
27887d523365SDimitry Andric bool SplatRight = true;
2789ff0cc061SDimitry Andric
27907d523365SDimitry Andric for (unsigned i = 1, e = VL.size(); i != e; ++i) {
27917d523365SDimitry Andric Instruction *I = cast<Instruction>(VL[i]);
27922cab237bSDimitry Andric assert(((I->getOpcode() == Opcode && I->isCommutative()) ||
27932cab237bSDimitry Andric (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) &&
27942cab237bSDimitry Andric "Can only process commutative instruction");
27957d523365SDimitry Andric // Commute to favor either a splat or maximizing having the same opcodes on
27967d523365SDimitry Andric // one side.
27972cab237bSDimitry Andric Value *VLeft;
27982cab237bSDimitry Andric Value *VRight;
27992cab237bSDimitry Andric if (shouldReorderOperands(i, Opcode, *I, Left, Right, AllSameOpcodeLeft,
28002cab237bSDimitry Andric AllSameOpcodeRight, SplatLeft, SplatRight, VLeft,
28012cab237bSDimitry Andric VRight)) {
28022cab237bSDimitry Andric Left.push_back(VRight);
28032cab237bSDimitry Andric Right.push_back(VLeft);
28047d523365SDimitry Andric } else {
28052cab237bSDimitry Andric Left.push_back(VLeft);
28062cab237bSDimitry Andric Right.push_back(VRight);
2807ff0cc061SDimitry Andric }
28087d523365SDimitry Andric // Update Splat* and AllSameOpcode* after the insertion.
28097d523365SDimitry Andric SplatRight = SplatRight && (Right[i - 1] == Right[i]);
28107d523365SDimitry Andric SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
28117d523365SDimitry Andric AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
28127d523365SDimitry Andric (cast<Instruction>(Left[i - 1])->getOpcode() ==
28137d523365SDimitry Andric cast<Instruction>(Left[i])->getOpcode());
28147d523365SDimitry Andric AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
28157d523365SDimitry Andric (cast<Instruction>(Right[i - 1])->getOpcode() ==
28167d523365SDimitry Andric cast<Instruction>(Right[i])->getOpcode());
28177d523365SDimitry Andric }
28187d523365SDimitry Andric
28197d523365SDimitry Andric // If one operand end up being broadcast, return this operand order.
28207d523365SDimitry Andric if (SplatRight || SplatLeft)
28217d523365SDimitry Andric return;
2822ff0cc061SDimitry Andric
2823ff0cc061SDimitry Andric // Finally check if we can get longer vectorizable chain by reordering
2824ff0cc061SDimitry Andric // without breaking the good operand order detected above.
2825ff0cc061SDimitry Andric // E.g. If we have something like-
2826ff0cc061SDimitry Andric // load a[0] load b[0]
2827ff0cc061SDimitry Andric // load b[1] load a[1]
2828ff0cc061SDimitry Andric // load a[2] load b[2]
2829ff0cc061SDimitry Andric // load a[3] load b[3]
2830ff0cc061SDimitry Andric // Reordering the second load b[1] load a[1] would allow us to vectorize
2831ff0cc061SDimitry Andric // this code and we still retain AllSameOpcode property.
2832ff0cc061SDimitry Andric // FIXME: This load reordering might break AllSameOpcode in some rare cases
2833ff0cc061SDimitry Andric // such as-
2834ff0cc061SDimitry Andric // add a[0],c[0] load b[0]
2835ff0cc061SDimitry Andric // add a[1],c[2] load b[1]
2836ff0cc061SDimitry Andric // b[2] load b[2]
2837ff0cc061SDimitry Andric // add a[3],c[3] load b[3]
28384ba319b5SDimitry Andric for (unsigned j = 0, e = VL.size() - 1; j < e; ++j) {
2839ff0cc061SDimitry Andric if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2840ff0cc061SDimitry Andric if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
28413ca95b02SDimitry Andric if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2842ff0cc061SDimitry Andric std::swap(Left[j + 1], Right[j + 1]);
2843ff0cc061SDimitry Andric continue;
2844ff0cc061SDimitry Andric }
2845ff0cc061SDimitry Andric }
2846ff0cc061SDimitry Andric }
2847ff0cc061SDimitry Andric if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2848ff0cc061SDimitry Andric if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
28493ca95b02SDimitry Andric if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2850ff0cc061SDimitry Andric std::swap(Left[j + 1], Right[j + 1]);
2851ff0cc061SDimitry Andric continue;
2852ff0cc061SDimitry Andric }
2853ff0cc061SDimitry Andric }
2854ff0cc061SDimitry Andric }
2855ff0cc061SDimitry Andric // else unchanged
2856ff0cc061SDimitry Andric }
2857ff0cc061SDimitry Andric }
2858ff0cc061SDimitry Andric
setInsertPointAfterBundle(ArrayRef<Value * > VL,const InstructionsState & S)28594ba319b5SDimitry Andric void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL,
28604ba319b5SDimitry Andric const InstructionsState &S) {
2861fccc5558SDimitry Andric // Get the basic block this bundle is in. All instructions in the bundle
2862fccc5558SDimitry Andric // should be in this block.
28634ba319b5SDimitry Andric auto *Front = cast<Instruction>(S.OpValue);
2864fccc5558SDimitry Andric auto *BB = Front->getParent();
28652cab237bSDimitry Andric assert(llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool {
28664ba319b5SDimitry Andric auto *I = cast<Instruction>(V);
28674ba319b5SDimitry Andric return !S.isOpcodeOrAlt(I) || I->getParent() == BB;
2868fccc5558SDimitry Andric }));
2869fccc5558SDimitry Andric
2870fccc5558SDimitry Andric // The last instruction in the bundle in program order.
2871fccc5558SDimitry Andric Instruction *LastInst = nullptr;
2872fccc5558SDimitry Andric
2873fccc5558SDimitry Andric // Find the last instruction. The common case should be that BB has been
2874fccc5558SDimitry Andric // scheduled, and the last instruction is VL.back(). So we start with
2875fccc5558SDimitry Andric // VL.back() and iterate over schedule data until we reach the end of the
2876fccc5558SDimitry Andric // bundle. The end of the bundle is marked by null ScheduleData.
2877fccc5558SDimitry Andric if (BlocksSchedules.count(BB)) {
28782cab237bSDimitry Andric auto *Bundle =
28794ba319b5SDimitry Andric BlocksSchedules[BB]->getScheduleData(isOneOf(S, VL.back()));
2880fccc5558SDimitry Andric if (Bundle && Bundle->isPartOfBundle())
2881fccc5558SDimitry Andric for (; Bundle; Bundle = Bundle->NextInBundle)
28822cab237bSDimitry Andric if (Bundle->OpValue == Bundle->Inst)
2883fccc5558SDimitry Andric LastInst = Bundle->Inst;
2884fccc5558SDimitry Andric }
2885fccc5558SDimitry Andric
2886fccc5558SDimitry Andric // LastInst can still be null at this point if there's either not an entry
2887fccc5558SDimitry Andric // for BB in BlocksSchedules or there's no ScheduleData available for
2888fccc5558SDimitry Andric // VL.back(). This can be the case if buildTree_rec aborts for various
2889fccc5558SDimitry Andric // reasons (e.g., the maximum recursion depth is reached, the maximum region
2890fccc5558SDimitry Andric // size is reached, etc.). ScheduleData is initialized in the scheduling
2891fccc5558SDimitry Andric // "dry-run".
2892fccc5558SDimitry Andric //
2893fccc5558SDimitry Andric // If this happens, we can still find the last instruction by brute force. We
2894fccc5558SDimitry Andric // iterate forwards from Front (inclusive) until we either see all
2895fccc5558SDimitry Andric // instructions in the bundle or reach the end of the block. If Front is the
2896fccc5558SDimitry Andric // last instruction in program order, LastInst will be set to Front, and we
2897fccc5558SDimitry Andric // will visit all the remaining instructions in the block.
2898fccc5558SDimitry Andric //
2899fccc5558SDimitry Andric // One of the reasons we exit early from buildTree_rec is to place an upper
2900fccc5558SDimitry Andric // bound on compile-time. Thus, taking an additional compile-time hit here is
2901fccc5558SDimitry Andric // not ideal. However, this should be exceedingly rare since it requires that
2902fccc5558SDimitry Andric // we both exit early from buildTree_rec and that the bundle be out-of-order
2903fccc5558SDimitry Andric // (causing us to iterate all the way to the end of the block).
2904fccc5558SDimitry Andric if (!LastInst) {
2905fccc5558SDimitry Andric SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2906fccc5558SDimitry Andric for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
29074ba319b5SDimitry Andric if (Bundle.erase(&I) && S.isOpcodeOrAlt(&I))
2908fccc5558SDimitry Andric LastInst = &I;
2909fccc5558SDimitry Andric if (Bundle.empty())
2910fccc5558SDimitry Andric break;
2911fccc5558SDimitry Andric }
2912fccc5558SDimitry Andric }
2913fccc5558SDimitry Andric
2914fccc5558SDimitry Andric // Set the insertion point after the last instruction in the bundle. Set the
2915fccc5558SDimitry Andric // debug location to Front.
2916d88c1a5aSDimitry Andric Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2917fccc5558SDimitry Andric Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2918f785676fSDimitry Andric }
2919f785676fSDimitry Andric
Gather(ArrayRef<Value * > VL,VectorType * Ty)2920f785676fSDimitry Andric Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2921f785676fSDimitry Andric Value *Vec = UndefValue::get(Ty);
2922f785676fSDimitry Andric // Generate the 'InsertElement' instruction.
2923f785676fSDimitry Andric for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2924f785676fSDimitry Andric Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2925f785676fSDimitry Andric if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2926f785676fSDimitry Andric GatherSeq.insert(Insrt);
2927f785676fSDimitry Andric CSEBlocks.insert(Insrt->getParent());
2928f785676fSDimitry Andric
2929f785676fSDimitry Andric // Add to our 'need-to-extract' list.
2930a580b014SDimitry Andric if (TreeEntry *E = getTreeEntry(VL[i])) {
2931f785676fSDimitry Andric // Find which lane we need to extract.
2932f785676fSDimitry Andric int FoundLane = -1;
29334ba319b5SDimitry Andric for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
2934f785676fSDimitry Andric // Is this the lane of the scalar that we are looking for ?
2935f785676fSDimitry Andric if (E->Scalars[Lane] == VL[i]) {
2936f785676fSDimitry Andric FoundLane = Lane;
2937f785676fSDimitry Andric break;
2938f785676fSDimitry Andric }
2939f785676fSDimitry Andric }
2940f785676fSDimitry Andric assert(FoundLane >= 0 && "Could not find the correct lane");
29414ba319b5SDimitry Andric if (!E->ReuseShuffleIndices.empty()) {
29424ba319b5SDimitry Andric FoundLane =
29434ba319b5SDimitry Andric std::distance(E->ReuseShuffleIndices.begin(),
29444ba319b5SDimitry Andric llvm::find(E->ReuseShuffleIndices, FoundLane));
29454ba319b5SDimitry Andric }
2946f785676fSDimitry Andric ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2947f785676fSDimitry Andric }
2948f785676fSDimitry Andric }
2949f785676fSDimitry Andric }
2950f785676fSDimitry Andric
2951f785676fSDimitry Andric return Vec;
2952f785676fSDimitry Andric }
2953f785676fSDimitry Andric
vectorizeTree(ArrayRef<Value * > VL)2954da09e106SDimitry Andric Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
29552cab237bSDimitry Andric InstructionsState S = getSameOpcode(VL);
29564ba319b5SDimitry Andric if (S.getOpcode()) {
29572cab237bSDimitry Andric if (TreeEntry *E = getTreeEntry(S.OpValue)) {
29584ba319b5SDimitry Andric if (E->isSame(VL)) {
29594ba319b5SDimitry Andric Value *V = vectorizeTree(E);
29604ba319b5SDimitry Andric if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
29614ba319b5SDimitry Andric // We need to get the vectorized value but without shuffle.
29624ba319b5SDimitry Andric if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
29634ba319b5SDimitry Andric V = SV->getOperand(0);
29644ba319b5SDimitry Andric } else {
29654ba319b5SDimitry Andric // Reshuffle to get only unique values.
29664ba319b5SDimitry Andric SmallVector<unsigned, 4> UniqueIdxs;
29674ba319b5SDimitry Andric SmallSet<unsigned, 4> UsedIdxs;
29684ba319b5SDimitry Andric for(unsigned Idx : E->ReuseShuffleIndices)
29694ba319b5SDimitry Andric if (UsedIdxs.insert(Idx).second)
29704ba319b5SDimitry Andric UniqueIdxs.emplace_back(Idx);
29714ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
29724ba319b5SDimitry Andric UniqueIdxs);
29734ba319b5SDimitry Andric }
29744ba319b5SDimitry Andric }
29754ba319b5SDimitry Andric return V;
29764ba319b5SDimitry Andric }
29772cab237bSDimitry Andric }
29782cab237bSDimitry Andric }
29792cab237bSDimitry Andric
29802cab237bSDimitry Andric Type *ScalarTy = S.OpValue->getType();
29812cab237bSDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2982f785676fSDimitry Andric ScalarTy = SI->getValueOperand()->getType();
29834ba319b5SDimitry Andric
29844ba319b5SDimitry Andric // Check that every instruction appears once in this bundle.
29854ba319b5SDimitry Andric SmallVector<unsigned, 4> ReuseShuffleIndicies;
29864ba319b5SDimitry Andric SmallVector<Value *, 4> UniqueValues;
29874ba319b5SDimitry Andric if (VL.size() > 2) {
29884ba319b5SDimitry Andric DenseMap<Value *, unsigned> UniquePositions;
29894ba319b5SDimitry Andric for (Value *V : VL) {
29904ba319b5SDimitry Andric auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
29914ba319b5SDimitry Andric ReuseShuffleIndicies.emplace_back(Res.first->second);
29924ba319b5SDimitry Andric if (Res.second || isa<Constant>(V))
29934ba319b5SDimitry Andric UniqueValues.emplace_back(V);
29944ba319b5SDimitry Andric }
29954ba319b5SDimitry Andric // Do not shuffle single element or if number of unique values is not power
29964ba319b5SDimitry Andric // of 2.
29974ba319b5SDimitry Andric if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
29984ba319b5SDimitry Andric !llvm::isPowerOf2_32(UniqueValues.size()))
29994ba319b5SDimitry Andric ReuseShuffleIndicies.clear();
30004ba319b5SDimitry Andric else
30014ba319b5SDimitry Andric VL = UniqueValues;
30024ba319b5SDimitry Andric }
3003f785676fSDimitry Andric VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
3004f785676fSDimitry Andric
30054ba319b5SDimitry Andric Value *V = Gather(VL, VecTy);
30064ba319b5SDimitry Andric if (!ReuseShuffleIndicies.empty()) {
30074ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
30084ba319b5SDimitry Andric ReuseShuffleIndicies, "shuffle");
30094ba319b5SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) {
30104ba319b5SDimitry Andric GatherSeq.insert(I);
30114ba319b5SDimitry Andric CSEBlocks.insert(I->getParent());
30124ba319b5SDimitry Andric }
30134ba319b5SDimitry Andric }
30144ba319b5SDimitry Andric return V;
30154ba319b5SDimitry Andric }
30164ba319b5SDimitry Andric
inversePermutation(ArrayRef<unsigned> Indices,SmallVectorImpl<unsigned> & Mask)30174ba319b5SDimitry Andric static void inversePermutation(ArrayRef<unsigned> Indices,
30184ba319b5SDimitry Andric SmallVectorImpl<unsigned> &Mask) {
30194ba319b5SDimitry Andric Mask.clear();
30204ba319b5SDimitry Andric const unsigned E = Indices.size();
30214ba319b5SDimitry Andric Mask.resize(E);
30224ba319b5SDimitry Andric for (unsigned I = 0; I < E; ++I)
30234ba319b5SDimitry Andric Mask[Indices[I]] = I;
3024f785676fSDimitry Andric }
3025f785676fSDimitry Andric
vectorizeTree(TreeEntry * E)3026da09e106SDimitry Andric Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
3027f785676fSDimitry Andric IRBuilder<>::InsertPointGuard Guard(Builder);
3028f785676fSDimitry Andric
3029f785676fSDimitry Andric if (E->VectorizedValue) {
30304ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
3031f785676fSDimitry Andric return E->VectorizedValue;
3032f785676fSDimitry Andric }
3033f785676fSDimitry Andric
30342cab237bSDimitry Andric InstructionsState S = getSameOpcode(E->Scalars);
30354ba319b5SDimitry Andric Instruction *VL0 = cast<Instruction>(S.OpValue);
3036f785676fSDimitry Andric Type *ScalarTy = VL0->getType();
3037f785676fSDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
3038f785676fSDimitry Andric ScalarTy = SI->getValueOperand()->getType();
3039f785676fSDimitry Andric VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
3040f785676fSDimitry Andric
30414ba319b5SDimitry Andric bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
30424ba319b5SDimitry Andric
3043f785676fSDimitry Andric if (E->NeedToGather) {
30444ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3045fccc5558SDimitry Andric auto *V = Gather(E->Scalars, VecTy);
30464ba319b5SDimitry Andric if (NeedToShuffleReuses) {
30474ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
30484ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
30494ba319b5SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) {
30504ba319b5SDimitry Andric GatherSeq.insert(I);
30514ba319b5SDimitry Andric CSEBlocks.insert(I->getParent());
30524ba319b5SDimitry Andric }
30534ba319b5SDimitry Andric }
3054fccc5558SDimitry Andric E->VectorizedValue = V;
3055fccc5558SDimitry Andric return V;
3056f785676fSDimitry Andric }
305739d628a0SDimitry Andric
30584ba319b5SDimitry Andric unsigned ShuffleOrOp = S.isAltShuffle() ?
30594ba319b5SDimitry Andric (unsigned) Instruction::ShuffleVector : S.getOpcode();
30602cab237bSDimitry Andric switch (ShuffleOrOp) {
3061f785676fSDimitry Andric case Instruction::PHI: {
3062f785676fSDimitry Andric PHINode *PH = dyn_cast<PHINode>(VL0);
3063f785676fSDimitry Andric Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
3064f785676fSDimitry Andric Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3065f785676fSDimitry Andric PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
30664ba319b5SDimitry Andric Value *V = NewPhi;
30674ba319b5SDimitry Andric if (NeedToShuffleReuses) {
30684ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
30694ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
30704ba319b5SDimitry Andric }
30714ba319b5SDimitry Andric E->VectorizedValue = V;
3072f785676fSDimitry Andric
3073f785676fSDimitry Andric // PHINodes may have multiple entries from the same block. We want to
3074f785676fSDimitry Andric // visit every block once.
30754ba319b5SDimitry Andric SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3076f785676fSDimitry Andric
3077f785676fSDimitry Andric for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
3078f785676fSDimitry Andric ValueList Operands;
3079f785676fSDimitry Andric BasicBlock *IBB = PH->getIncomingBlock(i);
3080f785676fSDimitry Andric
308139d628a0SDimitry Andric if (!VisitedBBs.insert(IBB).second) {
3082f785676fSDimitry Andric NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
3083f785676fSDimitry Andric continue;
3084f785676fSDimitry Andric }
3085f785676fSDimitry Andric
3086f785676fSDimitry Andric // Prepare the operand vector.
3087875ed548SDimitry Andric for (Value *V : E->Scalars)
3088875ed548SDimitry Andric Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
3089f785676fSDimitry Andric
3090f785676fSDimitry Andric Builder.SetInsertPoint(IBB->getTerminator());
3091f785676fSDimitry Andric Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3092da09e106SDimitry Andric Value *Vec = vectorizeTree(Operands);
3093f785676fSDimitry Andric NewPhi->addIncoming(Vec, IBB);
3094f785676fSDimitry Andric }
3095f785676fSDimitry Andric
3096f785676fSDimitry Andric assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
3097f785676fSDimitry Andric "Invalid number of incoming values");
30984ba319b5SDimitry Andric return V;
3099f785676fSDimitry Andric }
3100f785676fSDimitry Andric
3101f785676fSDimitry Andric case Instruction::ExtractElement: {
31024ba319b5SDimitry Andric if (!E->NeedToGather) {
3103f785676fSDimitry Andric Value *V = VL0->getOperand(0);
31044ba319b5SDimitry Andric if (!E->ReorderIndices.empty()) {
31054ba319b5SDimitry Andric OrdersType Mask;
31064ba319b5SDimitry Andric inversePermutation(E->ReorderIndices, Mask);
31074ba319b5SDimitry Andric Builder.SetInsertPoint(VL0);
31084ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
31094ba319b5SDimitry Andric "reorder_shuffle");
31104ba319b5SDimitry Andric }
31114ba319b5SDimitry Andric if (NeedToShuffleReuses) {
31124ba319b5SDimitry Andric // TODO: Merge this shuffle with the ReorderShuffleMask.
31134ba319b5SDimitry Andric if (E->ReorderIndices.empty())
31144ba319b5SDimitry Andric Builder.SetInsertPoint(VL0);
31154ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
31164ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
31174ba319b5SDimitry Andric }
3118f785676fSDimitry Andric E->VectorizedValue = V;
3119f785676fSDimitry Andric return V;
3120f785676fSDimitry Andric }
31214ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3122fccc5558SDimitry Andric auto *V = Gather(E->Scalars, VecTy);
31234ba319b5SDimitry Andric if (NeedToShuffleReuses) {
31244ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
31254ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
31264ba319b5SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) {
31274ba319b5SDimitry Andric GatherSeq.insert(I);
31284ba319b5SDimitry Andric CSEBlocks.insert(I->getParent());
31294ba319b5SDimitry Andric }
31304ba319b5SDimitry Andric }
3131fccc5558SDimitry Andric E->VectorizedValue = V;
3132fccc5558SDimitry Andric return V;
3133f785676fSDimitry Andric }
31343ca95b02SDimitry Andric case Instruction::ExtractValue: {
31354ba319b5SDimitry Andric if (!E->NeedToGather) {
31363ca95b02SDimitry Andric LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
31373ca95b02SDimitry Andric Builder.SetInsertPoint(LI);
31383ca95b02SDimitry Andric PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
31393ca95b02SDimitry Andric Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
31403ca95b02SDimitry Andric LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
31414ba319b5SDimitry Andric Value *NewV = propagateMetadata(V, E->Scalars);
31424ba319b5SDimitry Andric if (!E->ReorderIndices.empty()) {
31434ba319b5SDimitry Andric OrdersType Mask;
31444ba319b5SDimitry Andric inversePermutation(E->ReorderIndices, Mask);
31454ba319b5SDimitry Andric NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
31464ba319b5SDimitry Andric "reorder_shuffle");
31473ca95b02SDimitry Andric }
31484ba319b5SDimitry Andric if (NeedToShuffleReuses) {
31494ba319b5SDimitry Andric // TODO: Merge this shuffle with the ReorderShuffleMask.
31504ba319b5SDimitry Andric NewV = Builder.CreateShuffleVector(
31514ba319b5SDimitry Andric NewV, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle");
31524ba319b5SDimitry Andric }
31534ba319b5SDimitry Andric E->VectorizedValue = NewV;
31544ba319b5SDimitry Andric return NewV;
31554ba319b5SDimitry Andric }
31564ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3157fccc5558SDimitry Andric auto *V = Gather(E->Scalars, VecTy);
31584ba319b5SDimitry Andric if (NeedToShuffleReuses) {
31594ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
31604ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
31614ba319b5SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) {
31624ba319b5SDimitry Andric GatherSeq.insert(I);
31634ba319b5SDimitry Andric CSEBlocks.insert(I->getParent());
31644ba319b5SDimitry Andric }
31654ba319b5SDimitry Andric }
3166fccc5558SDimitry Andric E->VectorizedValue = V;
3167fccc5558SDimitry Andric return V;
31683ca95b02SDimitry Andric }
3169f785676fSDimitry Andric case Instruction::ZExt:
3170f785676fSDimitry Andric case Instruction::SExt:
3171f785676fSDimitry Andric case Instruction::FPToUI:
3172f785676fSDimitry Andric case Instruction::FPToSI:
3173f785676fSDimitry Andric case Instruction::FPExt:
3174f785676fSDimitry Andric case Instruction::PtrToInt:
3175f785676fSDimitry Andric case Instruction::IntToPtr:
3176f785676fSDimitry Andric case Instruction::SIToFP:
3177f785676fSDimitry Andric case Instruction::UIToFP:
3178f785676fSDimitry Andric case Instruction::Trunc:
3179f785676fSDimitry Andric case Instruction::FPTrunc:
3180f785676fSDimitry Andric case Instruction::BitCast: {
3181f785676fSDimitry Andric ValueList INVL;
3182875ed548SDimitry Andric for (Value *V : E->Scalars)
3183875ed548SDimitry Andric INVL.push_back(cast<Instruction>(V)->getOperand(0));
3184f785676fSDimitry Andric
31854ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3186f785676fSDimitry Andric
3187da09e106SDimitry Andric Value *InVec = vectorizeTree(INVL);
3188f785676fSDimitry Andric
31894ba319b5SDimitry Andric if (E->VectorizedValue) {
31904ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
31914ba319b5SDimitry Andric return E->VectorizedValue;
31924ba319b5SDimitry Andric }
3193f785676fSDimitry Andric
3194f785676fSDimitry Andric CastInst *CI = dyn_cast<CastInst>(VL0);
3195f785676fSDimitry Andric Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
31964ba319b5SDimitry Andric if (NeedToShuffleReuses) {
31974ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
31984ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
31994ba319b5SDimitry Andric }
3200f785676fSDimitry Andric E->VectorizedValue = V;
320139d628a0SDimitry Andric ++NumVectorInstructions;
3202f785676fSDimitry Andric return V;
3203f785676fSDimitry Andric }
3204f785676fSDimitry Andric case Instruction::FCmp:
3205f785676fSDimitry Andric case Instruction::ICmp: {
3206f785676fSDimitry Andric ValueList LHSV, RHSV;
3207875ed548SDimitry Andric for (Value *V : E->Scalars) {
3208875ed548SDimitry Andric LHSV.push_back(cast<Instruction>(V)->getOperand(0));
3209875ed548SDimitry Andric RHSV.push_back(cast<Instruction>(V)->getOperand(1));
3210f785676fSDimitry Andric }
3211f785676fSDimitry Andric
32124ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3213f785676fSDimitry Andric
3214da09e106SDimitry Andric Value *L = vectorizeTree(LHSV);
3215da09e106SDimitry Andric Value *R = vectorizeTree(RHSV);
3216f785676fSDimitry Andric
32174ba319b5SDimitry Andric if (E->VectorizedValue) {
32184ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
32194ba319b5SDimitry Andric return E->VectorizedValue;
32204ba319b5SDimitry Andric }
3221f785676fSDimitry Andric
3222ff0cc061SDimitry Andric CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3223f785676fSDimitry Andric Value *V;
32244ba319b5SDimitry Andric if (S.getOpcode() == Instruction::FCmp)
3225f785676fSDimitry Andric V = Builder.CreateFCmp(P0, L, R);
3226f785676fSDimitry Andric else
3227f785676fSDimitry Andric V = Builder.CreateICmp(P0, L, R);
3228f785676fSDimitry Andric
32294ba319b5SDimitry Andric propagateIRFlags(V, E->Scalars, VL0);
32304ba319b5SDimitry Andric if (NeedToShuffleReuses) {
32314ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
32324ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
32334ba319b5SDimitry Andric }
3234f785676fSDimitry Andric E->VectorizedValue = V;
323539d628a0SDimitry Andric ++NumVectorInstructions;
3236f785676fSDimitry Andric return V;
3237f785676fSDimitry Andric }
3238f785676fSDimitry Andric case Instruction::Select: {
3239f785676fSDimitry Andric ValueList TrueVec, FalseVec, CondVec;
3240875ed548SDimitry Andric for (Value *V : E->Scalars) {
3241875ed548SDimitry Andric CondVec.push_back(cast<Instruction>(V)->getOperand(0));
3242875ed548SDimitry Andric TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
3243875ed548SDimitry Andric FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
3244f785676fSDimitry Andric }
3245f785676fSDimitry Andric
32464ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3247f785676fSDimitry Andric
3248da09e106SDimitry Andric Value *Cond = vectorizeTree(CondVec);
3249da09e106SDimitry Andric Value *True = vectorizeTree(TrueVec);
3250da09e106SDimitry Andric Value *False = vectorizeTree(FalseVec);
3251f785676fSDimitry Andric
32524ba319b5SDimitry Andric if (E->VectorizedValue) {
32534ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
32544ba319b5SDimitry Andric return E->VectorizedValue;
32554ba319b5SDimitry Andric }
3256f785676fSDimitry Andric
3257f785676fSDimitry Andric Value *V = Builder.CreateSelect(Cond, True, False);
32584ba319b5SDimitry Andric if (NeedToShuffleReuses) {
32594ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
32604ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
32614ba319b5SDimitry Andric }
3262f785676fSDimitry Andric E->VectorizedValue = V;
326339d628a0SDimitry Andric ++NumVectorInstructions;
3264f785676fSDimitry Andric return V;
3265f785676fSDimitry Andric }
3266f785676fSDimitry Andric case Instruction::Add:
3267f785676fSDimitry Andric case Instruction::FAdd:
3268f785676fSDimitry Andric case Instruction::Sub:
3269f785676fSDimitry Andric case Instruction::FSub:
3270f785676fSDimitry Andric case Instruction::Mul:
3271f785676fSDimitry Andric case Instruction::FMul:
3272f785676fSDimitry Andric case Instruction::UDiv:
3273f785676fSDimitry Andric case Instruction::SDiv:
3274f785676fSDimitry Andric case Instruction::FDiv:
3275f785676fSDimitry Andric case Instruction::URem:
3276f785676fSDimitry Andric case Instruction::SRem:
3277f785676fSDimitry Andric case Instruction::FRem:
3278f785676fSDimitry Andric case Instruction::Shl:
3279f785676fSDimitry Andric case Instruction::LShr:
3280f785676fSDimitry Andric case Instruction::AShr:
3281f785676fSDimitry Andric case Instruction::And:
3282f785676fSDimitry Andric case Instruction::Or:
3283f785676fSDimitry Andric case Instruction::Xor: {
3284f785676fSDimitry Andric ValueList LHSVL, RHSVL;
3285f785676fSDimitry Andric if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
32864ba319b5SDimitry Andric reorderInputsAccordingToOpcode(S.getOpcode(), E->Scalars, LHSVL,
32872cab237bSDimitry Andric RHSVL);
3288f785676fSDimitry Andric else
3289875ed548SDimitry Andric for (Value *V : E->Scalars) {
32902cab237bSDimitry Andric auto *I = cast<Instruction>(V);
32912cab237bSDimitry Andric LHSVL.push_back(I->getOperand(0));
32922cab237bSDimitry Andric RHSVL.push_back(I->getOperand(1));
3293f785676fSDimitry Andric }
3294f785676fSDimitry Andric
32954ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3296f785676fSDimitry Andric
3297da09e106SDimitry Andric Value *LHS = vectorizeTree(LHSVL);
3298da09e106SDimitry Andric Value *RHS = vectorizeTree(RHSVL);
3299f785676fSDimitry Andric
33004ba319b5SDimitry Andric if (E->VectorizedValue) {
33014ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
33024ba319b5SDimitry Andric return E->VectorizedValue;
33034ba319b5SDimitry Andric }
3304f785676fSDimitry Andric
33052cab237bSDimitry Andric Value *V = Builder.CreateBinOp(
33064ba319b5SDimitry Andric static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
33074ba319b5SDimitry Andric propagateIRFlags(V, E->Scalars, VL0);
33084ba319b5SDimitry Andric if (auto *I = dyn_cast<Instruction>(V))
33094ba319b5SDimitry Andric V = propagateMetadata(I, E->Scalars);
3310f785676fSDimitry Andric
33114ba319b5SDimitry Andric if (NeedToShuffleReuses) {
33124ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
33134ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
33144ba319b5SDimitry Andric }
33154ba319b5SDimitry Andric E->VectorizedValue = V;
33164ba319b5SDimitry Andric ++NumVectorInstructions;
3317f785676fSDimitry Andric
3318f785676fSDimitry Andric return V;
3319f785676fSDimitry Andric }
3320f785676fSDimitry Andric case Instruction::Load: {
3321f785676fSDimitry Andric // Loads are inserted at the head of the tree because we don't want to
3322f785676fSDimitry Andric // sink them all the way down past store instructions.
33234ba319b5SDimitry Andric bool IsReorder = !E->ReorderIndices.empty();
33244ba319b5SDimitry Andric if (IsReorder) {
33254ba319b5SDimitry Andric S = getSameOpcode(E->Scalars, E->ReorderIndices.front());
33264ba319b5SDimitry Andric VL0 = cast<Instruction>(S.OpValue);
33274ba319b5SDimitry Andric }
33284ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3329f785676fSDimitry Andric
3330da09e106SDimitry Andric LoadInst *LI = cast<LoadInst>(VL0);
333139d628a0SDimitry Andric Type *ScalarLoadTy = LI->getType();
3332f785676fSDimitry Andric unsigned AS = LI->getPointerAddressSpace();
3333f785676fSDimitry Andric
3334f785676fSDimitry Andric Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
3335f785676fSDimitry Andric VecTy->getPointerTo(AS));
333639d628a0SDimitry Andric
333739d628a0SDimitry Andric // The pointer operand uses an in-tree scalar so we add the new BitCast to
333839d628a0SDimitry Andric // ExternalUses list to make sure that an extract will be generated in the
333939d628a0SDimitry Andric // future.
3340a580b014SDimitry Andric Value *PO = LI->getPointerOperand();
3341a580b014SDimitry Andric if (getTreeEntry(PO))
3342a580b014SDimitry Andric ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
334339d628a0SDimitry Andric
3344f785676fSDimitry Andric unsigned Alignment = LI->getAlignment();
3345f785676fSDimitry Andric LI = Builder.CreateLoad(VecPtr);
3346ff0cc061SDimitry Andric if (!Alignment) {
33473ca95b02SDimitry Andric Alignment = DL->getABITypeAlignment(ScalarLoadTy);
3348ff0cc061SDimitry Andric }
3349f785676fSDimitry Andric LI->setAlignment(Alignment);
33504ba319b5SDimitry Andric Value *V = propagateMetadata(LI, E->Scalars);
33514ba319b5SDimitry Andric if (IsReorder) {
33524ba319b5SDimitry Andric OrdersType Mask;
33534ba319b5SDimitry Andric inversePermutation(E->ReorderIndices, Mask);
33544ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
33554ba319b5SDimitry Andric Mask, "reorder_shuffle");
33564ba319b5SDimitry Andric }
33574ba319b5SDimitry Andric if (NeedToShuffleReuses) {
33584ba319b5SDimitry Andric // TODO: Merge this shuffle with the ReorderShuffleMask.
33594ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
33604ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
33614ba319b5SDimitry Andric }
33624ba319b5SDimitry Andric E->VectorizedValue = V;
336339d628a0SDimitry Andric ++NumVectorInstructions;
33644ba319b5SDimitry Andric return V;
3365f785676fSDimitry Andric }
3366f785676fSDimitry Andric case Instruction::Store: {
3367f785676fSDimitry Andric StoreInst *SI = cast<StoreInst>(VL0);
3368f785676fSDimitry Andric unsigned Alignment = SI->getAlignment();
3369f785676fSDimitry Andric unsigned AS = SI->getPointerAddressSpace();
3370f785676fSDimitry Andric
33712cab237bSDimitry Andric ValueList ScalarStoreValues;
3372875ed548SDimitry Andric for (Value *V : E->Scalars)
33732cab237bSDimitry Andric ScalarStoreValues.push_back(cast<StoreInst>(V)->getValueOperand());
3374f785676fSDimitry Andric
33754ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
3376f785676fSDimitry Andric
3377da09e106SDimitry Andric Value *VecValue = vectorizeTree(ScalarStoreValues);
33782cab237bSDimitry Andric Value *ScalarPtr = SI->getPointerOperand();
33792cab237bSDimitry Andric Value *VecPtr = Builder.CreateBitCast(ScalarPtr, VecTy->getPointerTo(AS));
33804ba319b5SDimitry Andric StoreInst *ST = Builder.CreateStore(VecValue, VecPtr);
338139d628a0SDimitry Andric
33822cab237bSDimitry Andric // The pointer operand uses an in-tree scalar, so add the new BitCast to
33832cab237bSDimitry Andric // ExternalUses to make sure that an extract will be generated in the
338439d628a0SDimitry Andric // future.
33852cab237bSDimitry Andric if (getTreeEntry(ScalarPtr))
33862cab237bSDimitry Andric ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
338739d628a0SDimitry Andric
33882cab237bSDimitry Andric if (!Alignment)
33893ca95b02SDimitry Andric Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
33902cab237bSDimitry Andric
33914ba319b5SDimitry Andric ST->setAlignment(Alignment);
33924ba319b5SDimitry Andric Value *V = propagateMetadata(ST, E->Scalars);
33934ba319b5SDimitry Andric if (NeedToShuffleReuses) {
33944ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
33954ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
33964ba319b5SDimitry Andric }
33974ba319b5SDimitry Andric E->VectorizedValue = V;
339839d628a0SDimitry Andric ++NumVectorInstructions;
33994ba319b5SDimitry Andric return V;
3400f785676fSDimitry Andric }
340191bc56edSDimitry Andric case Instruction::GetElementPtr: {
34024ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
340391bc56edSDimitry Andric
340491bc56edSDimitry Andric ValueList Op0VL;
3405875ed548SDimitry Andric for (Value *V : E->Scalars)
3406875ed548SDimitry Andric Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
340791bc56edSDimitry Andric
3408da09e106SDimitry Andric Value *Op0 = vectorizeTree(Op0VL);
340991bc56edSDimitry Andric
341091bc56edSDimitry Andric std::vector<Value *> OpVecs;
341191bc56edSDimitry Andric for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
341291bc56edSDimitry Andric ++j) {
341391bc56edSDimitry Andric ValueList OpVL;
3414875ed548SDimitry Andric for (Value *V : E->Scalars)
3415875ed548SDimitry Andric OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
341691bc56edSDimitry Andric
3417da09e106SDimitry Andric Value *OpVec = vectorizeTree(OpVL);
341891bc56edSDimitry Andric OpVecs.push_back(OpVec);
341991bc56edSDimitry Andric }
342091bc56edSDimitry Andric
3421ff0cc061SDimitry Andric Value *V = Builder.CreateGEP(
3422ff0cc061SDimitry Andric cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
34234ba319b5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(V))
34244ba319b5SDimitry Andric V = propagateMetadata(I, E->Scalars);
34254ba319b5SDimitry Andric
34264ba319b5SDimitry Andric if (NeedToShuffleReuses) {
34274ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
34284ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
34294ba319b5SDimitry Andric }
343091bc56edSDimitry Andric E->VectorizedValue = V;
343139d628a0SDimitry Andric ++NumVectorInstructions;
343291bc56edSDimitry Andric
343391bc56edSDimitry Andric return V;
343491bc56edSDimitry Andric }
343591bc56edSDimitry Andric case Instruction::Call: {
343691bc56edSDimitry Andric CallInst *CI = cast<CallInst>(VL0);
34374ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
343891bc56edSDimitry Andric Function *FI;
343991bc56edSDimitry Andric Intrinsic::ID IID = Intrinsic::not_intrinsic;
344039d628a0SDimitry Andric Value *ScalarArg = nullptr;
344191bc56edSDimitry Andric if (CI && (FI = CI->getCalledFunction())) {
3442ff0cc061SDimitry Andric IID = FI->getIntrinsicID();
344391bc56edSDimitry Andric }
344491bc56edSDimitry Andric std::vector<Value *> OpVecs;
344591bc56edSDimitry Andric for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
344691bc56edSDimitry Andric ValueList OpVL;
344791bc56edSDimitry Andric // ctlz,cttz and powi are special intrinsics whose second argument is
344891bc56edSDimitry Andric // a scalar. This argument should not be vectorized.
344991bc56edSDimitry Andric if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
34502cab237bSDimitry Andric CallInst *CEI = cast<CallInst>(VL0);
345139d628a0SDimitry Andric ScalarArg = CEI->getArgOperand(j);
345291bc56edSDimitry Andric OpVecs.push_back(CEI->getArgOperand(j));
345391bc56edSDimitry Andric continue;
345491bc56edSDimitry Andric }
3455875ed548SDimitry Andric for (Value *V : E->Scalars) {
3456875ed548SDimitry Andric CallInst *CEI = cast<CallInst>(V);
345791bc56edSDimitry Andric OpVL.push_back(CEI->getArgOperand(j));
345891bc56edSDimitry Andric }
345991bc56edSDimitry Andric
3460da09e106SDimitry Andric Value *OpVec = vectorizeTree(OpVL);
34614ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
346291bc56edSDimitry Andric OpVecs.push_back(OpVec);
346391bc56edSDimitry Andric }
346491bc56edSDimitry Andric
346591bc56edSDimitry Andric Module *M = F->getParent();
34663ca95b02SDimitry Andric Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
346791bc56edSDimitry Andric Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
346891bc56edSDimitry Andric Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
34693ca95b02SDimitry Andric SmallVector<OperandBundleDef, 1> OpBundles;
34703ca95b02SDimitry Andric CI->getOperandBundlesAsDefs(OpBundles);
34713ca95b02SDimitry Andric Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
347239d628a0SDimitry Andric
347339d628a0SDimitry Andric // The scalar argument uses an in-tree scalar so we add the new vectorized
347439d628a0SDimitry Andric // call to ExternalUses list to make sure that an extract will be
347539d628a0SDimitry Andric // generated in the future.
3476a580b014SDimitry Andric if (ScalarArg && getTreeEntry(ScalarArg))
347739d628a0SDimitry Andric ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
347839d628a0SDimitry Andric
34794ba319b5SDimitry Andric propagateIRFlags(V, E->Scalars, VL0);
34804ba319b5SDimitry Andric if (NeedToShuffleReuses) {
34814ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
34824ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
34834ba319b5SDimitry Andric }
348491bc56edSDimitry Andric E->VectorizedValue = V;
348539d628a0SDimitry Andric ++NumVectorInstructions;
348691bc56edSDimitry Andric return V;
348791bc56edSDimitry Andric }
348891bc56edSDimitry Andric case Instruction::ShuffleVector: {
348991bc56edSDimitry Andric ValueList LHSVL, RHSVL;
34904ba319b5SDimitry Andric assert(S.isAltShuffle() &&
34914ba319b5SDimitry Andric ((Instruction::isBinaryOp(S.getOpcode()) &&
34924ba319b5SDimitry Andric Instruction::isBinaryOp(S.getAltOpcode())) ||
34934ba319b5SDimitry Andric (Instruction::isCast(S.getOpcode()) &&
34944ba319b5SDimitry Andric Instruction::isCast(S.getAltOpcode()))) &&
34952cab237bSDimitry Andric "Invalid Shuffle Vector Operand");
349691bc56edSDimitry Andric
34974ba319b5SDimitry Andric Value *LHS, *RHS;
34984ba319b5SDimitry Andric if (Instruction::isBinaryOp(S.getOpcode())) {
34994ba319b5SDimitry Andric reorderAltShuffleOperands(S, E->Scalars, LHSVL, RHSVL);
35004ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
35014ba319b5SDimitry Andric LHS = vectorizeTree(LHSVL);
35024ba319b5SDimitry Andric RHS = vectorizeTree(RHSVL);
35034ba319b5SDimitry Andric } else {
35044ba319b5SDimitry Andric ValueList INVL;
35054ba319b5SDimitry Andric for (Value *V : E->Scalars)
35064ba319b5SDimitry Andric INVL.push_back(cast<Instruction>(V)->getOperand(0));
35074ba319b5SDimitry Andric setInsertPointAfterBundle(E->Scalars, S);
35084ba319b5SDimitry Andric LHS = vectorizeTree(INVL);
35094ba319b5SDimitry Andric }
351091bc56edSDimitry Andric
35114ba319b5SDimitry Andric if (E->VectorizedValue) {
35124ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
35134ba319b5SDimitry Andric return E->VectorizedValue;
35144ba319b5SDimitry Andric }
351591bc56edSDimitry Andric
35164ba319b5SDimitry Andric Value *V0, *V1;
35174ba319b5SDimitry Andric if (Instruction::isBinaryOp(S.getOpcode())) {
35184ba319b5SDimitry Andric V0 = Builder.CreateBinOp(
35194ba319b5SDimitry Andric static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
35204ba319b5SDimitry Andric V1 = Builder.CreateBinOp(
35214ba319b5SDimitry Andric static_cast<Instruction::BinaryOps>(S.getAltOpcode()), LHS, RHS);
35224ba319b5SDimitry Andric } else {
35234ba319b5SDimitry Andric V0 = Builder.CreateCast(
35244ba319b5SDimitry Andric static_cast<Instruction::CastOps>(S.getOpcode()), LHS, VecTy);
35254ba319b5SDimitry Andric V1 = Builder.CreateCast(
35264ba319b5SDimitry Andric static_cast<Instruction::CastOps>(S.getAltOpcode()), LHS, VecTy);
35274ba319b5SDimitry Andric }
352891bc56edSDimitry Andric
352939d628a0SDimitry Andric // Create shuffle to take alternate operations from the vector.
35304ba319b5SDimitry Andric // Also, gather up main and alt scalar ops to propagate IR flags to
353139d628a0SDimitry Andric // each vector operation.
35324ba319b5SDimitry Andric ValueList OpScalars, AltScalars;
353391bc56edSDimitry Andric unsigned e = E->Scalars.size();
353439d628a0SDimitry Andric SmallVector<Constant *, 8> Mask(e);
353591bc56edSDimitry Andric for (unsigned i = 0; i < e; ++i) {
35364ba319b5SDimitry Andric auto *OpInst = cast<Instruction>(E->Scalars[i]);
35374ba319b5SDimitry Andric assert(S.isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
35384ba319b5SDimitry Andric if (OpInst->getOpcode() == S.getAltOpcode()) {
353991bc56edSDimitry Andric Mask[i] = Builder.getInt32(e + i);
35404ba319b5SDimitry Andric AltScalars.push_back(E->Scalars[i]);
354139d628a0SDimitry Andric } else {
354291bc56edSDimitry Andric Mask[i] = Builder.getInt32(i);
35434ba319b5SDimitry Andric OpScalars.push_back(E->Scalars[i]);
354439d628a0SDimitry Andric }
354591bc56edSDimitry Andric }
354691bc56edSDimitry Andric
354791bc56edSDimitry Andric Value *ShuffleMask = ConstantVector::get(Mask);
35484ba319b5SDimitry Andric propagateIRFlags(V0, OpScalars);
35494ba319b5SDimitry Andric propagateIRFlags(V1, AltScalars);
355091bc56edSDimitry Andric
355191bc56edSDimitry Andric Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
35524ba319b5SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(V))
35534ba319b5SDimitry Andric V = propagateMetadata(I, E->Scalars);
35544ba319b5SDimitry Andric if (NeedToShuffleReuses) {
35554ba319b5SDimitry Andric V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
35564ba319b5SDimitry Andric E->ReuseShuffleIndices, "shuffle");
35574ba319b5SDimitry Andric }
355891bc56edSDimitry Andric E->VectorizedValue = V;
355939d628a0SDimitry Andric ++NumVectorInstructions;
356091bc56edSDimitry Andric
356191bc56edSDimitry Andric return V;
356291bc56edSDimitry Andric }
3563f785676fSDimitry Andric default:
3564f785676fSDimitry Andric llvm_unreachable("unknown inst");
3565f785676fSDimitry Andric }
356691bc56edSDimitry Andric return nullptr;
3567f785676fSDimitry Andric }
3568f785676fSDimitry Andric
vectorizeTree()3569f785676fSDimitry Andric Value *BoUpSLP::vectorizeTree() {
35707a7e6055SDimitry Andric ExtraValueToDebugLocsMap ExternallyUsedValues;
35717a7e6055SDimitry Andric return vectorizeTree(ExternallyUsedValues);
35727a7e6055SDimitry Andric }
35737a7e6055SDimitry Andric
35747a7e6055SDimitry Andric Value *
vectorizeTree(ExtraValueToDebugLocsMap & ExternallyUsedValues)35757a7e6055SDimitry Andric BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
357639d628a0SDimitry Andric // All blocks must be scheduled before any instructions are inserted.
357739d628a0SDimitry Andric for (auto &BSIter : BlocksSchedules) {
357839d628a0SDimitry Andric scheduleBlock(BSIter.second.get());
357939d628a0SDimitry Andric }
358039d628a0SDimitry Andric
35817d523365SDimitry Andric Builder.SetInsertPoint(&F->getEntryBlock().front());
35823ca95b02SDimitry Andric auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
35833ca95b02SDimitry Andric
35843ca95b02SDimitry Andric // If the vectorized tree can be rewritten in a smaller type, we truncate the
35853ca95b02SDimitry Andric // vectorized root. InstCombine will then rewrite the entire expression. We
35863ca95b02SDimitry Andric // sign extend the extracted values below.
35873ca95b02SDimitry Andric auto *ScalarRoot = VectorizableTree[0].Scalars[0];
35883ca95b02SDimitry Andric if (MinBWs.count(ScalarRoot)) {
35893ca95b02SDimitry Andric if (auto *I = dyn_cast<Instruction>(VectorRoot))
35903ca95b02SDimitry Andric Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
35913ca95b02SDimitry Andric auto BundleWidth = VectorizableTree[0].Scalars.size();
3592d88c1a5aSDimitry Andric auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
35933ca95b02SDimitry Andric auto *VecTy = VectorType::get(MinTy, BundleWidth);
35943ca95b02SDimitry Andric auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
35953ca95b02SDimitry Andric VectorizableTree[0].VectorizedValue = Trunc;
35963ca95b02SDimitry Andric }
3597f785676fSDimitry Andric
35984ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
35994ba319b5SDimitry Andric << " values .\n");
3600f785676fSDimitry Andric
3601d88c1a5aSDimitry Andric // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
3602d88c1a5aSDimitry Andric // specified by ScalarType.
3603d88c1a5aSDimitry Andric auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
3604d88c1a5aSDimitry Andric if (!MinBWs.count(ScalarRoot))
3605d88c1a5aSDimitry Andric return Ex;
3606d88c1a5aSDimitry Andric if (MinBWs[ScalarRoot].second)
3607d88c1a5aSDimitry Andric return Builder.CreateSExt(Ex, ScalarType);
3608d88c1a5aSDimitry Andric return Builder.CreateZExt(Ex, ScalarType);
3609d88c1a5aSDimitry Andric };
3610d88c1a5aSDimitry Andric
3611f785676fSDimitry Andric // Extract all of the elements with the external uses.
36123ca95b02SDimitry Andric for (const auto &ExternalUse : ExternalUses) {
36133ca95b02SDimitry Andric Value *Scalar = ExternalUse.Scalar;
36143ca95b02SDimitry Andric llvm::User *User = ExternalUse.User;
3615f785676fSDimitry Andric
3616f785676fSDimitry Andric // Skip users that we already RAUW. This happens when one instruction
3617f785676fSDimitry Andric // has multiple uses of the same value.
36187a7e6055SDimitry Andric if (User && !is_contained(Scalar->users(), User))
3619f785676fSDimitry Andric continue;
3620a580b014SDimitry Andric TreeEntry *E = getTreeEntry(Scalar);
3621a580b014SDimitry Andric assert(E && "Invalid scalar");
3622da09e106SDimitry Andric assert(!E->NeedToGather && "Extracting from a gather list");
3623f785676fSDimitry Andric
3624da09e106SDimitry Andric Value *Vec = E->VectorizedValue;
3625f785676fSDimitry Andric assert(Vec && "Can't find vectorizable value");
3626f785676fSDimitry Andric
36273ca95b02SDimitry Andric Value *Lane = Builder.getInt32(ExternalUse.Lane);
36287a7e6055SDimitry Andric // If User == nullptr, the Scalar is used as extra arg. Generate
36297a7e6055SDimitry Andric // ExtractElement instruction and update the record for this scalar in
36307a7e6055SDimitry Andric // ExternallyUsedValues.
36317a7e6055SDimitry Andric if (!User) {
36327a7e6055SDimitry Andric assert(ExternallyUsedValues.count(Scalar) &&
36337a7e6055SDimitry Andric "Scalar with nullptr as an external user must be registered in "
36347a7e6055SDimitry Andric "ExternallyUsedValues map");
36357a7e6055SDimitry Andric if (auto *VecI = dyn_cast<Instruction>(Vec)) {
36367a7e6055SDimitry Andric Builder.SetInsertPoint(VecI->getParent(),
36377a7e6055SDimitry Andric std::next(VecI->getIterator()));
36387a7e6055SDimitry Andric } else {
36397a7e6055SDimitry Andric Builder.SetInsertPoint(&F->getEntryBlock().front());
36407a7e6055SDimitry Andric }
36417a7e6055SDimitry Andric Value *Ex = Builder.CreateExtractElement(Vec, Lane);
36427a7e6055SDimitry Andric Ex = extend(ScalarRoot, Ex, Scalar->getType());
36437a7e6055SDimitry Andric CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
36447a7e6055SDimitry Andric auto &Locs = ExternallyUsedValues[Scalar];
36457a7e6055SDimitry Andric ExternallyUsedValues.insert({Ex, Locs});
36467a7e6055SDimitry Andric ExternallyUsedValues.erase(Scalar);
3647*b5893f02SDimitry Andric // Required to update internally referenced instructions.
3648*b5893f02SDimitry Andric Scalar->replaceAllUsesWith(Ex);
36497a7e6055SDimitry Andric continue;
36507a7e6055SDimitry Andric }
36517a7e6055SDimitry Andric
3652f785676fSDimitry Andric // Generate extracts for out-of-tree users.
3653f785676fSDimitry Andric // Find the insertion point for the extractelement lane.
36543ca95b02SDimitry Andric if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3655f785676fSDimitry Andric if (PHINode *PH = dyn_cast<PHINode>(User)) {
3656f785676fSDimitry Andric for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3657f785676fSDimitry Andric if (PH->getIncomingValue(i) == Scalar) {
3658*b5893f02SDimitry Andric Instruction *IncomingTerminator =
36593ca95b02SDimitry Andric PH->getIncomingBlock(i)->getTerminator();
36603ca95b02SDimitry Andric if (isa<CatchSwitchInst>(IncomingTerminator)) {
36613ca95b02SDimitry Andric Builder.SetInsertPoint(VecI->getParent(),
36623ca95b02SDimitry Andric std::next(VecI->getIterator()));
36633ca95b02SDimitry Andric } else {
3664f785676fSDimitry Andric Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
36653ca95b02SDimitry Andric }
3666f785676fSDimitry Andric Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3667d88c1a5aSDimitry Andric Ex = extend(ScalarRoot, Ex, Scalar->getType());
3668f785676fSDimitry Andric CSEBlocks.insert(PH->getIncomingBlock(i));
3669f785676fSDimitry Andric PH->setOperand(i, Ex);
3670f785676fSDimitry Andric }
3671f785676fSDimitry Andric }
3672f785676fSDimitry Andric } else {
3673f785676fSDimitry Andric Builder.SetInsertPoint(cast<Instruction>(User));
3674f785676fSDimitry Andric Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3675d88c1a5aSDimitry Andric Ex = extend(ScalarRoot, Ex, Scalar->getType());
3676f785676fSDimitry Andric CSEBlocks.insert(cast<Instruction>(User)->getParent());
3677f785676fSDimitry Andric User->replaceUsesOfWith(Scalar, Ex);
3678f785676fSDimitry Andric }
3679f785676fSDimitry Andric } else {
36807d523365SDimitry Andric Builder.SetInsertPoint(&F->getEntryBlock().front());
3681f785676fSDimitry Andric Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3682d88c1a5aSDimitry Andric Ex = extend(ScalarRoot, Ex, Scalar->getType());
3683f785676fSDimitry Andric CSEBlocks.insert(&F->getEntryBlock());
3684f785676fSDimitry Andric User->replaceUsesOfWith(Scalar, Ex);
3685f785676fSDimitry Andric }
3686f785676fSDimitry Andric
36874ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
3688f785676fSDimitry Andric }
3689f785676fSDimitry Andric
3690f785676fSDimitry Andric // For each vectorized value:
36913ca95b02SDimitry Andric for (TreeEntry &EIdx : VectorizableTree) {
36923ca95b02SDimitry Andric TreeEntry *Entry = &EIdx;
3693f785676fSDimitry Andric
3694f785676fSDimitry Andric // No need to handle users of gathered values.
3695f785676fSDimitry Andric if (Entry->NeedToGather)
3696f785676fSDimitry Andric continue;
3697f785676fSDimitry Andric
3698f785676fSDimitry Andric assert(Entry->VectorizedValue && "Can't find vectorizable value");
3699f785676fSDimitry Andric
37002cab237bSDimitry Andric // For each lane:
37012cab237bSDimitry Andric for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
37022cab237bSDimitry Andric Value *Scalar = Entry->Scalars[Lane];
37032cab237bSDimitry Andric
3704f785676fSDimitry Andric Type *Ty = Scalar->getType();
3705f785676fSDimitry Andric if (!Ty->isVoidTy()) {
370691bc56edSDimitry Andric #ifndef NDEBUG
370791bc56edSDimitry Andric for (User *U : Scalar->users()) {
37084ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
3709f785676fSDimitry Andric
371091bc56edSDimitry Andric // It is legal to replace users in the ignorelist by undef.
37112cab237bSDimitry Andric assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
3712f785676fSDimitry Andric "Replacing out-of-tree value with undef");
3713f785676fSDimitry Andric }
371491bc56edSDimitry Andric #endif
3715f785676fSDimitry Andric Value *Undef = UndefValue::get(Ty);
3716f785676fSDimitry Andric Scalar->replaceAllUsesWith(Undef);
3717f785676fSDimitry Andric }
37184ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
371939d628a0SDimitry Andric eraseInstruction(cast<Instruction>(Scalar));
3720f785676fSDimitry Andric }
3721f785676fSDimitry Andric }
3722f785676fSDimitry Andric
3723f785676fSDimitry Andric Builder.ClearInsertionPoint();
3724f785676fSDimitry Andric
3725f785676fSDimitry Andric return VectorizableTree[0].VectorizedValue;
3726f785676fSDimitry Andric }
3727f785676fSDimitry Andric
optimizeGatherSequence()37284ba319b5SDimitry Andric void BoUpSLP::optimizeGatherSequence() {
37294ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3730f785676fSDimitry Andric << " gather sequences instructions.\n");
3731f785676fSDimitry Andric // LICM InsertElementInst sequences.
37324ba319b5SDimitry Andric for (Instruction *I : GatherSeq) {
37334ba319b5SDimitry Andric if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(I))
3734f785676fSDimitry Andric continue;
3735f785676fSDimitry Andric
3736f785676fSDimitry Andric // Check if this block is inside a loop.
37374ba319b5SDimitry Andric Loop *L = LI->getLoopFor(I->getParent());
3738f785676fSDimitry Andric if (!L)
3739f785676fSDimitry Andric continue;
3740f785676fSDimitry Andric
3741f785676fSDimitry Andric // Check if it has a preheader.
3742f785676fSDimitry Andric BasicBlock *PreHeader = L->getLoopPreheader();
3743f785676fSDimitry Andric if (!PreHeader)
3744f785676fSDimitry Andric continue;
3745f785676fSDimitry Andric
3746f785676fSDimitry Andric // If the vector or the element that we insert into it are
3747f785676fSDimitry Andric // instructions that are defined in this basic block then we can't
3748f785676fSDimitry Andric // hoist this instruction.
37494ba319b5SDimitry Andric auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
37504ba319b5SDimitry Andric auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
37514ba319b5SDimitry Andric if (Op0 && L->contains(Op0))
3752f785676fSDimitry Andric continue;
37534ba319b5SDimitry Andric if (Op1 && L->contains(Op1))
3754f785676fSDimitry Andric continue;
3755f785676fSDimitry Andric
3756f785676fSDimitry Andric // We can hoist this instruction. Move it to the pre-header.
37574ba319b5SDimitry Andric I->moveBefore(PreHeader->getTerminator());
3758f785676fSDimitry Andric }
3759f785676fSDimitry Andric
37604ba319b5SDimitry Andric // Make a list of all reachable blocks in our CSE queue.
37614ba319b5SDimitry Andric SmallVector<const DomTreeNode *, 8> CSEWorkList;
37624ba319b5SDimitry Andric CSEWorkList.reserve(CSEBlocks.size());
37634ba319b5SDimitry Andric for (BasicBlock *BB : CSEBlocks)
37644ba319b5SDimitry Andric if (DomTreeNode *N = DT->getNode(BB)) {
37654ba319b5SDimitry Andric assert(DT->isReachableFromEntry(N));
37664ba319b5SDimitry Andric CSEWorkList.push_back(N);
37674ba319b5SDimitry Andric }
37684ba319b5SDimitry Andric
37694ba319b5SDimitry Andric // Sort blocks by domination. This ensures we visit a block after all blocks
37704ba319b5SDimitry Andric // dominating it are visited.
37714ba319b5SDimitry Andric std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
37724ba319b5SDimitry Andric [this](const DomTreeNode *A, const DomTreeNode *B) {
37734ba319b5SDimitry Andric return DT->properlyDominates(A, B);
37744ba319b5SDimitry Andric });
37754ba319b5SDimitry Andric
3776f785676fSDimitry Andric // Perform O(N^2) search over the gather sequences and merge identical
3777f785676fSDimitry Andric // instructions. TODO: We can further optimize this scan if we split the
3778f785676fSDimitry Andric // instructions into different buckets based on the insert lane.
3779f785676fSDimitry Andric SmallVector<Instruction *, 16> Visited;
37804ba319b5SDimitry Andric for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
37814ba319b5SDimitry Andric assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
37824ba319b5SDimitry Andric "Worklist not sorted properly!");
37834ba319b5SDimitry Andric BasicBlock *BB = (*I)->getBlock();
3784f785676fSDimitry Andric // For all instructions in blocks containing gather sequences:
3785f785676fSDimitry Andric for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
37867d523365SDimitry Andric Instruction *In = &*it++;
3787f785676fSDimitry Andric if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3788f785676fSDimitry Andric continue;
3789f785676fSDimitry Andric
3790f785676fSDimitry Andric // Check if we can replace this instruction with any of the
3791f785676fSDimitry Andric // visited instructions.
37923ca95b02SDimitry Andric for (Instruction *v : Visited) {
37933ca95b02SDimitry Andric if (In->isIdenticalTo(v) &&
37943ca95b02SDimitry Andric DT->dominates(v->getParent(), In->getParent())) {
37953ca95b02SDimitry Andric In->replaceAllUsesWith(v);
379639d628a0SDimitry Andric eraseInstruction(In);
379791bc56edSDimitry Andric In = nullptr;
3798f785676fSDimitry Andric break;
3799f785676fSDimitry Andric }
3800f785676fSDimitry Andric }
3801f785676fSDimitry Andric if (In) {
3802d88c1a5aSDimitry Andric assert(!is_contained(Visited, In));
3803f785676fSDimitry Andric Visited.push_back(In);
3804f785676fSDimitry Andric }
3805f785676fSDimitry Andric }
3806f785676fSDimitry Andric }
3807f785676fSDimitry Andric CSEBlocks.clear();
3808f785676fSDimitry Andric GatherSeq.clear();
3809f785676fSDimitry Andric }
3810f785676fSDimitry Andric
381139d628a0SDimitry Andric // Groups the instructions to a bundle (which is then a single scheduling entity)
381239d628a0SDimitry Andric // and schedules instructions until the bundle gets ready.
tryScheduleBundle(ArrayRef<Value * > VL,BoUpSLP * SLP,const InstructionsState & S)381339d628a0SDimitry Andric bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
38144ba319b5SDimitry Andric BoUpSLP *SLP,
38154ba319b5SDimitry Andric const InstructionsState &S) {
38164ba319b5SDimitry Andric if (isa<PHINode>(S.OpValue))
381739d628a0SDimitry Andric return true;
381839d628a0SDimitry Andric
381939d628a0SDimitry Andric // Initialize the instruction bundle.
382039d628a0SDimitry Andric Instruction *OldScheduleEnd = ScheduleEnd;
382139d628a0SDimitry Andric ScheduleData *PrevInBundle = nullptr;
382239d628a0SDimitry Andric ScheduleData *Bundle = nullptr;
382339d628a0SDimitry Andric bool ReSchedule = false;
38244ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n");
38257d523365SDimitry Andric
38267d523365SDimitry Andric // Make sure that the scheduling region contains all
38277d523365SDimitry Andric // instructions of the bundle.
382839d628a0SDimitry Andric for (Value *V : VL) {
38294ba319b5SDimitry Andric if (!extendSchedulingRegion(V, S))
38307d523365SDimitry Andric return false;
38317d523365SDimitry Andric }
38327d523365SDimitry Andric
38337d523365SDimitry Andric for (Value *V : VL) {
383439d628a0SDimitry Andric ScheduleData *BundleMember = getScheduleData(V);
383539d628a0SDimitry Andric assert(BundleMember &&
383639d628a0SDimitry Andric "no ScheduleData for bundle member (maybe not in same basic block)");
383739d628a0SDimitry Andric if (BundleMember->IsScheduled) {
383839d628a0SDimitry Andric // A bundle member was scheduled as single instruction before and now
383939d628a0SDimitry Andric // needs to be scheduled as part of the bundle. We just get rid of the
384039d628a0SDimitry Andric // existing schedule.
38414ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
384239d628a0SDimitry Andric << " was already scheduled\n");
384339d628a0SDimitry Andric ReSchedule = true;
384439d628a0SDimitry Andric }
384539d628a0SDimitry Andric assert(BundleMember->isSchedulingEntity() &&
384639d628a0SDimitry Andric "bundle member already part of other bundle");
384739d628a0SDimitry Andric if (PrevInBundle) {
384839d628a0SDimitry Andric PrevInBundle->NextInBundle = BundleMember;
384939d628a0SDimitry Andric } else {
385039d628a0SDimitry Andric Bundle = BundleMember;
385139d628a0SDimitry Andric }
385239d628a0SDimitry Andric BundleMember->UnscheduledDepsInBundle = 0;
385339d628a0SDimitry Andric Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
385439d628a0SDimitry Andric
385539d628a0SDimitry Andric // Group the instructions to a bundle.
385639d628a0SDimitry Andric BundleMember->FirstInBundle = Bundle;
385739d628a0SDimitry Andric PrevInBundle = BundleMember;
385839d628a0SDimitry Andric }
385939d628a0SDimitry Andric if (ScheduleEnd != OldScheduleEnd) {
386039d628a0SDimitry Andric // The scheduling region got new instructions at the lower end (or it is a
386139d628a0SDimitry Andric // new region for the first bundle). This makes it necessary to
386239d628a0SDimitry Andric // recalculate all dependencies.
386339d628a0SDimitry Andric // It is seldom that this needs to be done a second time after adding the
386439d628a0SDimitry Andric // initial bundle to the region.
386539d628a0SDimitry Andric for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
38662cab237bSDimitry Andric doForAllOpcodes(I, [](ScheduleData *SD) {
386739d628a0SDimitry Andric SD->clearDependencies();
38682cab237bSDimitry Andric });
386939d628a0SDimitry Andric }
387039d628a0SDimitry Andric ReSchedule = true;
387139d628a0SDimitry Andric }
387239d628a0SDimitry Andric if (ReSchedule) {
387339d628a0SDimitry Andric resetSchedule();
387439d628a0SDimitry Andric initialFillReadyList(ReadyInsts);
387539d628a0SDimitry Andric }
387639d628a0SDimitry Andric
38774ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
387839d628a0SDimitry Andric << BB->getName() << "\n");
387939d628a0SDimitry Andric
388039d628a0SDimitry Andric calculateDependencies(Bundle, true, SLP);
388139d628a0SDimitry Andric
388239d628a0SDimitry Andric // Now try to schedule the new bundle. As soon as the bundle is "ready" it
388339d628a0SDimitry Andric // means that there are no cyclic dependencies and we can schedule it.
388439d628a0SDimitry Andric // Note that's important that we don't "schedule" the bundle yet (see
388539d628a0SDimitry Andric // cancelScheduling).
388639d628a0SDimitry Andric while (!Bundle->isReady() && !ReadyInsts.empty()) {
388739d628a0SDimitry Andric
388839d628a0SDimitry Andric ScheduleData *pickedSD = ReadyInsts.back();
388939d628a0SDimitry Andric ReadyInsts.pop_back();
389039d628a0SDimitry Andric
389139d628a0SDimitry Andric if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
389239d628a0SDimitry Andric schedule(pickedSD, ReadyInsts);
389339d628a0SDimitry Andric }
389439d628a0SDimitry Andric }
38957d523365SDimitry Andric if (!Bundle->isReady()) {
38964ba319b5SDimitry Andric cancelScheduling(VL, S.OpValue);
38977d523365SDimitry Andric return false;
38987d523365SDimitry Andric }
38997d523365SDimitry Andric return true;
390039d628a0SDimitry Andric }
390139d628a0SDimitry Andric
cancelScheduling(ArrayRef<Value * > VL,Value * OpValue)3902c4394386SDimitry Andric void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3903c4394386SDimitry Andric Value *OpValue) {
3904c4394386SDimitry Andric if (isa<PHINode>(OpValue))
390539d628a0SDimitry Andric return;
390639d628a0SDimitry Andric
3907c4394386SDimitry Andric ScheduleData *Bundle = getScheduleData(OpValue);
39084ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
390939d628a0SDimitry Andric assert(!Bundle->IsScheduled &&
391039d628a0SDimitry Andric "Can't cancel bundle which is already scheduled");
391139d628a0SDimitry Andric assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
391239d628a0SDimitry Andric "tried to unbundle something which is not a bundle");
391339d628a0SDimitry Andric
391439d628a0SDimitry Andric // Un-bundle: make single instructions out of the bundle.
391539d628a0SDimitry Andric ScheduleData *BundleMember = Bundle;
391639d628a0SDimitry Andric while (BundleMember) {
391739d628a0SDimitry Andric assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
391839d628a0SDimitry Andric BundleMember->FirstInBundle = BundleMember;
391939d628a0SDimitry Andric ScheduleData *Next = BundleMember->NextInBundle;
392039d628a0SDimitry Andric BundleMember->NextInBundle = nullptr;
392139d628a0SDimitry Andric BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
392239d628a0SDimitry Andric if (BundleMember->UnscheduledDepsInBundle == 0) {
392339d628a0SDimitry Andric ReadyInsts.insert(BundleMember);
392439d628a0SDimitry Andric }
392539d628a0SDimitry Andric BundleMember = Next;
392639d628a0SDimitry Andric }
392739d628a0SDimitry Andric }
392839d628a0SDimitry Andric
allocateScheduleDataChunks()39292cab237bSDimitry Andric BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
39302cab237bSDimitry Andric // Allocate a new ScheduleData for the instruction.
39312cab237bSDimitry Andric if (ChunkPos >= ChunkSize) {
39322cab237bSDimitry Andric ScheduleDataChunks.push_back(llvm::make_unique<ScheduleData[]>(ChunkSize));
39332cab237bSDimitry Andric ChunkPos = 0;
39342cab237bSDimitry Andric }
39352cab237bSDimitry Andric return &(ScheduleDataChunks.back()[ChunkPos++]);
39362cab237bSDimitry Andric }
39372cab237bSDimitry Andric
extendSchedulingRegion(Value * V,const InstructionsState & S)39382cab237bSDimitry Andric bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
39394ba319b5SDimitry Andric const InstructionsState &S) {
39404ba319b5SDimitry Andric if (getScheduleData(V, isOneOf(S, V)))
39417d523365SDimitry Andric return true;
394239d628a0SDimitry Andric Instruction *I = dyn_cast<Instruction>(V);
394339d628a0SDimitry Andric assert(I && "bundle member must be an instruction");
394439d628a0SDimitry Andric assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
39454ba319b5SDimitry Andric auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
39462cab237bSDimitry Andric ScheduleData *ISD = getScheduleData(I);
39472cab237bSDimitry Andric if (!ISD)
39482cab237bSDimitry Andric return false;
39492cab237bSDimitry Andric assert(isInSchedulingRegion(ISD) &&
39502cab237bSDimitry Andric "ScheduleData not in scheduling region");
39512cab237bSDimitry Andric ScheduleData *SD = allocateScheduleDataChunks();
39522cab237bSDimitry Andric SD->Inst = I;
39534ba319b5SDimitry Andric SD->init(SchedulingRegionID, S.OpValue);
39544ba319b5SDimitry Andric ExtraScheduleDataMap[I][S.OpValue] = SD;
39552cab237bSDimitry Andric return true;
39562cab237bSDimitry Andric };
39572cab237bSDimitry Andric if (CheckSheduleForI(I))
39582cab237bSDimitry Andric return true;
395939d628a0SDimitry Andric if (!ScheduleStart) {
396039d628a0SDimitry Andric // It's the first instruction in the new region.
396139d628a0SDimitry Andric initScheduleData(I, I->getNextNode(), nullptr, nullptr);
396239d628a0SDimitry Andric ScheduleStart = I;
396339d628a0SDimitry Andric ScheduleEnd = I->getNextNode();
39644ba319b5SDimitry Andric if (isOneOf(S, I) != I)
39652cab237bSDimitry Andric CheckSheduleForI(I);
3966*b5893f02SDimitry Andric assert(ScheduleEnd && "tried to vectorize a terminator?");
39674ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
39687d523365SDimitry Andric return true;
396939d628a0SDimitry Andric }
397039d628a0SDimitry Andric // Search up and down at the same time, because we don't know if the new
397139d628a0SDimitry Andric // instruction is above or below the existing scheduling region.
3972d88c1a5aSDimitry Andric BasicBlock::reverse_iterator UpIter =
3973d88c1a5aSDimitry Andric ++ScheduleStart->getIterator().getReverse();
397439d628a0SDimitry Andric BasicBlock::reverse_iterator UpperEnd = BB->rend();
3975d88c1a5aSDimitry Andric BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
397639d628a0SDimitry Andric BasicBlock::iterator LowerEnd = BB->end();
39772cab237bSDimitry Andric while (true) {
39787d523365SDimitry Andric if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
39794ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
39807d523365SDimitry Andric return false;
39817d523365SDimitry Andric }
39827d523365SDimitry Andric
398339d628a0SDimitry Andric if (UpIter != UpperEnd) {
398439d628a0SDimitry Andric if (&*UpIter == I) {
398539d628a0SDimitry Andric initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
398639d628a0SDimitry Andric ScheduleStart = I;
39874ba319b5SDimitry Andric if (isOneOf(S, I) != I)
39882cab237bSDimitry Andric CheckSheduleForI(I);
39894ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
39904ba319b5SDimitry Andric << "\n");
39917d523365SDimitry Andric return true;
399239d628a0SDimitry Andric }
399339d628a0SDimitry Andric UpIter++;
399439d628a0SDimitry Andric }
399539d628a0SDimitry Andric if (DownIter != LowerEnd) {
399639d628a0SDimitry Andric if (&*DownIter == I) {
399739d628a0SDimitry Andric initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
399839d628a0SDimitry Andric nullptr);
399939d628a0SDimitry Andric ScheduleEnd = I->getNextNode();
40004ba319b5SDimitry Andric if (isOneOf(S, I) != I)
40012cab237bSDimitry Andric CheckSheduleForI(I);
4002*b5893f02SDimitry Andric assert(ScheduleEnd && "tried to vectorize a terminator?");
40034ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I
40044ba319b5SDimitry Andric << "\n");
40057d523365SDimitry Andric return true;
400639d628a0SDimitry Andric }
400739d628a0SDimitry Andric DownIter++;
400839d628a0SDimitry Andric }
400939d628a0SDimitry Andric assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
401039d628a0SDimitry Andric "instruction not found in block");
401139d628a0SDimitry Andric }
40127d523365SDimitry Andric return true;
401339d628a0SDimitry Andric }
401439d628a0SDimitry Andric
initScheduleData(Instruction * FromI,Instruction * ToI,ScheduleData * PrevLoadStore,ScheduleData * NextLoadStore)401539d628a0SDimitry Andric void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
401639d628a0SDimitry Andric Instruction *ToI,
401739d628a0SDimitry Andric ScheduleData *PrevLoadStore,
401839d628a0SDimitry Andric ScheduleData *NextLoadStore) {
401939d628a0SDimitry Andric ScheduleData *CurrentLoadStore = PrevLoadStore;
402039d628a0SDimitry Andric for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
402139d628a0SDimitry Andric ScheduleData *SD = ScheduleDataMap[I];
402239d628a0SDimitry Andric if (!SD) {
40232cab237bSDimitry Andric SD = allocateScheduleDataChunks();
402439d628a0SDimitry Andric ScheduleDataMap[I] = SD;
402539d628a0SDimitry Andric SD->Inst = I;
402639d628a0SDimitry Andric }
402739d628a0SDimitry Andric assert(!isInSchedulingRegion(SD) &&
402839d628a0SDimitry Andric "new ScheduleData already in scheduling region");
40292cab237bSDimitry Andric SD->init(SchedulingRegionID, I);
403039d628a0SDimitry Andric
40312cab237bSDimitry Andric if (I->mayReadOrWriteMemory() &&
40322cab237bSDimitry Andric (!isa<IntrinsicInst>(I) ||
40332cab237bSDimitry Andric cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
403439d628a0SDimitry Andric // Update the linked list of memory accessing instructions.
403539d628a0SDimitry Andric if (CurrentLoadStore) {
403639d628a0SDimitry Andric CurrentLoadStore->NextLoadStore = SD;
403739d628a0SDimitry Andric } else {
403839d628a0SDimitry Andric FirstLoadStoreInRegion = SD;
403939d628a0SDimitry Andric }
404039d628a0SDimitry Andric CurrentLoadStore = SD;
404139d628a0SDimitry Andric }
404239d628a0SDimitry Andric }
404339d628a0SDimitry Andric if (NextLoadStore) {
404439d628a0SDimitry Andric if (CurrentLoadStore)
404539d628a0SDimitry Andric CurrentLoadStore->NextLoadStore = NextLoadStore;
404639d628a0SDimitry Andric } else {
404739d628a0SDimitry Andric LastLoadStoreInRegion = CurrentLoadStore;
404839d628a0SDimitry Andric }
404939d628a0SDimitry Andric }
405039d628a0SDimitry Andric
calculateDependencies(ScheduleData * SD,bool InsertInReadyList,BoUpSLP * SLP)405139d628a0SDimitry Andric void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
405239d628a0SDimitry Andric bool InsertInReadyList,
405339d628a0SDimitry Andric BoUpSLP *SLP) {
405439d628a0SDimitry Andric assert(SD->isSchedulingEntity());
405539d628a0SDimitry Andric
405639d628a0SDimitry Andric SmallVector<ScheduleData *, 10> WorkList;
405739d628a0SDimitry Andric WorkList.push_back(SD);
405839d628a0SDimitry Andric
405939d628a0SDimitry Andric while (!WorkList.empty()) {
406039d628a0SDimitry Andric ScheduleData *SD = WorkList.back();
406139d628a0SDimitry Andric WorkList.pop_back();
406239d628a0SDimitry Andric
406339d628a0SDimitry Andric ScheduleData *BundleMember = SD;
406439d628a0SDimitry Andric while (BundleMember) {
406539d628a0SDimitry Andric assert(isInSchedulingRegion(BundleMember));
406639d628a0SDimitry Andric if (!BundleMember->hasValidDependencies()) {
406739d628a0SDimitry Andric
40684ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
40694ba319b5SDimitry Andric << "\n");
407039d628a0SDimitry Andric BundleMember->Dependencies = 0;
407139d628a0SDimitry Andric BundleMember->resetUnscheduledDeps();
407239d628a0SDimitry Andric
407339d628a0SDimitry Andric // Handle def-use chain dependencies.
40742cab237bSDimitry Andric if (BundleMember->OpValue != BundleMember->Inst) {
40752cab237bSDimitry Andric ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
40762cab237bSDimitry Andric if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
40772cab237bSDimitry Andric BundleMember->Dependencies++;
40782cab237bSDimitry Andric ScheduleData *DestBundle = UseSD->FirstInBundle;
40792cab237bSDimitry Andric if (!DestBundle->IsScheduled)
40802cab237bSDimitry Andric BundleMember->incrementUnscheduledDeps(1);
40812cab237bSDimitry Andric if (!DestBundle->hasValidDependencies())
40822cab237bSDimitry Andric WorkList.push_back(DestBundle);
40832cab237bSDimitry Andric }
40842cab237bSDimitry Andric } else {
408539d628a0SDimitry Andric for (User *U : BundleMember->Inst->users()) {
408639d628a0SDimitry Andric if (isa<Instruction>(U)) {
408739d628a0SDimitry Andric ScheduleData *UseSD = getScheduleData(U);
408839d628a0SDimitry Andric if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
408939d628a0SDimitry Andric BundleMember->Dependencies++;
409039d628a0SDimitry Andric ScheduleData *DestBundle = UseSD->FirstInBundle;
4091edd7eaddSDimitry Andric if (!DestBundle->IsScheduled)
409239d628a0SDimitry Andric BundleMember->incrementUnscheduledDeps(1);
4093edd7eaddSDimitry Andric if (!DestBundle->hasValidDependencies())
409439d628a0SDimitry Andric WorkList.push_back(DestBundle);
409539d628a0SDimitry Andric }
409639d628a0SDimitry Andric } else {
409739d628a0SDimitry Andric // I'm not sure if this can ever happen. But we need to be safe.
40987d523365SDimitry Andric // This lets the instruction/bundle never be scheduled and
40997d523365SDimitry Andric // eventually disable vectorization.
410039d628a0SDimitry Andric BundleMember->Dependencies++;
410139d628a0SDimitry Andric BundleMember->incrementUnscheduledDeps(1);
410239d628a0SDimitry Andric }
410339d628a0SDimitry Andric }
41042cab237bSDimitry Andric }
410539d628a0SDimitry Andric
410639d628a0SDimitry Andric // Handle the memory dependencies.
410739d628a0SDimitry Andric ScheduleData *DepDest = BundleMember->NextLoadStore;
410839d628a0SDimitry Andric if (DepDest) {
410939d628a0SDimitry Andric Instruction *SrcInst = BundleMember->Inst;
41108f0fd8f6SDimitry Andric MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
411139d628a0SDimitry Andric bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
4112ff0cc061SDimitry Andric unsigned numAliased = 0;
4113ff0cc061SDimitry Andric unsigned DistToSrc = 1;
411439d628a0SDimitry Andric
411539d628a0SDimitry Andric while (DepDest) {
411639d628a0SDimitry Andric assert(isInSchedulingRegion(DepDest));
4117ff0cc061SDimitry Andric
4118ff0cc061SDimitry Andric // We have two limits to reduce the complexity:
4119ff0cc061SDimitry Andric // 1) AliasedCheckLimit: It's a small limit to reduce calls to
4120ff0cc061SDimitry Andric // SLP->isAliased (which is the expensive part in this loop).
4121ff0cc061SDimitry Andric // 2) MaxMemDepDistance: It's for very large blocks and it aborts
4122ff0cc061SDimitry Andric // the whole loop (even if the loop is fast, it's quadratic).
4123ff0cc061SDimitry Andric // It's important for the loop break condition (see below) to
4124ff0cc061SDimitry Andric // check this limit even between two read-only instructions.
4125ff0cc061SDimitry Andric if (DistToSrc >= MaxMemDepDistance ||
4126ff0cc061SDimitry Andric ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
4127ff0cc061SDimitry Andric (numAliased >= AliasedCheckLimit ||
4128ff0cc061SDimitry Andric SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
4129ff0cc061SDimitry Andric
4130ff0cc061SDimitry Andric // We increment the counter only if the locations are aliased
4131ff0cc061SDimitry Andric // (instead of counting all alias checks). This gives a better
4132ff0cc061SDimitry Andric // balance between reduced runtime and accurate dependencies.
4133ff0cc061SDimitry Andric numAliased++;
4134ff0cc061SDimitry Andric
413539d628a0SDimitry Andric DepDest->MemoryDependencies.push_back(BundleMember);
413639d628a0SDimitry Andric BundleMember->Dependencies++;
413739d628a0SDimitry Andric ScheduleData *DestBundle = DepDest->FirstInBundle;
413839d628a0SDimitry Andric if (!DestBundle->IsScheduled) {
413939d628a0SDimitry Andric BundleMember->incrementUnscheduledDeps(1);
414039d628a0SDimitry Andric }
414139d628a0SDimitry Andric if (!DestBundle->hasValidDependencies()) {
414239d628a0SDimitry Andric WorkList.push_back(DestBundle);
414339d628a0SDimitry Andric }
414439d628a0SDimitry Andric }
414539d628a0SDimitry Andric DepDest = DepDest->NextLoadStore;
4146ff0cc061SDimitry Andric
4147ff0cc061SDimitry Andric // Example, explaining the loop break condition: Let's assume our
4148ff0cc061SDimitry Andric // starting instruction is i0 and MaxMemDepDistance = 3.
4149ff0cc061SDimitry Andric //
4150ff0cc061SDimitry Andric // +--------v--v--v
4151ff0cc061SDimitry Andric // i0,i1,i2,i3,i4,i5,i6,i7,i8
4152ff0cc061SDimitry Andric // +--------^--^--^
4153ff0cc061SDimitry Andric //
4154ff0cc061SDimitry Andric // MaxMemDepDistance let us stop alias-checking at i3 and we add
4155ff0cc061SDimitry Andric // dependencies from i0 to i3,i4,.. (even if they are not aliased).
4156ff0cc061SDimitry Andric // Previously we already added dependencies from i3 to i6,i7,i8
4157ff0cc061SDimitry Andric // (because of MaxMemDepDistance). As we added a dependency from
4158ff0cc061SDimitry Andric // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4159ff0cc061SDimitry Andric // and we can abort this loop at i6.
4160ff0cc061SDimitry Andric if (DistToSrc >= 2 * MaxMemDepDistance)
4161ff0cc061SDimitry Andric break;
4162ff0cc061SDimitry Andric DistToSrc++;
416339d628a0SDimitry Andric }
416439d628a0SDimitry Andric }
416539d628a0SDimitry Andric }
416639d628a0SDimitry Andric BundleMember = BundleMember->NextInBundle;
416739d628a0SDimitry Andric }
416839d628a0SDimitry Andric if (InsertInReadyList && SD->isReady()) {
416939d628a0SDimitry Andric ReadyInsts.push_back(SD);
41704ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst
41714ba319b5SDimitry Andric << "\n");
417239d628a0SDimitry Andric }
417339d628a0SDimitry Andric }
417439d628a0SDimitry Andric }
417539d628a0SDimitry Andric
resetSchedule()417639d628a0SDimitry Andric void BoUpSLP::BlockScheduling::resetSchedule() {
417739d628a0SDimitry Andric assert(ScheduleStart &&
417839d628a0SDimitry Andric "tried to reset schedule on block which has not been scheduled");
417939d628a0SDimitry Andric for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
41802cab237bSDimitry Andric doForAllOpcodes(I, [&](ScheduleData *SD) {
41812cab237bSDimitry Andric assert(isInSchedulingRegion(SD) &&
41822cab237bSDimitry Andric "ScheduleData not in scheduling region");
418339d628a0SDimitry Andric SD->IsScheduled = false;
418439d628a0SDimitry Andric SD->resetUnscheduledDeps();
41852cab237bSDimitry Andric });
418639d628a0SDimitry Andric }
418739d628a0SDimitry Andric ReadyInsts.clear();
418839d628a0SDimitry Andric }
418939d628a0SDimitry Andric
scheduleBlock(BlockScheduling * BS)419039d628a0SDimitry Andric void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
419139d628a0SDimitry Andric if (!BS->ScheduleStart)
419239d628a0SDimitry Andric return;
419339d628a0SDimitry Andric
41944ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
419539d628a0SDimitry Andric
419639d628a0SDimitry Andric BS->resetSchedule();
419739d628a0SDimitry Andric
419839d628a0SDimitry Andric // For the real scheduling we use a more sophisticated ready-list: it is
419939d628a0SDimitry Andric // sorted by the original instruction location. This lets the final schedule
420039d628a0SDimitry Andric // be as close as possible to the original instruction order.
420139d628a0SDimitry Andric struct ScheduleDataCompare {
42027a7e6055SDimitry Andric bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
420339d628a0SDimitry Andric return SD2->SchedulingPriority < SD1->SchedulingPriority;
420439d628a0SDimitry Andric }
420539d628a0SDimitry Andric };
420639d628a0SDimitry Andric std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
420739d628a0SDimitry Andric
42087d523365SDimitry Andric // Ensure that all dependency data is updated and fill the ready-list with
420939d628a0SDimitry Andric // initial instructions.
421039d628a0SDimitry Andric int Idx = 0;
421139d628a0SDimitry Andric int NumToSchedule = 0;
421239d628a0SDimitry Andric for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
421339d628a0SDimitry Andric I = I->getNextNode()) {
42142cab237bSDimitry Andric BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
42152cab237bSDimitry Andric assert(SD->isPartOfBundle() ==
42162cab237bSDimitry Andric (getTreeEntry(SD->Inst) != nullptr) &&
42172cab237bSDimitry Andric "scheduler and vectorizer bundle mismatch");
421839d628a0SDimitry Andric SD->FirstInBundle->SchedulingPriority = Idx++;
421939d628a0SDimitry Andric if (SD->isSchedulingEntity()) {
422039d628a0SDimitry Andric BS->calculateDependencies(SD, false, this);
422139d628a0SDimitry Andric NumToSchedule++;
422239d628a0SDimitry Andric }
42232cab237bSDimitry Andric });
422439d628a0SDimitry Andric }
422539d628a0SDimitry Andric BS->initialFillReadyList(ReadyInsts);
422639d628a0SDimitry Andric
422739d628a0SDimitry Andric Instruction *LastScheduledInst = BS->ScheduleEnd;
422839d628a0SDimitry Andric
422939d628a0SDimitry Andric // Do the "real" scheduling.
423039d628a0SDimitry Andric while (!ReadyInsts.empty()) {
423139d628a0SDimitry Andric ScheduleData *picked = *ReadyInsts.begin();
423239d628a0SDimitry Andric ReadyInsts.erase(ReadyInsts.begin());
423339d628a0SDimitry Andric
423439d628a0SDimitry Andric // Move the scheduled instruction(s) to their dedicated places, if not
423539d628a0SDimitry Andric // there yet.
423639d628a0SDimitry Andric ScheduleData *BundleMember = picked;
423739d628a0SDimitry Andric while (BundleMember) {
423839d628a0SDimitry Andric Instruction *pickedInst = BundleMember->Inst;
423939d628a0SDimitry Andric if (LastScheduledInst->getNextNode() != pickedInst) {
424039d628a0SDimitry Andric BS->BB->getInstList().remove(pickedInst);
42417d523365SDimitry Andric BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
42427d523365SDimitry Andric pickedInst);
424339d628a0SDimitry Andric }
424439d628a0SDimitry Andric LastScheduledInst = pickedInst;
424539d628a0SDimitry Andric BundleMember = BundleMember->NextInBundle;
424639d628a0SDimitry Andric }
424739d628a0SDimitry Andric
424839d628a0SDimitry Andric BS->schedule(picked, ReadyInsts);
424939d628a0SDimitry Andric NumToSchedule--;
425039d628a0SDimitry Andric }
425139d628a0SDimitry Andric assert(NumToSchedule == 0 && "could not schedule all instructions");
425239d628a0SDimitry Andric
425339d628a0SDimitry Andric // Avoid duplicate scheduling of the block.
425439d628a0SDimitry Andric BS->ScheduleStart = nullptr;
425539d628a0SDimitry Andric }
425639d628a0SDimitry Andric
getVectorElementSize(Value * V)42573ca95b02SDimitry Andric unsigned BoUpSLP::getVectorElementSize(Value *V) {
42583ca95b02SDimitry Andric // If V is a store, just return the width of the stored value without
42593ca95b02SDimitry Andric // traversing the expression tree. This is the common case.
42603ca95b02SDimitry Andric if (auto *Store = dyn_cast<StoreInst>(V))
42613ca95b02SDimitry Andric return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
42623ca95b02SDimitry Andric
42633ca95b02SDimitry Andric // If V is not a store, we can traverse the expression tree to find loads
42643ca95b02SDimitry Andric // that feed it. The type of the loaded value may indicate a more suitable
42653ca95b02SDimitry Andric // width than V's type. We want to base the vector element size on the width
42663ca95b02SDimitry Andric // of memory operations where possible.
42673ca95b02SDimitry Andric SmallVector<Instruction *, 16> Worklist;
42683ca95b02SDimitry Andric SmallPtrSet<Instruction *, 16> Visited;
42693ca95b02SDimitry Andric if (auto *I = dyn_cast<Instruction>(V))
42703ca95b02SDimitry Andric Worklist.push_back(I);
42713ca95b02SDimitry Andric
42723ca95b02SDimitry Andric // Traverse the expression tree in bottom-up order looking for loads. If we
4273*b5893f02SDimitry Andric // encounter an instruction we don't yet handle, we give up.
42743ca95b02SDimitry Andric auto MaxWidth = 0u;
42753ca95b02SDimitry Andric auto FoundUnknownInst = false;
42763ca95b02SDimitry Andric while (!Worklist.empty() && !FoundUnknownInst) {
42773ca95b02SDimitry Andric auto *I = Worklist.pop_back_val();
42783ca95b02SDimitry Andric Visited.insert(I);
42793ca95b02SDimitry Andric
42803ca95b02SDimitry Andric // We should only be looking at scalar instructions here. If the current
42813ca95b02SDimitry Andric // instruction has a vector type, give up.
42823ca95b02SDimitry Andric auto *Ty = I->getType();
42833ca95b02SDimitry Andric if (isa<VectorType>(Ty))
42843ca95b02SDimitry Andric FoundUnknownInst = true;
42853ca95b02SDimitry Andric
42863ca95b02SDimitry Andric // If the current instruction is a load, update MaxWidth to reflect the
42873ca95b02SDimitry Andric // width of the loaded value.
42883ca95b02SDimitry Andric else if (isa<LoadInst>(I))
42893ca95b02SDimitry Andric MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
42903ca95b02SDimitry Andric
42913ca95b02SDimitry Andric // Otherwise, we need to visit the operands of the instruction. We only
42923ca95b02SDimitry Andric // handle the interesting cases from buildTree here. If an operand is an
42933ca95b02SDimitry Andric // instruction we haven't yet visited, we add it to the worklist.
42943ca95b02SDimitry Andric else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
42953ca95b02SDimitry Andric isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
42963ca95b02SDimitry Andric for (Use &U : I->operands())
42973ca95b02SDimitry Andric if (auto *J = dyn_cast<Instruction>(U.get()))
42983ca95b02SDimitry Andric if (!Visited.count(J))
42993ca95b02SDimitry Andric Worklist.push_back(J);
43003ca95b02SDimitry Andric }
43013ca95b02SDimitry Andric
43023ca95b02SDimitry Andric // If we don't yet handle the instruction, give up.
43033ca95b02SDimitry Andric else
43043ca95b02SDimitry Andric FoundUnknownInst = true;
43053ca95b02SDimitry Andric }
43063ca95b02SDimitry Andric
43073ca95b02SDimitry Andric // If we didn't encounter a memory access in the expression tree, or if we
43083ca95b02SDimitry Andric // gave up for some reason, just return the width of V.
43093ca95b02SDimitry Andric if (!MaxWidth || FoundUnknownInst)
43103ca95b02SDimitry Andric return DL->getTypeSizeInBits(V->getType());
43113ca95b02SDimitry Andric
43123ca95b02SDimitry Andric // Otherwise, return the maximum width we found.
43133ca95b02SDimitry Andric return MaxWidth;
43143ca95b02SDimitry Andric }
43153ca95b02SDimitry Andric
43163ca95b02SDimitry Andric // Determine if a value V in a vectorizable expression Expr can be demoted to a
43173ca95b02SDimitry Andric // smaller type with a truncation. We collect the values that will be demoted
43183ca95b02SDimitry Andric // in ToDemote and additional roots that require investigating in Roots.
collectValuesToDemote(Value * V,SmallPtrSetImpl<Value * > & Expr,SmallVectorImpl<Value * > & ToDemote,SmallVectorImpl<Value * > & Roots)43193ca95b02SDimitry Andric static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
43203ca95b02SDimitry Andric SmallVectorImpl<Value *> &ToDemote,
43213ca95b02SDimitry Andric SmallVectorImpl<Value *> &Roots) {
43223ca95b02SDimitry Andric // We can always demote constants.
43233ca95b02SDimitry Andric if (isa<Constant>(V)) {
43243ca95b02SDimitry Andric ToDemote.push_back(V);
43253ca95b02SDimitry Andric return true;
43263ca95b02SDimitry Andric }
43273ca95b02SDimitry Andric
43283ca95b02SDimitry Andric // If the value is not an instruction in the expression with only one use, it
43293ca95b02SDimitry Andric // cannot be demoted.
43303ca95b02SDimitry Andric auto *I = dyn_cast<Instruction>(V);
43313ca95b02SDimitry Andric if (!I || !I->hasOneUse() || !Expr.count(I))
43323ca95b02SDimitry Andric return false;
43333ca95b02SDimitry Andric
43343ca95b02SDimitry Andric switch (I->getOpcode()) {
43353ca95b02SDimitry Andric
43363ca95b02SDimitry Andric // We can always demote truncations and extensions. Since truncations can
43373ca95b02SDimitry Andric // seed additional demotion, we save the truncated value.
43383ca95b02SDimitry Andric case Instruction::Trunc:
43393ca95b02SDimitry Andric Roots.push_back(I->getOperand(0));
4340da09e106SDimitry Andric break;
43413ca95b02SDimitry Andric case Instruction::ZExt:
43423ca95b02SDimitry Andric case Instruction::SExt:
43433ca95b02SDimitry Andric break;
43443ca95b02SDimitry Andric
43453ca95b02SDimitry Andric // We can demote certain binary operations if we can demote both of their
43463ca95b02SDimitry Andric // operands.
43473ca95b02SDimitry Andric case Instruction::Add:
43483ca95b02SDimitry Andric case Instruction::Sub:
43493ca95b02SDimitry Andric case Instruction::Mul:
43503ca95b02SDimitry Andric case Instruction::And:
43513ca95b02SDimitry Andric case Instruction::Or:
43523ca95b02SDimitry Andric case Instruction::Xor:
43533ca95b02SDimitry Andric if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
43543ca95b02SDimitry Andric !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
43553ca95b02SDimitry Andric return false;
43563ca95b02SDimitry Andric break;
43573ca95b02SDimitry Andric
43583ca95b02SDimitry Andric // We can demote selects if we can demote their true and false values.
43593ca95b02SDimitry Andric case Instruction::Select: {
43603ca95b02SDimitry Andric SelectInst *SI = cast<SelectInst>(I);
43613ca95b02SDimitry Andric if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
43623ca95b02SDimitry Andric !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
43633ca95b02SDimitry Andric return false;
43643ca95b02SDimitry Andric break;
43653ca95b02SDimitry Andric }
43663ca95b02SDimitry Andric
43673ca95b02SDimitry Andric // We can demote phis if we can demote all their incoming operands. Note that
43683ca95b02SDimitry Andric // we don't need to worry about cycles since we ensure single use above.
43693ca95b02SDimitry Andric case Instruction::PHI: {
43703ca95b02SDimitry Andric PHINode *PN = cast<PHINode>(I);
43713ca95b02SDimitry Andric for (Value *IncValue : PN->incoming_values())
43723ca95b02SDimitry Andric if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
43733ca95b02SDimitry Andric return false;
43743ca95b02SDimitry Andric break;
43753ca95b02SDimitry Andric }
43763ca95b02SDimitry Andric
43773ca95b02SDimitry Andric // Otherwise, conservatively give up.
43783ca95b02SDimitry Andric default:
43793ca95b02SDimitry Andric return false;
43803ca95b02SDimitry Andric }
43813ca95b02SDimitry Andric
43823ca95b02SDimitry Andric // Record the value that we can demote.
43833ca95b02SDimitry Andric ToDemote.push_back(V);
43843ca95b02SDimitry Andric return true;
43853ca95b02SDimitry Andric }
43863ca95b02SDimitry Andric
computeMinimumValueSizes()43873ca95b02SDimitry Andric void BoUpSLP::computeMinimumValueSizes() {
43883ca95b02SDimitry Andric // If there are no external uses, the expression tree must be rooted by a
43893ca95b02SDimitry Andric // store. We can't demote in-memory values, so there is nothing to do here.
43903ca95b02SDimitry Andric if (ExternalUses.empty())
43913ca95b02SDimitry Andric return;
43923ca95b02SDimitry Andric
43933ca95b02SDimitry Andric // We only attempt to truncate integer expressions.
43943ca95b02SDimitry Andric auto &TreeRoot = VectorizableTree[0].Scalars;
43953ca95b02SDimitry Andric auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
43963ca95b02SDimitry Andric if (!TreeRootIT)
43973ca95b02SDimitry Andric return;
43983ca95b02SDimitry Andric
43993ca95b02SDimitry Andric // If the expression is not rooted by a store, these roots should have
44003ca95b02SDimitry Andric // external uses. We will rely on InstCombine to rewrite the expression in
44013ca95b02SDimitry Andric // the narrower type. However, InstCombine only rewrites single-use values.
44023ca95b02SDimitry Andric // This means that if a tree entry other than a root is used externally, it
44033ca95b02SDimitry Andric // must have multiple uses and InstCombine will not rewrite it. The code
44043ca95b02SDimitry Andric // below ensures that only the roots are used externally.
44053ca95b02SDimitry Andric SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
44063ca95b02SDimitry Andric for (auto &EU : ExternalUses)
44073ca95b02SDimitry Andric if (!Expr.erase(EU.Scalar))
44083ca95b02SDimitry Andric return;
44093ca95b02SDimitry Andric if (!Expr.empty())
44103ca95b02SDimitry Andric return;
44113ca95b02SDimitry Andric
44123ca95b02SDimitry Andric // Collect the scalar values of the vectorizable expression. We will use this
44133ca95b02SDimitry Andric // context to determine which values can be demoted. If we see a truncation,
44143ca95b02SDimitry Andric // we mark it as seeding another demotion.
44153ca95b02SDimitry Andric for (auto &Entry : VectorizableTree)
44163ca95b02SDimitry Andric Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
44173ca95b02SDimitry Andric
44183ca95b02SDimitry Andric // Ensure the roots of the vectorizable tree don't form a cycle. They must
44193ca95b02SDimitry Andric // have a single external user that is not in the vectorizable tree.
44203ca95b02SDimitry Andric for (auto *Root : TreeRoot)
44213ca95b02SDimitry Andric if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
44223ca95b02SDimitry Andric return;
44233ca95b02SDimitry Andric
44243ca95b02SDimitry Andric // Conservatively determine if we can actually truncate the roots of the
44253ca95b02SDimitry Andric // expression. Collect the values that can be demoted in ToDemote and
44263ca95b02SDimitry Andric // additional roots that require investigating in Roots.
44273ca95b02SDimitry Andric SmallVector<Value *, 32> ToDemote;
44283ca95b02SDimitry Andric SmallVector<Value *, 4> Roots;
44293ca95b02SDimitry Andric for (auto *Root : TreeRoot)
44303ca95b02SDimitry Andric if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
44313ca95b02SDimitry Andric return;
44323ca95b02SDimitry Andric
44333ca95b02SDimitry Andric // The maximum bit width required to represent all the values that can be
44343ca95b02SDimitry Andric // demoted without loss of precision. It would be safe to truncate the roots
44353ca95b02SDimitry Andric // of the expression to this width.
44363ca95b02SDimitry Andric auto MaxBitWidth = 8u;
44373ca95b02SDimitry Andric
44383ca95b02SDimitry Andric // We first check if all the bits of the roots are demanded. If they're not,
44393ca95b02SDimitry Andric // we can truncate the roots to this narrower type.
44403ca95b02SDimitry Andric for (auto *Root : TreeRoot) {
44413ca95b02SDimitry Andric auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
44423ca95b02SDimitry Andric MaxBitWidth = std::max<unsigned>(
44433ca95b02SDimitry Andric Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
44443ca95b02SDimitry Andric }
44453ca95b02SDimitry Andric
4446d88c1a5aSDimitry Andric // True if the roots can be zero-extended back to their original type, rather
4447d88c1a5aSDimitry Andric // than sign-extended. We know that if the leading bits are not demanded, we
4448d88c1a5aSDimitry Andric // can safely zero-extend. So we initialize IsKnownPositive to True.
4449d88c1a5aSDimitry Andric bool IsKnownPositive = true;
4450d88c1a5aSDimitry Andric
44513ca95b02SDimitry Andric // If all the bits of the roots are demanded, we can try a little harder to
44523ca95b02SDimitry Andric // compute a narrower type. This can happen, for example, if the roots are
44533ca95b02SDimitry Andric // getelementptr indices. InstCombine promotes these indices to the pointer
44543ca95b02SDimitry Andric // width. Thus, all their bits are technically demanded even though the
44553ca95b02SDimitry Andric // address computation might be vectorized in a smaller type.
44563ca95b02SDimitry Andric //
44573ca95b02SDimitry Andric // We start by looking at each entry that can be demoted. We compute the
44583ca95b02SDimitry Andric // maximum bit width required to store the scalar by using ValueTracking to
44593ca95b02SDimitry Andric // compute the number of high-order bits we can truncate.
44604ba319b5SDimitry Andric if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
44614ba319b5SDimitry Andric llvm::all_of(TreeRoot, [](Value *R) {
44624ba319b5SDimitry Andric assert(R->hasOneUse() && "Root should have only one use!");
44634ba319b5SDimitry Andric return isa<GetElementPtrInst>(R->user_back());
44644ba319b5SDimitry Andric })) {
44653ca95b02SDimitry Andric MaxBitWidth = 8u;
4466d88c1a5aSDimitry Andric
4467d88c1a5aSDimitry Andric // Determine if the sign bit of all the roots is known to be zero. If not,
4468d88c1a5aSDimitry Andric // IsKnownPositive is set to False.
44692cab237bSDimitry Andric IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
44705517e702SDimitry Andric KnownBits Known = computeKnownBits(R, *DL);
44715517e702SDimitry Andric return Known.isNonNegative();
4472d88c1a5aSDimitry Andric });
4473d88c1a5aSDimitry Andric
4474d88c1a5aSDimitry Andric // Determine the maximum number of bits required to store the scalar
4475d88c1a5aSDimitry Andric // values.
44763ca95b02SDimitry Andric for (auto *Scalar : ToDemote) {
44772cab237bSDimitry Andric auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
44783ca95b02SDimitry Andric auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
44793ca95b02SDimitry Andric MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
44803ca95b02SDimitry Andric }
4481d88c1a5aSDimitry Andric
4482d88c1a5aSDimitry Andric // If we can't prove that the sign bit is zero, we must add one to the
4483d88c1a5aSDimitry Andric // maximum bit width to account for the unknown sign bit. This preserves
4484d88c1a5aSDimitry Andric // the existing sign bit so we can safely sign-extend the root back to the
4485d88c1a5aSDimitry Andric // original type. Otherwise, if we know the sign bit is zero, we will
4486d88c1a5aSDimitry Andric // zero-extend the root instead.
4487d88c1a5aSDimitry Andric //
4488d88c1a5aSDimitry Andric // FIXME: This is somewhat suboptimal, as there will be cases where adding
4489d88c1a5aSDimitry Andric // one to the maximum bit width will yield a larger-than-necessary
4490d88c1a5aSDimitry Andric // type. In general, we need to add an extra bit only if we can't
4491d88c1a5aSDimitry Andric // prove that the upper bit of the original type is equal to the
4492d88c1a5aSDimitry Andric // upper bit of the proposed smaller type. If these two bits are the
4493d88c1a5aSDimitry Andric // same (either zero or one) we know that sign-extending from the
4494d88c1a5aSDimitry Andric // smaller type will result in the same value. Here, since we can't
4495d88c1a5aSDimitry Andric // yet prove this, we are just making the proposed smaller type
4496d88c1a5aSDimitry Andric // larger to ensure correctness.
4497d88c1a5aSDimitry Andric if (!IsKnownPositive)
4498d88c1a5aSDimitry Andric ++MaxBitWidth;
44993ca95b02SDimitry Andric }
45003ca95b02SDimitry Andric
45013ca95b02SDimitry Andric // Round MaxBitWidth up to the next power-of-two.
45023ca95b02SDimitry Andric if (!isPowerOf2_64(MaxBitWidth))
45033ca95b02SDimitry Andric MaxBitWidth = NextPowerOf2(MaxBitWidth);
45043ca95b02SDimitry Andric
45053ca95b02SDimitry Andric // If the maximum bit width we compute is less than the with of the roots'
45063ca95b02SDimitry Andric // type, we can proceed with the narrowing. Otherwise, do nothing.
45073ca95b02SDimitry Andric if (MaxBitWidth >= TreeRootIT->getBitWidth())
45083ca95b02SDimitry Andric return;
45093ca95b02SDimitry Andric
45103ca95b02SDimitry Andric // If we can truncate the root, we must collect additional values that might
45113ca95b02SDimitry Andric // be demoted as a result. That is, those seeded by truncations we will
45123ca95b02SDimitry Andric // modify.
45133ca95b02SDimitry Andric while (!Roots.empty())
45143ca95b02SDimitry Andric collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
45153ca95b02SDimitry Andric
45163ca95b02SDimitry Andric // Finally, map the values we can demote to the maximum bit with we computed.
45173ca95b02SDimitry Andric for (auto *Scalar : ToDemote)
4518d88c1a5aSDimitry Andric MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
45193ca95b02SDimitry Andric }
45203ca95b02SDimitry Andric
45213ca95b02SDimitry Andric namespace {
45222cab237bSDimitry Andric
4523284c1978SDimitry Andric /// The SLPVectorizer Pass.
4524284c1978SDimitry Andric struct SLPVectorizer : public FunctionPass {
45253ca95b02SDimitry Andric SLPVectorizerPass Impl;
4526284c1978SDimitry Andric
4527284c1978SDimitry Andric /// Pass identification, replacement for typeid
4528284c1978SDimitry Andric static char ID;
4529284c1978SDimitry Andric
SLPVectorizer__anonfe9ee8d91511::SLPVectorizer4530284c1978SDimitry Andric explicit SLPVectorizer() : FunctionPass(ID) {
4531284c1978SDimitry Andric initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4532284c1978SDimitry Andric }
4533284c1978SDimitry Andric
doInitialization__anonfe9ee8d91511::SLPVectorizer45343ca95b02SDimitry Andric bool doInitialization(Module &M) override {
45353ca95b02SDimitry Andric return false;
45363ca95b02SDimitry Andric }
4537284c1978SDimitry Andric
runOnFunction__anonfe9ee8d91511::SLPVectorizer453891bc56edSDimitry Andric bool runOnFunction(Function &F) override {
45393ca95b02SDimitry Andric if (skipFunction(F))
454091bc56edSDimitry Andric return false;
454191bc56edSDimitry Andric
45423ca95b02SDimitry Andric auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
45433ca95b02SDimitry Andric auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4544ff0cc061SDimitry Andric auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
45453ca95b02SDimitry Andric auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
45463ca95b02SDimitry Andric auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
45473ca95b02SDimitry Andric auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
45483ca95b02SDimitry Andric auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
45493ca95b02SDimitry Andric auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
45503ca95b02SDimitry Andric auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
45515517e702SDimitry Andric auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4552284c1978SDimitry Andric
45535517e702SDimitry Andric return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4554284c1978SDimitry Andric }
4555284c1978SDimitry Andric
getAnalysisUsage__anonfe9ee8d91511::SLPVectorizer455691bc56edSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
4557284c1978SDimitry Andric FunctionPass::getAnalysisUsage(AU);
455839d628a0SDimitry Andric AU.addRequired<AssumptionCacheTracker>();
45597d523365SDimitry Andric AU.addRequired<ScalarEvolutionWrapperPass>();
45607d523365SDimitry Andric AU.addRequired<AAResultsWrapperPass>();
4561ff0cc061SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>();
4562ff0cc061SDimitry Andric AU.addRequired<LoopInfoWrapperPass>();
456391bc56edSDimitry Andric AU.addRequired<DominatorTreeWrapperPass>();
45643ca95b02SDimitry Andric AU.addRequired<DemandedBitsWrapperPass>();
45655517e702SDimitry Andric AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4566ff0cc061SDimitry Andric AU.addPreserved<LoopInfoWrapperPass>();
456791bc56edSDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>();
45687d523365SDimitry Andric AU.addPreserved<AAResultsWrapperPass>();
45697d523365SDimitry Andric AU.addPreserved<GlobalsAAWrapperPass>();
4570f785676fSDimitry Andric AU.setPreservesCFG();
4571284c1978SDimitry Andric }
4572284c1978SDimitry Andric };
45732cab237bSDimitry Andric
45743ca95b02SDimitry Andric } // end anonymous namespace
45753ca95b02SDimitry Andric
run(Function & F,FunctionAnalysisManager & AM)45763ca95b02SDimitry Andric PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
45773ca95b02SDimitry Andric auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
45783ca95b02SDimitry Andric auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
45793ca95b02SDimitry Andric auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
45803ca95b02SDimitry Andric auto *AA = &AM.getResult<AAManager>(F);
45813ca95b02SDimitry Andric auto *LI = &AM.getResult<LoopAnalysis>(F);
45823ca95b02SDimitry Andric auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
45833ca95b02SDimitry Andric auto *AC = &AM.getResult<AssumptionAnalysis>(F);
45843ca95b02SDimitry Andric auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
45855517e702SDimitry Andric auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
45863ca95b02SDimitry Andric
45875517e702SDimitry Andric bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
45883ca95b02SDimitry Andric if (!Changed)
45893ca95b02SDimitry Andric return PreservedAnalyses::all();
45907a7e6055SDimitry Andric
45913ca95b02SDimitry Andric PreservedAnalyses PA;
45927a7e6055SDimitry Andric PA.preserveSet<CFGAnalyses>();
45933ca95b02SDimitry Andric PA.preserve<AAManager>();
45943ca95b02SDimitry Andric PA.preserve<GlobalsAA>();
45953ca95b02SDimitry Andric return PA;
45963ca95b02SDimitry Andric }
45973ca95b02SDimitry Andric
runImpl(Function & F,ScalarEvolution * SE_,TargetTransformInfo * TTI_,TargetLibraryInfo * TLI_,AliasAnalysis * AA_,LoopInfo * LI_,DominatorTree * DT_,AssumptionCache * AC_,DemandedBits * DB_,OptimizationRemarkEmitter * ORE_)45983ca95b02SDimitry Andric bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
45993ca95b02SDimitry Andric TargetTransformInfo *TTI_,
46003ca95b02SDimitry Andric TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
46013ca95b02SDimitry Andric LoopInfo *LI_, DominatorTree *DT_,
46025517e702SDimitry Andric AssumptionCache *AC_, DemandedBits *DB_,
46035517e702SDimitry Andric OptimizationRemarkEmitter *ORE_) {
46043ca95b02SDimitry Andric SE = SE_;
46053ca95b02SDimitry Andric TTI = TTI_;
46063ca95b02SDimitry Andric TLI = TLI_;
46073ca95b02SDimitry Andric AA = AA_;
46083ca95b02SDimitry Andric LI = LI_;
46093ca95b02SDimitry Andric DT = DT_;
46103ca95b02SDimitry Andric AC = AC_;
46113ca95b02SDimitry Andric DB = DB_;
46123ca95b02SDimitry Andric DL = &F.getParent()->getDataLayout();
46133ca95b02SDimitry Andric
46143ca95b02SDimitry Andric Stores.clear();
46153ca95b02SDimitry Andric GEPs.clear();
46163ca95b02SDimitry Andric bool Changed = false;
46173ca95b02SDimitry Andric
46183ca95b02SDimitry Andric // If the target claims to have no vector registers don't attempt
46193ca95b02SDimitry Andric // vectorization.
46203ca95b02SDimitry Andric if (!TTI->getNumberOfRegisters(true))
46213ca95b02SDimitry Andric return false;
46223ca95b02SDimitry Andric
46233ca95b02SDimitry Andric // Don't vectorize when the attribute NoImplicitFloat is used.
46243ca95b02SDimitry Andric if (F.hasFnAttribute(Attribute::NoImplicitFloat))
46253ca95b02SDimitry Andric return false;
46263ca95b02SDimitry Andric
46274ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
46283ca95b02SDimitry Andric
46293ca95b02SDimitry Andric // Use the bottom up slp vectorizer to construct chains that start with
46303ca95b02SDimitry Andric // store instructions.
46315517e702SDimitry Andric BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
46323ca95b02SDimitry Andric
46333ca95b02SDimitry Andric // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
46343ca95b02SDimitry Andric // delete instructions.
46353ca95b02SDimitry Andric
46363ca95b02SDimitry Andric // Scan the blocks in the function in post order.
46373ca95b02SDimitry Andric for (auto BB : post_order(&F.getEntryBlock())) {
46383ca95b02SDimitry Andric collectSeedInstructions(BB);
46393ca95b02SDimitry Andric
46403ca95b02SDimitry Andric // Vectorize trees that end at stores.
46413ca95b02SDimitry Andric if (!Stores.empty()) {
46424ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
46433ca95b02SDimitry Andric << " underlying objects.\n");
46443ca95b02SDimitry Andric Changed |= vectorizeStoreChains(R);
46453ca95b02SDimitry Andric }
46463ca95b02SDimitry Andric
46473ca95b02SDimitry Andric // Vectorize trees that end at reductions.
46483ca95b02SDimitry Andric Changed |= vectorizeChainsInBlock(BB, R);
46493ca95b02SDimitry Andric
46503ca95b02SDimitry Andric // Vectorize the index computations of getelementptr instructions. This
46513ca95b02SDimitry Andric // is primarily intended to catch gather-like idioms ending at
46523ca95b02SDimitry Andric // non-consecutive loads.
46533ca95b02SDimitry Andric if (!GEPs.empty()) {
46544ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
46553ca95b02SDimitry Andric << " underlying objects.\n");
46563ca95b02SDimitry Andric Changed |= vectorizeGEPIndices(BB, R);
46573ca95b02SDimitry Andric }
46583ca95b02SDimitry Andric }
46593ca95b02SDimitry Andric
46603ca95b02SDimitry Andric if (Changed) {
46614ba319b5SDimitry Andric R.optimizeGatherSequence();
46624ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
46634ba319b5SDimitry Andric LLVM_DEBUG(verifyFunction(F));
46643ca95b02SDimitry Andric }
46653ca95b02SDimitry Andric return Changed;
46663ca95b02SDimitry Andric }
4667284c1978SDimitry Andric
46684ba319b5SDimitry Andric /// Check that the Values in the slice in VL array are still existent in
4669f37b6182SDimitry Andric /// the WeakTrackingVH array.
4670f785676fSDimitry Andric /// Vectorization of part of the VL array may cause later values in the VL array
4671f37b6182SDimitry Andric /// to become invalid. We track when this has happened in the WeakTrackingVH
4672f37b6182SDimitry Andric /// array.
hasValueBeenRAUWed(ArrayRef<Value * > VL,ArrayRef<WeakTrackingVH> VH,unsigned SliceBegin,unsigned SliceSize)4673f37b6182SDimitry Andric static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4674f37b6182SDimitry Andric ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4675f37b6182SDimitry Andric unsigned SliceSize) {
4676ff0cc061SDimitry Andric VL = VL.slice(SliceBegin, SliceSize);
4677ff0cc061SDimitry Andric VH = VH.slice(SliceBegin, SliceSize);
4678ff0cc061SDimitry Andric return !std::equal(VL.begin(), VL.end(), VH.begin());
4679f785676fSDimitry Andric }
4680f785676fSDimitry Andric
vectorizeStoreChain(ArrayRef<Value * > Chain,BoUpSLP & R,unsigned VecRegSize)4681d88c1a5aSDimitry Andric bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4682875ed548SDimitry Andric unsigned VecRegSize) {
46834ba319b5SDimitry Andric const unsigned ChainLen = Chain.size();
46844ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
4685f785676fSDimitry Andric << "\n");
46864ba319b5SDimitry Andric const unsigned Sz = R.getVectorElementSize(Chain[0]);
46874ba319b5SDimitry Andric const unsigned VF = VecRegSize / Sz;
4688f785676fSDimitry Andric
4689f785676fSDimitry Andric if (!isPowerOf2_32(Sz) || VF < 2)
4690f785676fSDimitry Andric return false;
4691f785676fSDimitry Andric
469291bc56edSDimitry Andric // Keep track of values that were deleted by vectorizing in the loop below.
46934ba319b5SDimitry Andric const SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4694f785676fSDimitry Andric
4695f785676fSDimitry Andric bool Changed = false;
4696f785676fSDimitry Andric // Look for profitable vectorizable trees at all offsets, starting at zero.
46974ba319b5SDimitry Andric for (unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
4698f785676fSDimitry Andric
4699f785676fSDimitry Andric // Check that a previous iteration of this loop did not delete the Value.
4700f785676fSDimitry Andric if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4701f785676fSDimitry Andric continue;
4702f785676fSDimitry Andric
47034ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
4704f785676fSDimitry Andric << "\n");
4705f785676fSDimitry Andric ArrayRef<Value *> Operands = Chain.slice(i, VF);
4706f785676fSDimitry Andric
4707f785676fSDimitry Andric R.buildTree(Operands);
4708d88c1a5aSDimitry Andric if (R.isTreeTinyAndNotFullyVectorizable())
4709d88c1a5aSDimitry Andric continue;
4710d88c1a5aSDimitry Andric
47113ca95b02SDimitry Andric R.computeMinimumValueSizes();
4712f785676fSDimitry Andric
4713f785676fSDimitry Andric int Cost = R.getTreeCost();
4714f785676fSDimitry Andric
47154ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF
47164ba319b5SDimitry Andric << "\n");
4717d88c1a5aSDimitry Andric if (Cost < -SLPCostThreshold) {
47184ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
47192cab237bSDimitry Andric
47205517e702SDimitry Andric using namespace ore;
47212cab237bSDimitry Andric
47225517e702SDimitry Andric R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
47235517e702SDimitry Andric cast<StoreInst>(Chain[i]))
47245517e702SDimitry Andric << "Stores SLP vectorized with cost " << NV("Cost", Cost)
47255517e702SDimitry Andric << " and with tree size "
47265517e702SDimitry Andric << NV("TreeSize", R.getTreeSize()));
47275517e702SDimitry Andric
4728f785676fSDimitry Andric R.vectorizeTree();
4729f785676fSDimitry Andric
4730f785676fSDimitry Andric // Move to the next bundle.
4731f785676fSDimitry Andric i += VF - 1;
4732f785676fSDimitry Andric Changed = true;
4733f785676fSDimitry Andric }
4734f785676fSDimitry Andric }
4735f785676fSDimitry Andric
4736f785676fSDimitry Andric return Changed;
4737f785676fSDimitry Andric }
4738f785676fSDimitry Andric
vectorizeStores(ArrayRef<StoreInst * > Stores,BoUpSLP & R)47393ca95b02SDimitry Andric bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4740d88c1a5aSDimitry Andric BoUpSLP &R) {
47412cab237bSDimitry Andric SetVector<StoreInst *> Heads;
47422cab237bSDimitry Andric SmallDenseSet<StoreInst *> Tails;
4743ff0cc061SDimitry Andric SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4744f785676fSDimitry Andric
4745f785676fSDimitry Andric // We may run into multiple chains that merge into a single chain. We mark the
4746f785676fSDimitry Andric // stores that we vectorized so that we don't visit the same store twice.
4747f785676fSDimitry Andric BoUpSLP::ValueSet VectorizedStores;
4748f785676fSDimitry Andric bool Changed = false;
4749f785676fSDimitry Andric
47502cab237bSDimitry Andric // Do a quadratic search on all of the given stores in reverse order and find
4751f785676fSDimitry Andric // all of the pairs of stores that follow each other.
47527d523365SDimitry Andric SmallVector<unsigned, 16> IndexQueue;
47532cab237bSDimitry Andric unsigned E = Stores.size();
47542cab237bSDimitry Andric IndexQueue.resize(E - 1);
47552cab237bSDimitry Andric for (unsigned I = E; I > 0; --I) {
47562cab237bSDimitry Andric unsigned Idx = I - 1;
47577d523365SDimitry Andric // If a store has multiple consecutive store candidates, search Stores
47582cab237bSDimitry Andric // array according to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
47597d523365SDimitry Andric // This is because usually pairing with immediate succeeding or preceding
47607d523365SDimitry Andric // candidate create the best chance to find slp vectorization opportunity.
47612cab237bSDimitry Andric unsigned Offset = 1;
47622cab237bSDimitry Andric unsigned Cnt = 0;
47632cab237bSDimitry Andric for (unsigned J = 0; J < E - 1; ++J, ++Offset) {
47642cab237bSDimitry Andric if (Idx >= Offset) {
47652cab237bSDimitry Andric IndexQueue[Cnt] = Idx - Offset;
47662cab237bSDimitry Andric ++Cnt;
47672cab237bSDimitry Andric }
47682cab237bSDimitry Andric if (Idx + Offset < E) {
47692cab237bSDimitry Andric IndexQueue[Cnt] = Idx + Offset;
47702cab237bSDimitry Andric ++Cnt;
47712cab237bSDimitry Andric }
47722cab237bSDimitry Andric }
47737d523365SDimitry Andric
47742cab237bSDimitry Andric for (auto K : IndexQueue) {
47752cab237bSDimitry Andric if (isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE)) {
47762cab237bSDimitry Andric Tails.insert(Stores[Idx]);
47772cab237bSDimitry Andric Heads.insert(Stores[K]);
47782cab237bSDimitry Andric ConsecutiveChain[Stores[K]] = Stores[Idx];
47797d523365SDimitry Andric break;
4780f785676fSDimitry Andric }
4781f785676fSDimitry Andric }
4782f785676fSDimitry Andric }
4783f785676fSDimitry Andric
4784f785676fSDimitry Andric // For stores that start but don't end a link in the chain:
47852cab237bSDimitry Andric for (auto *SI : llvm::reverse(Heads)) {
47862cab237bSDimitry Andric if (Tails.count(SI))
4787f785676fSDimitry Andric continue;
4788f785676fSDimitry Andric
4789f785676fSDimitry Andric // We found a store instr that starts a chain. Now follow the chain and try
4790f785676fSDimitry Andric // to vectorize it.
4791f785676fSDimitry Andric BoUpSLP::ValueList Operands;
47922cab237bSDimitry Andric StoreInst *I = SI;
4793f785676fSDimitry Andric // Collect the chain into a list.
47942cab237bSDimitry Andric while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
4795f785676fSDimitry Andric Operands.push_back(I);
4796f785676fSDimitry Andric // Move to the next value in the chain.
4797f785676fSDimitry Andric I = ConsecutiveChain[I];
4798f785676fSDimitry Andric }
4799f785676fSDimitry Andric
4800875ed548SDimitry Andric // FIXME: Is division-by-2 the correct step? Should we assert that the
4801875ed548SDimitry Andric // register size is a power-of-2?
4802d88c1a5aSDimitry Andric for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4803d88c1a5aSDimitry Andric Size /= 2) {
4804d88c1a5aSDimitry Andric if (vectorizeStoreChain(Operands, R, Size)) {
4805f785676fSDimitry Andric // Mark the vectorized stores so that we don't vectorize them again.
4806f785676fSDimitry Andric VectorizedStores.insert(Operands.begin(), Operands.end());
4807875ed548SDimitry Andric Changed = true;
4808875ed548SDimitry Andric break;
4809875ed548SDimitry Andric }
4810875ed548SDimitry Andric }
4811f785676fSDimitry Andric }
4812f785676fSDimitry Andric
4813f785676fSDimitry Andric return Changed;
4814f785676fSDimitry Andric }
4815f785676fSDimitry Andric
collectSeedInstructions(BasicBlock * BB)48163ca95b02SDimitry Andric void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
48173ca95b02SDimitry Andric // Initialize the collections. We will make a single pass over the block.
48183ca95b02SDimitry Andric Stores.clear();
48193ca95b02SDimitry Andric GEPs.clear();
48203ca95b02SDimitry Andric
48213ca95b02SDimitry Andric // Visit the store and getelementptr instructions in BB and organize them in
48223ca95b02SDimitry Andric // Stores and GEPs according to the underlying objects of their pointer
48233ca95b02SDimitry Andric // operands.
4824875ed548SDimitry Andric for (Instruction &I : *BB) {
48253ca95b02SDimitry Andric // Ignore store instructions that are volatile or have a pointer operand
48263ca95b02SDimitry Andric // that doesn't point to a scalar type.
48273ca95b02SDimitry Andric if (auto *SI = dyn_cast<StoreInst>(&I)) {
4828f785676fSDimitry Andric if (!SI->isSimple())
4829f785676fSDimitry Andric continue;
48303ca95b02SDimitry Andric if (!isValidElementType(SI->getValueOperand()->getType()))
483191bc56edSDimitry Andric continue;
48323ca95b02SDimitry Andric Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4833284c1978SDimitry Andric }
4834284c1978SDimitry Andric
48353ca95b02SDimitry Andric // Ignore getelementptr instructions that have more than one index, a
48363ca95b02SDimitry Andric // constant index, or a pointer operand that doesn't point to a scalar
48373ca95b02SDimitry Andric // type.
48383ca95b02SDimitry Andric else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
48393ca95b02SDimitry Andric auto Idx = GEP->idx_begin()->get();
48403ca95b02SDimitry Andric if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
48413ca95b02SDimitry Andric continue;
48423ca95b02SDimitry Andric if (!isValidElementType(Idx->getType()))
48433ca95b02SDimitry Andric continue;
48443ca95b02SDimitry Andric if (GEP->getType()->isVectorTy())
48453ca95b02SDimitry Andric continue;
4846*b5893f02SDimitry Andric GEPs[GEP->getPointerOperand()].push_back(GEP);
48473ca95b02SDimitry Andric }
48483ca95b02SDimitry Andric }
48493ca95b02SDimitry Andric }
48503ca95b02SDimitry Andric
tryToVectorizePair(Value * A,Value * B,BoUpSLP & R)48513ca95b02SDimitry Andric bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4852f785676fSDimitry Andric if (!A || !B)
4853f785676fSDimitry Andric return false;
4854284c1978SDimitry Andric Value *VL[] = { A, B };
48554ba319b5SDimitry Andric return tryToVectorizeList(VL, R, /*UserCost=*/0, true);
4856284c1978SDimitry Andric }
4857284c1978SDimitry Andric
tryToVectorizeList(ArrayRef<Value * > VL,BoUpSLP & R,int UserCost,bool AllowReorder)48583ca95b02SDimitry Andric bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
48594ba319b5SDimitry Andric int UserCost, bool AllowReorder) {
4860f785676fSDimitry Andric if (VL.size() < 2)
4861f785676fSDimitry Andric return false;
4862f785676fSDimitry Andric
48634ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
48644ba319b5SDimitry Andric << VL.size() << ".\n");
4865284c1978SDimitry Andric
48664ba319b5SDimitry Andric // Check that all of the parts are scalar instructions of the same type,
48674ba319b5SDimitry Andric // we permit an alternate opcode via InstructionsState.
48684ba319b5SDimitry Andric InstructionsState S = getSameOpcode(VL);
48694ba319b5SDimitry Andric if (!S.getOpcode())
4870f785676fSDimitry Andric return false;
4871f785676fSDimitry Andric
48724ba319b5SDimitry Andric Instruction *I0 = cast<Instruction>(S.OpValue);
48733ca95b02SDimitry Andric unsigned Sz = R.getVectorElementSize(I0);
4874d88c1a5aSDimitry Andric unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4875d88c1a5aSDimitry Andric unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
48762cab237bSDimitry Andric if (MaxVF < 2) {
48772cab237bSDimitry Andric R.getORE()->emit([&]() {
48784ba319b5SDimitry Andric return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
48792cab237bSDimitry Andric << "Cannot SLP vectorize list: vectorization factor "
48802cab237bSDimitry Andric << "less than 2 is not supported";
48812cab237bSDimitry Andric });
4882f785676fSDimitry Andric return false;
4883284c1978SDimitry Andric }
4884284c1978SDimitry Andric
48852cab237bSDimitry Andric for (Value *V : VL) {
48862cab237bSDimitry Andric Type *Ty = V->getType();
48872cab237bSDimitry Andric if (!isValidElementType(Ty)) {
48884ba319b5SDimitry Andric // NOTE: the following will give user internal llvm type name, which may
48894ba319b5SDimitry Andric // not be useful.
48902cab237bSDimitry Andric R.getORE()->emit([&]() {
48912cab237bSDimitry Andric std::string type_str;
48922cab237bSDimitry Andric llvm::raw_string_ostream rso(type_str);
48932cab237bSDimitry Andric Ty->print(rso);
48944ba319b5SDimitry Andric return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
48952cab237bSDimitry Andric << "Cannot SLP vectorize list: type "
48962cab237bSDimitry Andric << rso.str() + " is unsupported by vectorizer";
48972cab237bSDimitry Andric });
48982cab237bSDimitry Andric return false;
48992cab237bSDimitry Andric }
49002cab237bSDimitry Andric }
49012cab237bSDimitry Andric
4902f785676fSDimitry Andric bool Changed = false;
49032cab237bSDimitry Andric bool CandidateFound = false;
49042cab237bSDimitry Andric int MinCost = SLPCostThreshold;
4905f785676fSDimitry Andric
490691bc56edSDimitry Andric // Keep track of values that were deleted by vectorizing in the loop below.
4907f37b6182SDimitry Andric SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4908f785676fSDimitry Andric
4909d88c1a5aSDimitry Andric unsigned NextInst = 0, MaxInst = VL.size();
4910d88c1a5aSDimitry Andric for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4911d88c1a5aSDimitry Andric VF /= 2) {
4912d88c1a5aSDimitry Andric // No actual vectorization should happen, if number of parts is the same as
4913d88c1a5aSDimitry Andric // provided vectorization factor (i.e. the scalar type is used for vector
4914d88c1a5aSDimitry Andric // code during codegen).
4915d88c1a5aSDimitry Andric auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4916d88c1a5aSDimitry Andric if (TTI->getNumberOfParts(VecTy) == VF)
4917d88c1a5aSDimitry Andric continue;
4918d88c1a5aSDimitry Andric for (unsigned I = NextInst; I < MaxInst; ++I) {
4919f785676fSDimitry Andric unsigned OpsWidth = 0;
4920f785676fSDimitry Andric
4921d88c1a5aSDimitry Andric if (I + VF > MaxInst)
4922d88c1a5aSDimitry Andric OpsWidth = MaxInst - I;
4923f785676fSDimitry Andric else
4924f785676fSDimitry Andric OpsWidth = VF;
4925f785676fSDimitry Andric
4926f785676fSDimitry Andric if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4927f785676fSDimitry Andric break;
4928f785676fSDimitry Andric
4929f785676fSDimitry Andric // Check that a previous iteration of this loop did not delete the Value.
4930d88c1a5aSDimitry Andric if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4931f785676fSDimitry Andric continue;
4932f785676fSDimitry Andric
49334ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4934f785676fSDimitry Andric << "\n");
4935d88c1a5aSDimitry Andric ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4936f785676fSDimitry Andric
4937782f2e69SDimitry Andric R.buildTree(Ops);
49384ba319b5SDimitry Andric Optional<ArrayRef<unsigned>> Order = R.bestOrder();
4939d88c1a5aSDimitry Andric // TODO: check if we can allow reordering for more cases.
49404ba319b5SDimitry Andric if (AllowReorder && Order) {
49414ba319b5SDimitry Andric // TODO: reorder tree nodes without tree rebuilding.
4942d88c1a5aSDimitry Andric // Conceptually, there is nothing actually preventing us from trying to
4943d88c1a5aSDimitry Andric // reorder a larger list. In fact, we do exactly this when vectorizing
49446bc11b14SDimitry Andric // reductions. However, at this point, we only expect to get here when
49456bc11b14SDimitry Andric // there are exactly two operations.
494639d628a0SDimitry Andric assert(Ops.size() == 2);
494739d628a0SDimitry Andric Value *ReorderedOps[] = {Ops[1], Ops[0]};
494839d628a0SDimitry Andric R.buildTree(ReorderedOps, None);
494939d628a0SDimitry Andric }
4950d88c1a5aSDimitry Andric if (R.isTreeTinyAndNotFullyVectorizable())
4951d88c1a5aSDimitry Andric continue;
4952d88c1a5aSDimitry Andric
49533ca95b02SDimitry Andric R.computeMinimumValueSizes();
49544ba319b5SDimitry Andric int Cost = R.getTreeCost() - UserCost;
49552cab237bSDimitry Andric CandidateFound = true;
49562cab237bSDimitry Andric MinCost = std::min(MinCost, Cost);
4957f785676fSDimitry Andric
4958f785676fSDimitry Andric if (Cost < -SLPCostThreshold) {
49594ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
49605517e702SDimitry Andric R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
49615517e702SDimitry Andric cast<Instruction>(Ops[0]))
49625517e702SDimitry Andric << "SLP vectorized with cost " << ore::NV("Cost", Cost)
49635517e702SDimitry Andric << " and with tree size "
49645517e702SDimitry Andric << ore::NV("TreeSize", R.getTreeSize()));
49655517e702SDimitry Andric
4966782f2e69SDimitry Andric R.vectorizeTree();
4967f785676fSDimitry Andric // Move to the next bundle.
4968d88c1a5aSDimitry Andric I += VF - 1;
4969d88c1a5aSDimitry Andric NextInst = I + 1;
4970f785676fSDimitry Andric Changed = true;
4971f785676fSDimitry Andric }
4972f785676fSDimitry Andric }
4973d88c1a5aSDimitry Andric }
4974f785676fSDimitry Andric
49752cab237bSDimitry Andric if (!Changed && CandidateFound) {
49762cab237bSDimitry Andric R.getORE()->emit([&]() {
49774ba319b5SDimitry Andric return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
49782cab237bSDimitry Andric << "List vectorization was possible but not beneficial with cost "
49792cab237bSDimitry Andric << ore::NV("Cost", MinCost) << " >= "
49802cab237bSDimitry Andric << ore::NV("Treshold", -SLPCostThreshold);
49812cab237bSDimitry Andric });
49822cab237bSDimitry Andric } else if (!Changed) {
49832cab237bSDimitry Andric R.getORE()->emit([&]() {
49844ba319b5SDimitry Andric return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
49852cab237bSDimitry Andric << "Cannot SLP vectorize list: vectorization was impossible"
49862cab237bSDimitry Andric << " with available vectorization factors";
49872cab237bSDimitry Andric });
49882cab237bSDimitry Andric }
4989f785676fSDimitry Andric return Changed;
4990284c1978SDimitry Andric }
4991284c1978SDimitry Andric
tryToVectorize(Instruction * I,BoUpSLP & R)49922cab237bSDimitry Andric bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
49932cab237bSDimitry Andric if (!I)
4994f785676fSDimitry Andric return false;
4995f785676fSDimitry Andric
49962cab237bSDimitry Andric if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
49972cab237bSDimitry Andric return false;
49982cab237bSDimitry Andric
49992cab237bSDimitry Andric Value *P = I->getParent();
50007a7e6055SDimitry Andric
50017a7e6055SDimitry Andric // Vectorize in current basic block only.
50022cab237bSDimitry Andric auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
50032cab237bSDimitry Andric auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
50047a7e6055SDimitry Andric if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
50057a7e6055SDimitry Andric return false;
50067a7e6055SDimitry Andric
5007284c1978SDimitry Andric // Try to vectorize V.
50087a7e6055SDimitry Andric if (tryToVectorizePair(Op0, Op1, R))
5009284c1978SDimitry Andric return true;
5010284c1978SDimitry Andric
50117a7e6055SDimitry Andric auto *A = dyn_cast<BinaryOperator>(Op0);
50127a7e6055SDimitry Andric auto *B = dyn_cast<BinaryOperator>(Op1);
5013284c1978SDimitry Andric // Try to skip B.
5014284c1978SDimitry Andric if (B && B->hasOneUse()) {
50157a7e6055SDimitry Andric auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
50167a7e6055SDimitry Andric auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
50177a7e6055SDimitry Andric if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
5018284c1978SDimitry Andric return true;
50197a7e6055SDimitry Andric if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
5020284c1978SDimitry Andric return true;
5021284c1978SDimitry Andric }
5022284c1978SDimitry Andric
5023284c1978SDimitry Andric // Try to skip A.
5024284c1978SDimitry Andric if (A && A->hasOneUse()) {
50257a7e6055SDimitry Andric auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
50267a7e6055SDimitry Andric auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
50277a7e6055SDimitry Andric if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
50287a7e6055SDimitry Andric return true;
50297a7e6055SDimitry Andric if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
5030284c1978SDimitry Andric return true;
5031284c1978SDimitry Andric }
50327a7e6055SDimitry Andric return false;
5033284c1978SDimitry Andric }
5034284c1978SDimitry Andric
50354ba319b5SDimitry Andric /// Generate a shuffle mask to be used in a reduction tree.
5036f785676fSDimitry Andric ///
5037f785676fSDimitry Andric /// \param VecLen The length of the vector to be reduced.
5038f785676fSDimitry Andric /// \param NumEltsToRdx The number of elements that should be reduced in the
5039f785676fSDimitry Andric /// vector.
5040f785676fSDimitry Andric /// \param IsPairwise Whether the reduction is a pairwise or splitting
5041f785676fSDimitry Andric /// reduction. A pairwise reduction will generate a mask of
5042f785676fSDimitry Andric /// <0,2,...> or <1,3,..> while a splitting reduction will generate
5043f785676fSDimitry Andric /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
5044f785676fSDimitry Andric /// \param IsLeft True will generate a mask of even elements, odd otherwise.
createRdxShuffleMask(unsigned VecLen,unsigned NumEltsToRdx,bool IsPairwise,bool IsLeft,IRBuilder<> & Builder)5045f785676fSDimitry Andric static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
5046f785676fSDimitry Andric bool IsPairwise, bool IsLeft,
5047f785676fSDimitry Andric IRBuilder<> &Builder) {
5048f785676fSDimitry Andric assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
5049f785676fSDimitry Andric
5050f785676fSDimitry Andric SmallVector<Constant *, 32> ShuffleMask(
5051f785676fSDimitry Andric VecLen, UndefValue::get(Builder.getInt32Ty()));
5052f785676fSDimitry Andric
5053f785676fSDimitry Andric if (IsPairwise)
5054f785676fSDimitry Andric // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
5055f785676fSDimitry Andric for (unsigned i = 0; i != NumEltsToRdx; ++i)
5056f785676fSDimitry Andric ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
5057f785676fSDimitry Andric else
5058f785676fSDimitry Andric // Move the upper half of the vector to the lower half.
5059f785676fSDimitry Andric for (unsigned i = 0; i != NumEltsToRdx; ++i)
5060f785676fSDimitry Andric ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
5061f785676fSDimitry Andric
5062f785676fSDimitry Andric return ConstantVector::get(ShuffleMask);
5063f785676fSDimitry Andric }
5064f785676fSDimitry Andric
5065d88c1a5aSDimitry Andric namespace {
50662cab237bSDimitry Andric
5067f785676fSDimitry Andric /// Model horizontal reductions.
5068f785676fSDimitry Andric ///
5069f785676fSDimitry Andric /// A horizontal reduction is a tree of reduction operations (currently add and
5070f785676fSDimitry Andric /// fadd) that has operations that can be put into a vector as its leaf.
5071f785676fSDimitry Andric /// For example, this tree:
5072f785676fSDimitry Andric ///
5073f785676fSDimitry Andric /// mul mul mul mul
5074f785676fSDimitry Andric /// \ / \ /
5075f785676fSDimitry Andric /// + +
5076f785676fSDimitry Andric /// \ /
5077f785676fSDimitry Andric /// +
5078f785676fSDimitry Andric /// This tree has "mul" as its reduced values and "+" as its reduction
5079f785676fSDimitry Andric /// operations. A reduction might be feeding into a store or a binary operation
5080f785676fSDimitry Andric /// feeding a phi.
5081f785676fSDimitry Andric /// ...
5082f785676fSDimitry Andric /// \ /
5083f785676fSDimitry Andric /// +
5084f785676fSDimitry Andric /// |
5085f785676fSDimitry Andric /// phi +=
5086f785676fSDimitry Andric ///
5087f785676fSDimitry Andric /// Or:
5088f785676fSDimitry Andric /// ...
5089f785676fSDimitry Andric /// \ /
5090f785676fSDimitry Andric /// +
5091f785676fSDimitry Andric /// |
5092f785676fSDimitry Andric /// *p =
5093f785676fSDimitry Andric ///
5094f785676fSDimitry Andric class HorizontalReduction {
50952cab237bSDimitry Andric using ReductionOpsType = SmallVector<Value *, 16>;
50962cab237bSDimitry Andric using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
50972cab237bSDimitry Andric ReductionOpsListType ReductionOps;
5098f785676fSDimitry Andric SmallVector<Value *, 32> ReducedVals;
50997a7e6055SDimitry Andric // Use map vector to make stable output.
51007a7e6055SDimitry Andric MapVector<Instruction *, Value *> ExtraArgs;
5101f785676fSDimitry Andric
51022cab237bSDimitry Andric /// Kind of the reduction data.
51032cab237bSDimitry Andric enum ReductionKind {
51042cab237bSDimitry Andric RK_None, /// Not a reduction.
51052cab237bSDimitry Andric RK_Arithmetic, /// Binary reduction data.
51062cab237bSDimitry Andric RK_Min, /// Minimum reduction data.
51072cab237bSDimitry Andric RK_UMin, /// Unsigned minimum reduction data.
51082cab237bSDimitry Andric RK_Max, /// Maximum reduction data.
51092cab237bSDimitry Andric RK_UMax, /// Unsigned maximum reduction data.
51102cab237bSDimitry Andric };
5111f785676fSDimitry Andric
51122cab237bSDimitry Andric /// Contains info about operation, like its opcode, left and right operands.
51132cab237bSDimitry Andric class OperationData {
51142cab237bSDimitry Andric /// Opcode of the instruction.
51152cab237bSDimitry Andric unsigned Opcode = 0;
51162cab237bSDimitry Andric
51172cab237bSDimitry Andric /// Left operand of the reduction operation.
51182cab237bSDimitry Andric Value *LHS = nullptr;
51192cab237bSDimitry Andric
51202cab237bSDimitry Andric /// Right operand of the reduction operation.
51212cab237bSDimitry Andric Value *RHS = nullptr;
51222cab237bSDimitry Andric
51232cab237bSDimitry Andric /// Kind of the reduction operation.
51242cab237bSDimitry Andric ReductionKind Kind = RK_None;
51252cab237bSDimitry Andric
51262cab237bSDimitry Andric /// True if float point min/max reduction has no NaNs.
51272cab237bSDimitry Andric bool NoNaN = false;
51282cab237bSDimitry Andric
51292cab237bSDimitry Andric /// Checks if the reduction operation can be vectorized.
isVectorizable() const51302cab237bSDimitry Andric bool isVectorizable() const {
51312cab237bSDimitry Andric return LHS && RHS &&
5132*b5893f02SDimitry Andric // We currently only support add/mul/logical && min/max reductions.
51332cab237bSDimitry Andric ((Kind == RK_Arithmetic &&
5134*b5893f02SDimitry Andric (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
5135*b5893f02SDimitry Andric Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
5136*b5893f02SDimitry Andric Opcode == Instruction::And || Opcode == Instruction::Or ||
5137*b5893f02SDimitry Andric Opcode == Instruction::Xor)) ||
51382cab237bSDimitry Andric ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
51392cab237bSDimitry Andric (Kind == RK_Min || Kind == RK_Max)) ||
51402cab237bSDimitry Andric (Opcode == Instruction::ICmp &&
51412cab237bSDimitry Andric (Kind == RK_UMin || Kind == RK_UMax)));
51422cab237bSDimitry Andric }
51432cab237bSDimitry Andric
51442cab237bSDimitry Andric /// Creates reduction operation with the current opcode.
createOp(IRBuilder<> & Builder,const Twine & Name) const51452cab237bSDimitry Andric Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
51462cab237bSDimitry Andric assert(isVectorizable() &&
51472cab237bSDimitry Andric "Expected add|fadd or min/max reduction operation.");
51482cab237bSDimitry Andric Value *Cmp;
51492cab237bSDimitry Andric switch (Kind) {
51502cab237bSDimitry Andric case RK_Arithmetic:
51512cab237bSDimitry Andric return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
51522cab237bSDimitry Andric Name);
51532cab237bSDimitry Andric case RK_Min:
51542cab237bSDimitry Andric Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
51552cab237bSDimitry Andric : Builder.CreateFCmpOLT(LHS, RHS);
51562cab237bSDimitry Andric break;
51572cab237bSDimitry Andric case RK_Max:
51582cab237bSDimitry Andric Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
51592cab237bSDimitry Andric : Builder.CreateFCmpOGT(LHS, RHS);
51602cab237bSDimitry Andric break;
51612cab237bSDimitry Andric case RK_UMin:
51622cab237bSDimitry Andric assert(Opcode == Instruction::ICmp && "Expected integer types.");
51632cab237bSDimitry Andric Cmp = Builder.CreateICmpULT(LHS, RHS);
51642cab237bSDimitry Andric break;
51652cab237bSDimitry Andric case RK_UMax:
51662cab237bSDimitry Andric assert(Opcode == Instruction::ICmp && "Expected integer types.");
51672cab237bSDimitry Andric Cmp = Builder.CreateICmpUGT(LHS, RHS);
51682cab237bSDimitry Andric break;
51692cab237bSDimitry Andric case RK_None:
51702cab237bSDimitry Andric llvm_unreachable("Unknown reduction operation.");
51712cab237bSDimitry Andric }
51722cab237bSDimitry Andric return Builder.CreateSelect(Cmp, LHS, RHS, Name);
51732cab237bSDimitry Andric }
51742cab237bSDimitry Andric
51752cab237bSDimitry Andric public:
51762cab237bSDimitry Andric explicit OperationData() = default;
51772cab237bSDimitry Andric
51782cab237bSDimitry Andric /// Construction for reduced values. They are identified by opcode only and
51792cab237bSDimitry Andric /// don't have associated LHS/RHS values.
OperationData(Value * V)51802cab237bSDimitry Andric explicit OperationData(Value *V) {
51812cab237bSDimitry Andric if (auto *I = dyn_cast<Instruction>(V))
51822cab237bSDimitry Andric Opcode = I->getOpcode();
51832cab237bSDimitry Andric }
51842cab237bSDimitry Andric
51852cab237bSDimitry Andric /// Constructor for reduction operations with opcode and its left and
51862cab237bSDimitry Andric /// right operands.
OperationData(unsigned Opcode,Value * LHS,Value * RHS,ReductionKind Kind,bool NoNaN=false)51872cab237bSDimitry Andric OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
51882cab237bSDimitry Andric bool NoNaN = false)
51892cab237bSDimitry Andric : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
51902cab237bSDimitry Andric assert(Kind != RK_None && "One of the reduction operations is expected.");
51912cab237bSDimitry Andric }
51922cab237bSDimitry Andric
operator bool() const51932cab237bSDimitry Andric explicit operator bool() const { return Opcode; }
51942cab237bSDimitry Andric
51952cab237bSDimitry Andric /// Get the index of the first operand.
getFirstOperandIndex() const51962cab237bSDimitry Andric unsigned getFirstOperandIndex() const {
51972cab237bSDimitry Andric assert(!!*this && "The opcode is not set.");
51982cab237bSDimitry Andric switch (Kind) {
51992cab237bSDimitry Andric case RK_Min:
52002cab237bSDimitry Andric case RK_UMin:
52012cab237bSDimitry Andric case RK_Max:
52022cab237bSDimitry Andric case RK_UMax:
52032cab237bSDimitry Andric return 1;
52042cab237bSDimitry Andric case RK_Arithmetic:
52052cab237bSDimitry Andric case RK_None:
52062cab237bSDimitry Andric break;
52072cab237bSDimitry Andric }
52082cab237bSDimitry Andric return 0;
52092cab237bSDimitry Andric }
52102cab237bSDimitry Andric
52112cab237bSDimitry Andric /// Total number of operands in the reduction operation.
getNumberOfOperands() const52122cab237bSDimitry Andric unsigned getNumberOfOperands() const {
52132cab237bSDimitry Andric assert(Kind != RK_None && !!*this && LHS && RHS &&
52142cab237bSDimitry Andric "Expected reduction operation.");
52152cab237bSDimitry Andric switch (Kind) {
52162cab237bSDimitry Andric case RK_Arithmetic:
52172cab237bSDimitry Andric return 2;
52182cab237bSDimitry Andric case RK_Min:
52192cab237bSDimitry Andric case RK_UMin:
52202cab237bSDimitry Andric case RK_Max:
52212cab237bSDimitry Andric case RK_UMax:
52222cab237bSDimitry Andric return 3;
52232cab237bSDimitry Andric case RK_None:
52242cab237bSDimitry Andric break;
52252cab237bSDimitry Andric }
52262cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
52272cab237bSDimitry Andric }
52282cab237bSDimitry Andric
52292cab237bSDimitry Andric /// Checks if the operation has the same parent as \p P.
hasSameParent(Instruction * I,Value * P,bool IsRedOp) const52302cab237bSDimitry Andric bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
52312cab237bSDimitry Andric assert(Kind != RK_None && !!*this && LHS && RHS &&
52322cab237bSDimitry Andric "Expected reduction operation.");
52332cab237bSDimitry Andric if (!IsRedOp)
52342cab237bSDimitry Andric return I->getParent() == P;
52352cab237bSDimitry Andric switch (Kind) {
52362cab237bSDimitry Andric case RK_Arithmetic:
52372cab237bSDimitry Andric // Arithmetic reduction operation must be used once only.
52382cab237bSDimitry Andric return I->getParent() == P;
52392cab237bSDimitry Andric case RK_Min:
52402cab237bSDimitry Andric case RK_UMin:
52412cab237bSDimitry Andric case RK_Max:
52422cab237bSDimitry Andric case RK_UMax: {
52432cab237bSDimitry Andric // SelectInst must be used twice while the condition op must have single
52442cab237bSDimitry Andric // use only.
52452cab237bSDimitry Andric auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
52462cab237bSDimitry Andric return I->getParent() == P && Cmp && Cmp->getParent() == P;
52472cab237bSDimitry Andric }
52482cab237bSDimitry Andric case RK_None:
52492cab237bSDimitry Andric break;
52502cab237bSDimitry Andric }
52512cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
52522cab237bSDimitry Andric }
52532cab237bSDimitry Andric /// Expected number of uses for reduction operations/reduced values.
hasRequiredNumberOfUses(Instruction * I,bool IsReductionOp) const52542cab237bSDimitry Andric bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
52552cab237bSDimitry Andric assert(Kind != RK_None && !!*this && LHS && RHS &&
52562cab237bSDimitry Andric "Expected reduction operation.");
52572cab237bSDimitry Andric switch (Kind) {
52582cab237bSDimitry Andric case RK_Arithmetic:
52592cab237bSDimitry Andric return I->hasOneUse();
52602cab237bSDimitry Andric case RK_Min:
52612cab237bSDimitry Andric case RK_UMin:
52622cab237bSDimitry Andric case RK_Max:
52632cab237bSDimitry Andric case RK_UMax:
52642cab237bSDimitry Andric return I->hasNUses(2) &&
52652cab237bSDimitry Andric (!IsReductionOp ||
52662cab237bSDimitry Andric cast<SelectInst>(I)->getCondition()->hasOneUse());
52672cab237bSDimitry Andric case RK_None:
52682cab237bSDimitry Andric break;
52692cab237bSDimitry Andric }
52702cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
52712cab237bSDimitry Andric }
52722cab237bSDimitry Andric
52732cab237bSDimitry Andric /// Initializes the list of reduction operations.
initReductionOps(ReductionOpsListType & ReductionOps)52742cab237bSDimitry Andric void initReductionOps(ReductionOpsListType &ReductionOps) {
52752cab237bSDimitry Andric assert(Kind != RK_None && !!*this && LHS && RHS &&
52762cab237bSDimitry Andric "Expected reduction operation.");
52772cab237bSDimitry Andric switch (Kind) {
52782cab237bSDimitry Andric case RK_Arithmetic:
52792cab237bSDimitry Andric ReductionOps.assign(1, ReductionOpsType());
52802cab237bSDimitry Andric break;
52812cab237bSDimitry Andric case RK_Min:
52822cab237bSDimitry Andric case RK_UMin:
52832cab237bSDimitry Andric case RK_Max:
52842cab237bSDimitry Andric case RK_UMax:
52852cab237bSDimitry Andric ReductionOps.assign(2, ReductionOpsType());
52862cab237bSDimitry Andric break;
52872cab237bSDimitry Andric case RK_None:
52882cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
52892cab237bSDimitry Andric }
52902cab237bSDimitry Andric }
52912cab237bSDimitry Andric /// Add all reduction operations for the reduction instruction \p I.
addReductionOps(Instruction * I,ReductionOpsListType & ReductionOps)52922cab237bSDimitry Andric void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
52932cab237bSDimitry Andric assert(Kind != RK_None && !!*this && LHS && RHS &&
52942cab237bSDimitry Andric "Expected reduction operation.");
52952cab237bSDimitry Andric switch (Kind) {
52962cab237bSDimitry Andric case RK_Arithmetic:
52972cab237bSDimitry Andric ReductionOps[0].emplace_back(I);
52982cab237bSDimitry Andric break;
52992cab237bSDimitry Andric case RK_Min:
53002cab237bSDimitry Andric case RK_UMin:
53012cab237bSDimitry Andric case RK_Max:
53022cab237bSDimitry Andric case RK_UMax:
53032cab237bSDimitry Andric ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
53042cab237bSDimitry Andric ReductionOps[1].emplace_back(I);
53052cab237bSDimitry Andric break;
53062cab237bSDimitry Andric case RK_None:
53072cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
53082cab237bSDimitry Andric }
53092cab237bSDimitry Andric }
53102cab237bSDimitry Andric
53112cab237bSDimitry Andric /// Checks if instruction is associative and can be vectorized.
isAssociative(Instruction * I) const53122cab237bSDimitry Andric bool isAssociative(Instruction *I) const {
53132cab237bSDimitry Andric assert(Kind != RK_None && *this && LHS && RHS &&
53142cab237bSDimitry Andric "Expected reduction operation.");
53152cab237bSDimitry Andric switch (Kind) {
53162cab237bSDimitry Andric case RK_Arithmetic:
53172cab237bSDimitry Andric return I->isAssociative();
53182cab237bSDimitry Andric case RK_Min:
53192cab237bSDimitry Andric case RK_Max:
53202cab237bSDimitry Andric return Opcode == Instruction::ICmp ||
53212cab237bSDimitry Andric cast<Instruction>(I->getOperand(0))->isFast();
53222cab237bSDimitry Andric case RK_UMin:
53232cab237bSDimitry Andric case RK_UMax:
53242cab237bSDimitry Andric assert(Opcode == Instruction::ICmp &&
53252cab237bSDimitry Andric "Only integer compare operation is expected.");
53262cab237bSDimitry Andric return true;
53272cab237bSDimitry Andric case RK_None:
53282cab237bSDimitry Andric break;
53292cab237bSDimitry Andric }
53302cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
53312cab237bSDimitry Andric }
53322cab237bSDimitry Andric
53332cab237bSDimitry Andric /// Checks if the reduction operation can be vectorized.
isVectorizable(Instruction * I) const53342cab237bSDimitry Andric bool isVectorizable(Instruction *I) const {
53352cab237bSDimitry Andric return isVectorizable() && isAssociative(I);
53362cab237bSDimitry Andric }
53372cab237bSDimitry Andric
53382cab237bSDimitry Andric /// Checks if two operation data are both a reduction op or both a reduced
53392cab237bSDimitry Andric /// value.
operator ==(const OperationData & OD)53402cab237bSDimitry Andric bool operator==(const OperationData &OD) {
53412cab237bSDimitry Andric assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
53422cab237bSDimitry Andric "One of the comparing operations is incorrect.");
53432cab237bSDimitry Andric return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
53442cab237bSDimitry Andric }
operator !=(const OperationData & OD)53452cab237bSDimitry Andric bool operator!=(const OperationData &OD) { return !(*this == OD); }
clear()53462cab237bSDimitry Andric void clear() {
53472cab237bSDimitry Andric Opcode = 0;
53482cab237bSDimitry Andric LHS = nullptr;
53492cab237bSDimitry Andric RHS = nullptr;
53502cab237bSDimitry Andric Kind = RK_None;
53512cab237bSDimitry Andric NoNaN = false;
53522cab237bSDimitry Andric }
53532cab237bSDimitry Andric
53542cab237bSDimitry Andric /// Get the opcode of the reduction operation.
getOpcode() const53552cab237bSDimitry Andric unsigned getOpcode() const {
53562cab237bSDimitry Andric assert(isVectorizable() && "Expected vectorizable operation.");
53572cab237bSDimitry Andric return Opcode;
53582cab237bSDimitry Andric }
53592cab237bSDimitry Andric
53602cab237bSDimitry Andric /// Get kind of reduction data.
getKind() const53612cab237bSDimitry Andric ReductionKind getKind() const { return Kind; }
getLHS() const53622cab237bSDimitry Andric Value *getLHS() const { return LHS; }
getRHS() const53632cab237bSDimitry Andric Value *getRHS() const { return RHS; }
getConditionType() const53642cab237bSDimitry Andric Type *getConditionType() const {
53652cab237bSDimitry Andric switch (Kind) {
53662cab237bSDimitry Andric case RK_Arithmetic:
53672cab237bSDimitry Andric return nullptr;
53682cab237bSDimitry Andric case RK_Min:
53692cab237bSDimitry Andric case RK_Max:
53702cab237bSDimitry Andric case RK_UMin:
53712cab237bSDimitry Andric case RK_UMax:
53722cab237bSDimitry Andric return CmpInst::makeCmpResultType(LHS->getType());
53732cab237bSDimitry Andric case RK_None:
53742cab237bSDimitry Andric break;
53752cab237bSDimitry Andric }
53762cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
53772cab237bSDimitry Andric }
53782cab237bSDimitry Andric
53792cab237bSDimitry Andric /// Creates reduction operation with the current opcode with the IR flags
53802cab237bSDimitry Andric /// from \p ReductionOps.
createOp(IRBuilder<> & Builder,const Twine & Name,const ReductionOpsListType & ReductionOps) const53812cab237bSDimitry Andric Value *createOp(IRBuilder<> &Builder, const Twine &Name,
53822cab237bSDimitry Andric const ReductionOpsListType &ReductionOps) const {
53832cab237bSDimitry Andric assert(isVectorizable() &&
53842cab237bSDimitry Andric "Expected add|fadd or min/max reduction operation.");
53852cab237bSDimitry Andric auto *Op = createOp(Builder, Name);
53862cab237bSDimitry Andric switch (Kind) {
53872cab237bSDimitry Andric case RK_Arithmetic:
53882cab237bSDimitry Andric propagateIRFlags(Op, ReductionOps[0]);
53892cab237bSDimitry Andric return Op;
53902cab237bSDimitry Andric case RK_Min:
53912cab237bSDimitry Andric case RK_Max:
53922cab237bSDimitry Andric case RK_UMin:
53932cab237bSDimitry Andric case RK_UMax:
53942cab237bSDimitry Andric if (auto *SI = dyn_cast<SelectInst>(Op))
53952cab237bSDimitry Andric propagateIRFlags(SI->getCondition(), ReductionOps[0]);
53962cab237bSDimitry Andric propagateIRFlags(Op, ReductionOps[1]);
53972cab237bSDimitry Andric return Op;
53982cab237bSDimitry Andric case RK_None:
53992cab237bSDimitry Andric break;
54002cab237bSDimitry Andric }
54012cab237bSDimitry Andric llvm_unreachable("Unknown reduction operation.");
54022cab237bSDimitry Andric }
54032cab237bSDimitry Andric /// Creates reduction operation with the current opcode with the IR flags
54042cab237bSDimitry Andric /// from \p I.
createOp(IRBuilder<> & Builder,const Twine & Name,Instruction * I) const54052cab237bSDimitry Andric Value *createOp(IRBuilder<> &Builder, const Twine &Name,
54062cab237bSDimitry Andric Instruction *I) const {
54072cab237bSDimitry Andric assert(isVectorizable() &&
54082cab237bSDimitry Andric "Expected add|fadd or min/max reduction operation.");
54092cab237bSDimitry Andric auto *Op = createOp(Builder, Name);
54102cab237bSDimitry Andric switch (Kind) {
54112cab237bSDimitry Andric case RK_Arithmetic:
54122cab237bSDimitry Andric propagateIRFlags(Op, I);
54132cab237bSDimitry Andric return Op;
54142cab237bSDimitry Andric case RK_Min:
54152cab237bSDimitry Andric case RK_Max:
54162cab237bSDimitry Andric case RK_UMin:
54172cab237bSDimitry Andric case RK_UMax:
54182cab237bSDimitry Andric if (auto *SI = dyn_cast<SelectInst>(Op)) {
54192cab237bSDimitry Andric propagateIRFlags(SI->getCondition(),
54202cab237bSDimitry Andric cast<SelectInst>(I)->getCondition());
54212cab237bSDimitry Andric }
54222cab237bSDimitry Andric propagateIRFlags(Op, I);
54232cab237bSDimitry Andric return Op;
54242cab237bSDimitry Andric case RK_None:
54252cab237bSDimitry Andric break;
54262cab237bSDimitry Andric }
54272cab237bSDimitry Andric llvm_unreachable("Unknown reduction operation.");
54282cab237bSDimitry Andric }
54292cab237bSDimitry Andric
getFlags() const54302cab237bSDimitry Andric TargetTransformInfo::ReductionFlags getFlags() const {
54312cab237bSDimitry Andric TargetTransformInfo::ReductionFlags Flags;
54322cab237bSDimitry Andric Flags.NoNaN = NoNaN;
54332cab237bSDimitry Andric switch (Kind) {
54342cab237bSDimitry Andric case RK_Arithmetic:
54352cab237bSDimitry Andric break;
54362cab237bSDimitry Andric case RK_Min:
54372cab237bSDimitry Andric Flags.IsSigned = Opcode == Instruction::ICmp;
54382cab237bSDimitry Andric Flags.IsMaxOp = false;
54392cab237bSDimitry Andric break;
54402cab237bSDimitry Andric case RK_Max:
54412cab237bSDimitry Andric Flags.IsSigned = Opcode == Instruction::ICmp;
54422cab237bSDimitry Andric Flags.IsMaxOp = true;
54432cab237bSDimitry Andric break;
54442cab237bSDimitry Andric case RK_UMin:
54452cab237bSDimitry Andric Flags.IsSigned = false;
54462cab237bSDimitry Andric Flags.IsMaxOp = false;
54472cab237bSDimitry Andric break;
54482cab237bSDimitry Andric case RK_UMax:
54492cab237bSDimitry Andric Flags.IsSigned = false;
54502cab237bSDimitry Andric Flags.IsMaxOp = true;
54512cab237bSDimitry Andric break;
54522cab237bSDimitry Andric case RK_None:
54532cab237bSDimitry Andric llvm_unreachable("Reduction kind is not set");
54542cab237bSDimitry Andric }
54552cab237bSDimitry Andric return Flags;
54562cab237bSDimitry Andric }
54572cab237bSDimitry Andric };
54582cab237bSDimitry Andric
5459*b5893f02SDimitry Andric WeakTrackingVH ReductionRoot;
54602cab237bSDimitry Andric
54612cab237bSDimitry Andric /// The operation data of the reduction operation.
54622cab237bSDimitry Andric OperationData ReductionData;
54632cab237bSDimitry Andric
54642cab237bSDimitry Andric /// The operation data of the values we perform a reduction on.
54652cab237bSDimitry Andric OperationData ReducedValueData;
54662cab237bSDimitry Andric
5467f785676fSDimitry Andric /// Should we model this reduction as a pairwise reduction tree or a tree that
5468f785676fSDimitry Andric /// splits the vector in halves and adds those halves.
54697a7e6055SDimitry Andric bool IsPairwiseReduction = false;
54707a7e6055SDimitry Andric
54717a7e6055SDimitry Andric /// Checks if the ParentStackElem.first should be marked as a reduction
54727a7e6055SDimitry Andric /// operation with an extra argument or as extra argument itself.
markExtraArg(std::pair<Instruction *,unsigned> & ParentStackElem,Value * ExtraArg)54737a7e6055SDimitry Andric void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
54747a7e6055SDimitry Andric Value *ExtraArg) {
54757a7e6055SDimitry Andric if (ExtraArgs.count(ParentStackElem.first)) {
54767a7e6055SDimitry Andric ExtraArgs[ParentStackElem.first] = nullptr;
54777a7e6055SDimitry Andric // We ran into something like:
54787a7e6055SDimitry Andric // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
54797a7e6055SDimitry Andric // The whole ParentStackElem.first should be considered as an extra value
54807a7e6055SDimitry Andric // in this case.
54817a7e6055SDimitry Andric // Do not perform analysis of remaining operands of ParentStackElem.first
54827a7e6055SDimitry Andric // instruction, this whole instruction is an extra argument.
54837a7e6055SDimitry Andric ParentStackElem.second = ParentStackElem.first->getNumOperands();
54847a7e6055SDimitry Andric } else {
54857a7e6055SDimitry Andric // We ran into something like:
54867a7e6055SDimitry Andric // ParentStackElem.first += ... + ExtraArg + ...
54877a7e6055SDimitry Andric ExtraArgs[ParentStackElem.first] = ExtraArg;
54887a7e6055SDimitry Andric }
54897a7e6055SDimitry Andric }
5490f785676fSDimitry Andric
getOperationData(Value * V)54912cab237bSDimitry Andric static OperationData getOperationData(Value *V) {
54922cab237bSDimitry Andric if (!V)
54932cab237bSDimitry Andric return OperationData();
54942cab237bSDimitry Andric
54952cab237bSDimitry Andric Value *LHS;
54962cab237bSDimitry Andric Value *RHS;
54972cab237bSDimitry Andric if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
54982cab237bSDimitry Andric return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
54992cab237bSDimitry Andric RK_Arithmetic);
55002cab237bSDimitry Andric }
55012cab237bSDimitry Andric if (auto *Select = dyn_cast<SelectInst>(V)) {
55022cab237bSDimitry Andric // Look for a min/max pattern.
55032cab237bSDimitry Andric if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
55042cab237bSDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
55052cab237bSDimitry Andric } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
55062cab237bSDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
55072cab237bSDimitry Andric } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
55082cab237bSDimitry Andric m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
55092cab237bSDimitry Andric return OperationData(
55102cab237bSDimitry Andric Instruction::FCmp, LHS, RHS, RK_Min,
55112cab237bSDimitry Andric cast<Instruction>(Select->getCondition())->hasNoNaNs());
55122cab237bSDimitry Andric } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
55132cab237bSDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
55142cab237bSDimitry Andric } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
55152cab237bSDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
55162cab237bSDimitry Andric } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
55172cab237bSDimitry Andric m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
55182cab237bSDimitry Andric return OperationData(
55192cab237bSDimitry Andric Instruction::FCmp, LHS, RHS, RK_Max,
55202cab237bSDimitry Andric cast<Instruction>(Select->getCondition())->hasNoNaNs());
55214ba319b5SDimitry Andric } else {
55224ba319b5SDimitry Andric // Try harder: look for min/max pattern based on instructions producing
55234ba319b5SDimitry Andric // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
55244ba319b5SDimitry Andric // During the intermediate stages of SLP, it's very common to have
55254ba319b5SDimitry Andric // pattern like this (since optimizeGatherSequence is run only once
55264ba319b5SDimitry Andric // at the end):
55274ba319b5SDimitry Andric // %1 = extractelement <2 x i32> %a, i32 0
55284ba319b5SDimitry Andric // %2 = extractelement <2 x i32> %a, i32 1
55294ba319b5SDimitry Andric // %cond = icmp sgt i32 %1, %2
55304ba319b5SDimitry Andric // %3 = extractelement <2 x i32> %a, i32 0
55314ba319b5SDimitry Andric // %4 = extractelement <2 x i32> %a, i32 1
55324ba319b5SDimitry Andric // %select = select i1 %cond, i32 %3, i32 %4
55334ba319b5SDimitry Andric CmpInst::Predicate Pred;
55344ba319b5SDimitry Andric Instruction *L1;
55354ba319b5SDimitry Andric Instruction *L2;
55364ba319b5SDimitry Andric
55374ba319b5SDimitry Andric LHS = Select->getTrueValue();
55384ba319b5SDimitry Andric RHS = Select->getFalseValue();
55394ba319b5SDimitry Andric Value *Cond = Select->getCondition();
55404ba319b5SDimitry Andric
55414ba319b5SDimitry Andric // TODO: Support inverse predicates.
55424ba319b5SDimitry Andric if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
55434ba319b5SDimitry Andric if (!isa<ExtractElementInst>(RHS) ||
55444ba319b5SDimitry Andric !L2->isIdenticalTo(cast<Instruction>(RHS)))
55454ba319b5SDimitry Andric return OperationData(V);
55464ba319b5SDimitry Andric } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
55474ba319b5SDimitry Andric if (!isa<ExtractElementInst>(LHS) ||
55484ba319b5SDimitry Andric !L1->isIdenticalTo(cast<Instruction>(LHS)))
55494ba319b5SDimitry Andric return OperationData(V);
55504ba319b5SDimitry Andric } else {
55514ba319b5SDimitry Andric if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
55524ba319b5SDimitry Andric return OperationData(V);
55534ba319b5SDimitry Andric if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
55544ba319b5SDimitry Andric !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
55554ba319b5SDimitry Andric !L2->isIdenticalTo(cast<Instruction>(RHS)))
55564ba319b5SDimitry Andric return OperationData(V);
55574ba319b5SDimitry Andric }
55584ba319b5SDimitry Andric switch (Pred) {
55594ba319b5SDimitry Andric default:
55604ba319b5SDimitry Andric return OperationData(V);
55614ba319b5SDimitry Andric
55624ba319b5SDimitry Andric case CmpInst::ICMP_ULT:
55634ba319b5SDimitry Andric case CmpInst::ICMP_ULE:
55644ba319b5SDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
55654ba319b5SDimitry Andric
55664ba319b5SDimitry Andric case CmpInst::ICMP_SLT:
55674ba319b5SDimitry Andric case CmpInst::ICMP_SLE:
55684ba319b5SDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
55694ba319b5SDimitry Andric
55704ba319b5SDimitry Andric case CmpInst::FCMP_OLT:
55714ba319b5SDimitry Andric case CmpInst::FCMP_OLE:
55724ba319b5SDimitry Andric case CmpInst::FCMP_ULT:
55734ba319b5SDimitry Andric case CmpInst::FCMP_ULE:
55744ba319b5SDimitry Andric return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
55754ba319b5SDimitry Andric cast<Instruction>(Cond)->hasNoNaNs());
55764ba319b5SDimitry Andric
55774ba319b5SDimitry Andric case CmpInst::ICMP_UGT:
55784ba319b5SDimitry Andric case CmpInst::ICMP_UGE:
55794ba319b5SDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
55804ba319b5SDimitry Andric
55814ba319b5SDimitry Andric case CmpInst::ICMP_SGT:
55824ba319b5SDimitry Andric case CmpInst::ICMP_SGE:
55834ba319b5SDimitry Andric return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
55844ba319b5SDimitry Andric
55854ba319b5SDimitry Andric case CmpInst::FCMP_OGT:
55864ba319b5SDimitry Andric case CmpInst::FCMP_OGE:
55874ba319b5SDimitry Andric case CmpInst::FCMP_UGT:
55884ba319b5SDimitry Andric case CmpInst::FCMP_UGE:
55894ba319b5SDimitry Andric return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
55904ba319b5SDimitry Andric cast<Instruction>(Cond)->hasNoNaNs());
55914ba319b5SDimitry Andric }
55922cab237bSDimitry Andric }
55932cab237bSDimitry Andric }
55942cab237bSDimitry Andric return OperationData(V);
55952cab237bSDimitry Andric }
55962cab237bSDimitry Andric
5597f785676fSDimitry Andric public:
55987a7e6055SDimitry Andric HorizontalReduction() = default;
5599f785676fSDimitry Andric
56004ba319b5SDimitry Andric /// Try to find a reduction tree.
matchAssociativeReduction(PHINode * Phi,Instruction * B)56012cab237bSDimitry Andric bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
5602d88c1a5aSDimitry Andric assert((!Phi || is_contained(Phi->operands(), B)) &&
5603f785676fSDimitry Andric "Thi phi needs to use the binary operator");
5604f785676fSDimitry Andric
56052cab237bSDimitry Andric ReductionData = getOperationData(B);
56062cab237bSDimitry Andric
5607f785676fSDimitry Andric // We could have a initial reductions that is not an add.
5608f785676fSDimitry Andric // r *= v1 + v2 + v3 + v4
5609f785676fSDimitry Andric // In such a case start looking for a tree rooted in the first '+'.
5610f785676fSDimitry Andric if (Phi) {
56112cab237bSDimitry Andric if (ReductionData.getLHS() == Phi) {
561291bc56edSDimitry Andric Phi = nullptr;
56132cab237bSDimitry Andric B = dyn_cast<Instruction>(ReductionData.getRHS());
56142cab237bSDimitry Andric ReductionData = getOperationData(B);
56152cab237bSDimitry Andric } else if (ReductionData.getRHS() == Phi) {
561691bc56edSDimitry Andric Phi = nullptr;
56172cab237bSDimitry Andric B = dyn_cast<Instruction>(ReductionData.getLHS());
56182cab237bSDimitry Andric ReductionData = getOperationData(B);
5619f785676fSDimitry Andric }
5620f785676fSDimitry Andric }
5621f785676fSDimitry Andric
56222cab237bSDimitry Andric if (!ReductionData.isVectorizable(B))
5623f785676fSDimitry Andric return false;
5624f785676fSDimitry Andric
5625f785676fSDimitry Andric Type *Ty = B->getType();
562644f7b0dcSDimitry Andric if (!isValidElementType(Ty))
5627f785676fSDimitry Andric return false;
56284ba319b5SDimitry Andric if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
56294ba319b5SDimitry Andric return false;
5630f785676fSDimitry Andric
56312cab237bSDimitry Andric ReducedValueData.clear();
5632f785676fSDimitry Andric ReductionRoot = B;
5633f785676fSDimitry Andric
5634f785676fSDimitry Andric // Post order traverse the reduction tree starting at B. We only handle true
56352cab237bSDimitry Andric // trees containing only binary operators.
56367d523365SDimitry Andric SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
56372cab237bSDimitry Andric Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
56382cab237bSDimitry Andric ReductionData.initReductionOps(ReductionOps);
5639f785676fSDimitry Andric while (!Stack.empty()) {
56407d523365SDimitry Andric Instruction *TreeN = Stack.back().first;
5641f785676fSDimitry Andric unsigned EdgeToVist = Stack.back().second++;
56422cab237bSDimitry Andric OperationData OpData = getOperationData(TreeN);
56432cab237bSDimitry Andric bool IsReducedValue = OpData != ReductionData;
5644f785676fSDimitry Andric
5645f785676fSDimitry Andric // Postorder vist.
56462cab237bSDimitry Andric if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
56477a7e6055SDimitry Andric if (IsReducedValue)
5648f785676fSDimitry Andric ReducedVals.push_back(TreeN);
56497a7e6055SDimitry Andric else {
56507a7e6055SDimitry Andric auto I = ExtraArgs.find(TreeN);
56517a7e6055SDimitry Andric if (I != ExtraArgs.end() && !I->second) {
56527a7e6055SDimitry Andric // Check if TreeN is an extra argument of its parent operation.
56537a7e6055SDimitry Andric if (Stack.size() <= 1) {
56547a7e6055SDimitry Andric // TreeN can't be an extra argument as it is a root reduction
56557a7e6055SDimitry Andric // operation.
5656f785676fSDimitry Andric return false;
56577a7e6055SDimitry Andric }
56587a7e6055SDimitry Andric // Yes, TreeN is an extra argument, do not add it to a list of
56597a7e6055SDimitry Andric // reduction operations.
56607a7e6055SDimitry Andric // Stack[Stack.size() - 2] always points to the parent operation.
56617a7e6055SDimitry Andric markExtraArg(Stack[Stack.size() - 2], TreeN);
56627a7e6055SDimitry Andric ExtraArgs.erase(TreeN);
56637a7e6055SDimitry Andric } else
56642cab237bSDimitry Andric ReductionData.addReductionOps(TreeN, ReductionOps);
5665f785676fSDimitry Andric }
5666f785676fSDimitry Andric // Retract.
5667f785676fSDimitry Andric Stack.pop_back();
5668f785676fSDimitry Andric continue;
5669f785676fSDimitry Andric }
5670f785676fSDimitry Andric
5671f785676fSDimitry Andric // Visit left or right.
5672f785676fSDimitry Andric Value *NextV = TreeN->getOperand(EdgeToVist);
5673d88c1a5aSDimitry Andric if (NextV != Phi) {
5674d88c1a5aSDimitry Andric auto *I = dyn_cast<Instruction>(NextV);
56752cab237bSDimitry Andric OpData = getOperationData(I);
5676d88c1a5aSDimitry Andric // Continue analysis if the next operand is a reduction operation or
5677d88c1a5aSDimitry Andric // (possibly) a reduced value. If the reduced value opcode is not set,
5678d88c1a5aSDimitry Andric // the first met operation != reduction operation is considered as the
5679d88c1a5aSDimitry Andric // reduced value class.
56802cab237bSDimitry Andric if (I && (!ReducedValueData || OpData == ReducedValueData ||
56812cab237bSDimitry Andric OpData == ReductionData)) {
56822cab237bSDimitry Andric const bool IsReductionOperation = OpData == ReductionData;
56837a7e6055SDimitry Andric // Only handle trees in the current basic block.
56842cab237bSDimitry Andric if (!ReductionData.hasSameParent(I, B->getParent(),
56852cab237bSDimitry Andric IsReductionOperation)) {
56867a7e6055SDimitry Andric // I is an extra argument for TreeN (its parent operation).
56877a7e6055SDimitry Andric markExtraArg(Stack.back(), I);
56887a7e6055SDimitry Andric continue;
56897a7e6055SDimitry Andric }
56907a7e6055SDimitry Andric
56912cab237bSDimitry Andric // Each tree node needs to have minimal number of users except for the
56922cab237bSDimitry Andric // ultimate reduction.
56932cab237bSDimitry Andric if (!ReductionData.hasRequiredNumberOfUses(I,
56942cab237bSDimitry Andric OpData == ReductionData) &&
56952cab237bSDimitry Andric I != B) {
56967a7e6055SDimitry Andric // I is an extra argument for TreeN (its parent operation).
56977a7e6055SDimitry Andric markExtraArg(Stack.back(), I);
56987a7e6055SDimitry Andric continue;
56997a7e6055SDimitry Andric }
57007a7e6055SDimitry Andric
57012cab237bSDimitry Andric if (IsReductionOperation) {
57027a7e6055SDimitry Andric // We need to be able to reassociate the reduction operations.
57032cab237bSDimitry Andric if (!OpData.isAssociative(I)) {
57047a7e6055SDimitry Andric // I is an extra argument for TreeN (its parent operation).
57057a7e6055SDimitry Andric markExtraArg(Stack.back(), I);
57067a7e6055SDimitry Andric continue;
57077a7e6055SDimitry Andric }
57082cab237bSDimitry Andric } else if (ReducedValueData &&
57092cab237bSDimitry Andric ReducedValueData != OpData) {
57107a7e6055SDimitry Andric // Make sure that the opcodes of the operations that we are going to
57117a7e6055SDimitry Andric // reduce match.
57127a7e6055SDimitry Andric // I is an extra argument for TreeN (its parent operation).
57137a7e6055SDimitry Andric markExtraArg(Stack.back(), I);
57147a7e6055SDimitry Andric continue;
57152cab237bSDimitry Andric } else if (!ReducedValueData)
57162cab237bSDimitry Andric ReducedValueData = OpData;
57177a7e6055SDimitry Andric
57182cab237bSDimitry Andric Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5719d88c1a5aSDimitry Andric continue;
5720d88c1a5aSDimitry Andric }
5721f785676fSDimitry Andric }
57227a7e6055SDimitry Andric // NextV is an extra argument for TreeN (its parent operation).
57237a7e6055SDimitry Andric markExtraArg(Stack.back(), NextV);
5724d88c1a5aSDimitry Andric }
5725f785676fSDimitry Andric return true;
5726f785676fSDimitry Andric }
5727f785676fSDimitry Andric
57284ba319b5SDimitry Andric /// Attempt to vectorize the tree found by
5729f785676fSDimitry Andric /// matchAssociativeReduction.
tryToReduce(BoUpSLP & V,TargetTransformInfo * TTI)5730f785676fSDimitry Andric bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5731f785676fSDimitry Andric if (ReducedVals.empty())
5732f785676fSDimitry Andric return false;
5733f785676fSDimitry Andric
57347a7e6055SDimitry Andric // If there is a sufficient number of reduction values, reduce
57357a7e6055SDimitry Andric // to a nearby power-of-2. Can safely generate oversized
57367a7e6055SDimitry Andric // vectors and rely on the backend to split them to legal sizes.
5737f785676fSDimitry Andric unsigned NumReducedVals = ReducedVals.size();
57387a7e6055SDimitry Andric if (NumReducedVals < 4)
5739f785676fSDimitry Andric return false;
5740f785676fSDimitry Andric
57417a7e6055SDimitry Andric unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
57427a7e6055SDimitry Andric
574391bc56edSDimitry Andric Value *VectorizedTree = nullptr;
5744*b5893f02SDimitry Andric IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
5745f785676fSDimitry Andric FastMathFlags Unsafe;
57462cab237bSDimitry Andric Unsafe.setFast();
5747444ed5c5SDimitry Andric Builder.setFastMathFlags(Unsafe);
5748f785676fSDimitry Andric unsigned i = 0;
5749f785676fSDimitry Andric
57507a7e6055SDimitry Andric BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
57517a7e6055SDimitry Andric // The same extra argument may be used several time, so log each attempt
57527a7e6055SDimitry Andric // to use it.
5753*b5893f02SDimitry Andric for (auto &Pair : ExtraArgs) {
5754*b5893f02SDimitry Andric assert(Pair.first && "DebugLoc must be set.");
57557a7e6055SDimitry Andric ExternallyUsedValues[Pair.second].push_back(Pair.first);
5756*b5893f02SDimitry Andric }
5757*b5893f02SDimitry Andric // The reduction root is used as the insertion point for new instructions,
5758*b5893f02SDimitry Andric // so set it as externally used to prevent it from being deleted.
5759*b5893f02SDimitry Andric ExternallyUsedValues[ReductionRoot];
57602cab237bSDimitry Andric SmallVector<Value *, 16> IgnoreList;
57612cab237bSDimitry Andric for (auto &V : ReductionOps)
57622cab237bSDimitry Andric IgnoreList.append(V.begin(), V.end());
57637a7e6055SDimitry Andric while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5764d88c1a5aSDimitry Andric auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
57652cab237bSDimitry Andric V.buildTree(VL, ExternallyUsedValues, IgnoreList);
57664ba319b5SDimitry Andric Optional<ArrayRef<unsigned>> Order = V.bestOrder();
57674ba319b5SDimitry Andric // TODO: Handle orders of size less than number of elements in the vector.
57684ba319b5SDimitry Andric if (Order && Order->size() == VL.size()) {
57694ba319b5SDimitry Andric // TODO: reorder tree nodes without tree rebuilding.
57704ba319b5SDimitry Andric SmallVector<Value *, 4> ReorderedOps(VL.size());
57714ba319b5SDimitry Andric llvm::transform(*Order, ReorderedOps.begin(),
57724ba319b5SDimitry Andric [VL](const unsigned Idx) { return VL[Idx]; });
57734ba319b5SDimitry Andric V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
5774d88c1a5aSDimitry Andric }
5775d88c1a5aSDimitry Andric if (V.isTreeTinyAndNotFullyVectorizable())
57767a7e6055SDimitry Andric break;
5777d88c1a5aSDimitry Andric
57783ca95b02SDimitry Andric V.computeMinimumValueSizes();
5779f785676fSDimitry Andric
5780f785676fSDimitry Andric // Estimate cost.
57814ba319b5SDimitry Andric int TreeCost = V.getTreeCost();
57824ba319b5SDimitry Andric int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
57834ba319b5SDimitry Andric int Cost = TreeCost + ReductionCost;
57842cab237bSDimitry Andric if (Cost >= -SLPCostThreshold) {
57852cab237bSDimitry Andric V.getORE()->emit([&]() {
57862cab237bSDimitry Andric return OptimizationRemarkMissed(
57872cab237bSDimitry Andric SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
57882cab237bSDimitry Andric << "Vectorizing horizontal reduction is possible"
57892cab237bSDimitry Andric << "but not beneficial with cost "
57902cab237bSDimitry Andric << ore::NV("Cost", Cost) << " and threshold "
57912cab237bSDimitry Andric << ore::NV("Threshold", -SLPCostThreshold);
57922cab237bSDimitry Andric });
5793f785676fSDimitry Andric break;
57942cab237bSDimitry Andric }
5795f785676fSDimitry Andric
57964ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
57974ba319b5SDimitry Andric << Cost << ". (HorRdx)\n");
57982cab237bSDimitry Andric V.getORE()->emit([&]() {
57992cab237bSDimitry Andric return OptimizationRemark(
58002cab237bSDimitry Andric SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
58015517e702SDimitry Andric << "Vectorized horizontal reduction with cost "
58025517e702SDimitry Andric << ore::NV("Cost", Cost) << " and with tree size "
58032cab237bSDimitry Andric << ore::NV("TreeSize", V.getTreeSize());
58042cab237bSDimitry Andric });
5805f785676fSDimitry Andric
5806f785676fSDimitry Andric // Vectorize a tree.
5807f785676fSDimitry Andric DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
58087a7e6055SDimitry Andric Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5809f785676fSDimitry Andric
5810f785676fSDimitry Andric // Emit a reduction.
5811*b5893f02SDimitry Andric Builder.SetInsertPoint(cast<Instruction>(ReductionRoot));
58127a7e6055SDimitry Andric Value *ReducedSubTree =
58132cab237bSDimitry Andric emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
5814f785676fSDimitry Andric if (VectorizedTree) {
5815f785676fSDimitry Andric Builder.SetCurrentDebugLocation(Loc);
58162cab237bSDimitry Andric OperationData VectReductionData(ReductionData.getOpcode(),
58172cab237bSDimitry Andric VectorizedTree, ReducedSubTree,
58182cab237bSDimitry Andric ReductionData.getKind());
58192cab237bSDimitry Andric VectorizedTree =
58202cab237bSDimitry Andric VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5821f785676fSDimitry Andric } else
5822f785676fSDimitry Andric VectorizedTree = ReducedSubTree;
58237a7e6055SDimitry Andric i += ReduxWidth;
58247a7e6055SDimitry Andric ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5825f785676fSDimitry Andric }
5826f785676fSDimitry Andric
5827f785676fSDimitry Andric if (VectorizedTree) {
5828f785676fSDimitry Andric // Finish the reduction.
5829f785676fSDimitry Andric for (; i < NumReducedVals; ++i) {
58307a7e6055SDimitry Andric auto *I = cast<Instruction>(ReducedVals[i]);
58317a7e6055SDimitry Andric Builder.SetCurrentDebugLocation(I->getDebugLoc());
58322cab237bSDimitry Andric OperationData VectReductionData(ReductionData.getOpcode(),
58332cab237bSDimitry Andric VectorizedTree, I,
58342cab237bSDimitry Andric ReductionData.getKind());
58352cab237bSDimitry Andric VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
58367a7e6055SDimitry Andric }
58377a7e6055SDimitry Andric for (auto &Pair : ExternallyUsedValues) {
58387a7e6055SDimitry Andric // Add each externally used value to the final reduction.
58397a7e6055SDimitry Andric for (auto *I : Pair.second) {
58407a7e6055SDimitry Andric Builder.SetCurrentDebugLocation(I->getDebugLoc());
58412cab237bSDimitry Andric OperationData VectReductionData(ReductionData.getOpcode(),
58422cab237bSDimitry Andric VectorizedTree, Pair.first,
58432cab237bSDimitry Andric ReductionData.getKind());
58442cab237bSDimitry Andric VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
58457a7e6055SDimitry Andric }
5846f785676fSDimitry Andric }
5847f785676fSDimitry Andric // Update users.
5848f785676fSDimitry Andric ReductionRoot->replaceAllUsesWith(VectorizedTree);
5849f785676fSDimitry Andric }
585091bc56edSDimitry Andric return VectorizedTree != nullptr;
5851f785676fSDimitry Andric }
5852f785676fSDimitry Andric
numReductionValues() const58537d523365SDimitry Andric unsigned numReductionValues() const {
58547d523365SDimitry Andric return ReducedVals.size();
58557d523365SDimitry Andric }
5856f785676fSDimitry Andric
58577d523365SDimitry Andric private:
58584ba319b5SDimitry Andric /// Calculate the cost of a reduction.
getReductionCost(TargetTransformInfo * TTI,Value * FirstReducedVal,unsigned ReduxWidth)58597a7e6055SDimitry Andric int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
58607a7e6055SDimitry Andric unsigned ReduxWidth) {
5861f785676fSDimitry Andric Type *ScalarTy = FirstReducedVal->getType();
5862f785676fSDimitry Andric Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5863f785676fSDimitry Andric
58642cab237bSDimitry Andric int PairwiseRdxCost;
58652cab237bSDimitry Andric int SplittingRdxCost;
58662cab237bSDimitry Andric switch (ReductionData.getKind()) {
58672cab237bSDimitry Andric case RK_Arithmetic:
58682cab237bSDimitry Andric PairwiseRdxCost =
58692cab237bSDimitry Andric TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
58702cab237bSDimitry Andric /*IsPairwiseForm=*/true);
58712cab237bSDimitry Andric SplittingRdxCost =
58722cab237bSDimitry Andric TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
58732cab237bSDimitry Andric /*IsPairwiseForm=*/false);
58742cab237bSDimitry Andric break;
58752cab237bSDimitry Andric case RK_Min:
58762cab237bSDimitry Andric case RK_Max:
58772cab237bSDimitry Andric case RK_UMin:
58782cab237bSDimitry Andric case RK_UMax: {
58792cab237bSDimitry Andric Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
58802cab237bSDimitry Andric bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
58812cab237bSDimitry Andric ReductionData.getKind() == RK_UMax;
58822cab237bSDimitry Andric PairwiseRdxCost =
58832cab237bSDimitry Andric TTI->getMinMaxReductionCost(VecTy, VecCondTy,
58842cab237bSDimitry Andric /*IsPairwiseForm=*/true, IsUnsigned);
58852cab237bSDimitry Andric SplittingRdxCost =
58862cab237bSDimitry Andric TTI->getMinMaxReductionCost(VecTy, VecCondTy,
58872cab237bSDimitry Andric /*IsPairwiseForm=*/false, IsUnsigned);
58882cab237bSDimitry Andric break;
58892cab237bSDimitry Andric }
58902cab237bSDimitry Andric case RK_None:
58912cab237bSDimitry Andric llvm_unreachable("Expected arithmetic or min/max reduction operation");
58922cab237bSDimitry Andric }
5893f785676fSDimitry Andric
5894f785676fSDimitry Andric IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5895f785676fSDimitry Andric int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5896f785676fSDimitry Andric
58972cab237bSDimitry Andric int ScalarReduxCost;
58982cab237bSDimitry Andric switch (ReductionData.getKind()) {
58992cab237bSDimitry Andric case RK_Arithmetic:
59002cab237bSDimitry Andric ScalarReduxCost =
59012cab237bSDimitry Andric TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
59022cab237bSDimitry Andric break;
59032cab237bSDimitry Andric case RK_Min:
59042cab237bSDimitry Andric case RK_Max:
59052cab237bSDimitry Andric case RK_UMin:
59062cab237bSDimitry Andric case RK_UMax:
59072cab237bSDimitry Andric ScalarReduxCost =
59082cab237bSDimitry Andric TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
59092cab237bSDimitry Andric TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
59102cab237bSDimitry Andric CmpInst::makeCmpResultType(ScalarTy));
59112cab237bSDimitry Andric break;
59122cab237bSDimitry Andric case RK_None:
59132cab237bSDimitry Andric llvm_unreachable("Expected arithmetic or min/max reduction operation");
59142cab237bSDimitry Andric }
59152cab237bSDimitry Andric ScalarReduxCost *= (ReduxWidth - 1);
5916f785676fSDimitry Andric
59174ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5918f785676fSDimitry Andric << " for reduction that starts with " << *FirstReducedVal
5919f785676fSDimitry Andric << " (It is a "
5920f785676fSDimitry Andric << (IsPairwiseReduction ? "pairwise" : "splitting")
5921f785676fSDimitry Andric << " reduction)\n");
5922f785676fSDimitry Andric
5923f785676fSDimitry Andric return VecReduxCost - ScalarReduxCost;
5924f785676fSDimitry Andric }
5925f785676fSDimitry Andric
59264ba319b5SDimitry Andric /// Emit a horizontal reduction of the vectorized value.
emitReduction(Value * VectorizedValue,IRBuilder<> & Builder,unsigned ReduxWidth,const TargetTransformInfo * TTI)59277a7e6055SDimitry Andric Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
59282cab237bSDimitry Andric unsigned ReduxWidth, const TargetTransformInfo *TTI) {
5929f785676fSDimitry Andric assert(VectorizedValue && "Need to have a vectorized tree node");
5930f785676fSDimitry Andric assert(isPowerOf2_32(ReduxWidth) &&
5931f785676fSDimitry Andric "We only handle power-of-two reductions for now");
5932f785676fSDimitry Andric
59335517e702SDimitry Andric if (!IsPairwiseReduction)
59345517e702SDimitry Andric return createSimpleTargetReduction(
59352cab237bSDimitry Andric Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
59362cab237bSDimitry Andric ReductionData.getFlags(), ReductionOps.back());
59375517e702SDimitry Andric
593839d628a0SDimitry Andric Value *TmpVec = VectorizedValue;
5939f785676fSDimitry Andric for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5940f785676fSDimitry Andric Value *LeftMask =
5941f785676fSDimitry Andric createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5942f785676fSDimitry Andric Value *RightMask =
5943f785676fSDimitry Andric createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5944f785676fSDimitry Andric
5945f785676fSDimitry Andric Value *LeftShuf = Builder.CreateShuffleVector(
5946f785676fSDimitry Andric TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5947f785676fSDimitry Andric Value *RightShuf = Builder.CreateShuffleVector(
5948f785676fSDimitry Andric TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5949f785676fSDimitry Andric "rdx.shuf.r");
59502cab237bSDimitry Andric OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
59512cab237bSDimitry Andric RightShuf, ReductionData.getKind());
59522cab237bSDimitry Andric TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5953f785676fSDimitry Andric }
5954f785676fSDimitry Andric
5955f785676fSDimitry Andric // The result is in the first element of the vector.
5956f785676fSDimitry Andric return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5957f785676fSDimitry Andric }
5958f785676fSDimitry Andric };
59592cab237bSDimitry Andric
5960d88c1a5aSDimitry Andric } // end anonymous namespace
5961f785676fSDimitry Andric
59624ba319b5SDimitry Andric /// Recognize construction of vectors like
5963f785676fSDimitry Andric /// %ra = insertelement <4 x float> undef, float %s0, i32 0
5964f785676fSDimitry Andric /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
5965f785676fSDimitry Andric /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
5966f785676fSDimitry Andric /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
59672cab237bSDimitry Andric /// starting from the last insertelement instruction.
5968f785676fSDimitry Andric ///
5969f785676fSDimitry Andric /// Returns true if it matches
findBuildVector(InsertElementInst * LastInsertElem,TargetTransformInfo * TTI,SmallVectorImpl<Value * > & BuildVectorOpds,int & UserCost)59702cab237bSDimitry Andric static bool findBuildVector(InsertElementInst *LastInsertElem,
59714ba319b5SDimitry Andric TargetTransformInfo *TTI,
59724ba319b5SDimitry Andric SmallVectorImpl<Value *> &BuildVectorOpds,
59734ba319b5SDimitry Andric int &UserCost) {
59744ba319b5SDimitry Andric UserCost = 0;
59752cab237bSDimitry Andric Value *V = nullptr;
59762cab237bSDimitry Andric do {
59774ba319b5SDimitry Andric if (auto *CI = dyn_cast<ConstantInt>(LastInsertElem->getOperand(2))) {
59784ba319b5SDimitry Andric UserCost += TTI->getVectorInstrCost(Instruction::InsertElement,
59794ba319b5SDimitry Andric LastInsertElem->getType(),
59804ba319b5SDimitry Andric CI->getZExtValue());
59814ba319b5SDimitry Andric }
59822cab237bSDimitry Andric BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
59832cab237bSDimitry Andric V = LastInsertElem->getOperand(0);
59842cab237bSDimitry Andric if (isa<UndefValue>(V))
59852cab237bSDimitry Andric break;
59862cab237bSDimitry Andric LastInsertElem = dyn_cast<InsertElementInst>(V);
59872cab237bSDimitry Andric if (!LastInsertElem || !LastInsertElem->hasOneUse())
5988f785676fSDimitry Andric return false;
59892cab237bSDimitry Andric } while (true);
59902cab237bSDimitry Andric std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5991f785676fSDimitry Andric return true;
5992f785676fSDimitry Andric }
5993f785676fSDimitry Andric
59944ba319b5SDimitry Andric /// Like findBuildVector, but looks for construction of aggregate.
59953ca95b02SDimitry Andric ///
59963ca95b02SDimitry Andric /// \return true if it matches.
findBuildAggregate(InsertValueInst * IV,SmallVectorImpl<Value * > & BuildVectorOpds)59973ca95b02SDimitry Andric static bool findBuildAggregate(InsertValueInst *IV,
59983ca95b02SDimitry Andric SmallVectorImpl<Value *> &BuildVectorOpds) {
59997a7e6055SDimitry Andric Value *V;
60007a7e6055SDimitry Andric do {
60013ca95b02SDimitry Andric BuildVectorOpds.push_back(IV->getInsertedValueOperand());
60027a7e6055SDimitry Andric V = IV->getAggregateOperand();
60037a7e6055SDimitry Andric if (isa<UndefValue>(V))
60047a7e6055SDimitry Andric break;
60057a7e6055SDimitry Andric IV = dyn_cast<InsertValueInst>(V);
60067a7e6055SDimitry Andric if (!IV || !IV->hasOneUse())
60077a7e6055SDimitry Andric return false;
60087a7e6055SDimitry Andric } while (true);
60097a7e6055SDimitry Andric std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
60103ca95b02SDimitry Andric return true;
60113ca95b02SDimitry Andric }
60123ca95b02SDimitry Andric
PhiTypeSorterFunc(Value * V,Value * V2)6013f785676fSDimitry Andric static bool PhiTypeSorterFunc(Value *V, Value *V2) {
6014f785676fSDimitry Andric return V->getType() < V2->getType();
6015f785676fSDimitry Andric }
6016f785676fSDimitry Andric
60174ba319b5SDimitry Andric /// Try and get a reduction value from a phi node.
60187d523365SDimitry Andric ///
60197d523365SDimitry Andric /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
60207d523365SDimitry Andric /// if they come from either \p ParentBB or a containing loop latch.
60217d523365SDimitry Andric ///
60227d523365SDimitry Andric /// \returns A candidate reduction value if possible, or \code nullptr \endcode
60237d523365SDimitry Andric /// if not possible.
getReductionValue(const DominatorTree * DT,PHINode * P,BasicBlock * ParentBB,LoopInfo * LI)60247d523365SDimitry Andric static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
60257d523365SDimitry Andric BasicBlock *ParentBB, LoopInfo *LI) {
60267d523365SDimitry Andric // There are situations where the reduction value is not dominated by the
60277d523365SDimitry Andric // reduction phi. Vectorizing such cases has been reported to cause
60287d523365SDimitry Andric // miscompiles. See PR25787.
60297d523365SDimitry Andric auto DominatedReduxValue = [&](Value *R) {
60304ba319b5SDimitry Andric return isa<Instruction>(R) &&
60314ba319b5SDimitry Andric DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
60327d523365SDimitry Andric };
60337d523365SDimitry Andric
60347d523365SDimitry Andric Value *Rdx = nullptr;
60357d523365SDimitry Andric
60367d523365SDimitry Andric // Return the incoming value if it comes from the same BB as the phi node.
60377d523365SDimitry Andric if (P->getIncomingBlock(0) == ParentBB) {
60387d523365SDimitry Andric Rdx = P->getIncomingValue(0);
60397d523365SDimitry Andric } else if (P->getIncomingBlock(1) == ParentBB) {
60407d523365SDimitry Andric Rdx = P->getIncomingValue(1);
60417d523365SDimitry Andric }
60427d523365SDimitry Andric
60437d523365SDimitry Andric if (Rdx && DominatedReduxValue(Rdx))
60447d523365SDimitry Andric return Rdx;
60457d523365SDimitry Andric
60467d523365SDimitry Andric // Otherwise, check whether we have a loop latch to look at.
60477d523365SDimitry Andric Loop *BBL = LI->getLoopFor(ParentBB);
60487d523365SDimitry Andric if (!BBL)
60497d523365SDimitry Andric return nullptr;
60507d523365SDimitry Andric BasicBlock *BBLatch = BBL->getLoopLatch();
60517d523365SDimitry Andric if (!BBLatch)
60527d523365SDimitry Andric return nullptr;
60537d523365SDimitry Andric
60547d523365SDimitry Andric // There is a loop latch, return the incoming value if it comes from
6055d88c1a5aSDimitry Andric // that. This reduction pattern occasionally turns up.
60567d523365SDimitry Andric if (P->getIncomingBlock(0) == BBLatch) {
60577d523365SDimitry Andric Rdx = P->getIncomingValue(0);
60587d523365SDimitry Andric } else if (P->getIncomingBlock(1) == BBLatch) {
60597d523365SDimitry Andric Rdx = P->getIncomingValue(1);
60607d523365SDimitry Andric }
60617d523365SDimitry Andric
60627d523365SDimitry Andric if (Rdx && DominatedReduxValue(Rdx))
60637d523365SDimitry Andric return Rdx;
60647d523365SDimitry Andric
60657d523365SDimitry Andric return nullptr;
60667d523365SDimitry Andric }
60677d523365SDimitry Andric
60686d97bb29SDimitry Andric /// Attempt to reduce a horizontal reduction.
60696d97bb29SDimitry Andric /// If it is legal to match a horizontal reduction feeding the phi node \a P
60706d97bb29SDimitry Andric /// with reduction operators \a Root (or one of its operands) in a basic block
60716d97bb29SDimitry Andric /// \a BB, then check if it can be done. If horizontal reduction is not found
60726d97bb29SDimitry Andric /// and root instruction is a binary operation, vectorization of the operands is
60736d97bb29SDimitry Andric /// attempted.
60746d97bb29SDimitry Andric /// \returns true if a horizontal reduction was matched and reduced or operands
60756d97bb29SDimitry Andric /// of one of the binary instruction were vectorized.
60766d97bb29SDimitry Andric /// \returns false if a horizontal reduction was not matched (or not possible)
60776d97bb29SDimitry Andric /// or no vectorization of any binary operation feeding \a Root instruction was
60786d97bb29SDimitry Andric /// performed.
tryToVectorizeHorReductionOrInstOperands(PHINode * P,Instruction * Root,BasicBlock * BB,BoUpSLP & R,TargetTransformInfo * TTI,const function_ref<bool (Instruction *,BoUpSLP &)> Vectorize)60796d97bb29SDimitry Andric static bool tryToVectorizeHorReductionOrInstOperands(
60807a7e6055SDimitry Andric PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
60817a7e6055SDimitry Andric TargetTransformInfo *TTI,
60822cab237bSDimitry Andric const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
60837d523365SDimitry Andric if (!ShouldVectorizeHor)
60847d523365SDimitry Andric return false;
60857d523365SDimitry Andric
60867a7e6055SDimitry Andric if (!Root)
60877d523365SDimitry Andric return false;
60887d523365SDimitry Andric
60892cab237bSDimitry Andric if (Root->getParent() != BB || isa<PHINode>(Root))
60907a7e6055SDimitry Andric return false;
60916d97bb29SDimitry Andric // Start analysis starting from Root instruction. If horizontal reduction is
60926d97bb29SDimitry Andric // found, try to vectorize it. If it is not a horizontal reduction or
60936d97bb29SDimitry Andric // vectorization is not possible or not effective, and currently analyzed
60946d97bb29SDimitry Andric // instruction is a binary operation, try to vectorize the operands, using
60956d97bb29SDimitry Andric // pre-order DFS traversal order. If the operands were not vectorized, repeat
60966d97bb29SDimitry Andric // the same procedure considering each operand as a possible root of the
60976d97bb29SDimitry Andric // horizontal reduction.
60986d97bb29SDimitry Andric // Interrupt the process if the Root instruction itself was vectorized or all
60996d97bb29SDimitry Andric // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
61006d97bb29SDimitry Andric SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
61014ba319b5SDimitry Andric SmallPtrSet<Value *, 8> VisitedInstrs;
61027a7e6055SDimitry Andric bool Res = false;
61037a7e6055SDimitry Andric while (!Stack.empty()) {
61046d97bb29SDimitry Andric Value *V;
61056d97bb29SDimitry Andric unsigned Level;
61066d97bb29SDimitry Andric std::tie(V, Level) = Stack.pop_back_val();
61076d97bb29SDimitry Andric if (!V)
61087a7e6055SDimitry Andric continue;
61097a7e6055SDimitry Andric auto *Inst = dyn_cast<Instruction>(V);
61102cab237bSDimitry Andric if (!Inst)
61117a7e6055SDimitry Andric continue;
61122cab237bSDimitry Andric auto *BI = dyn_cast<BinaryOperator>(Inst);
61132cab237bSDimitry Andric auto *SI = dyn_cast<SelectInst>(Inst);
61142cab237bSDimitry Andric if (BI || SI) {
61157a7e6055SDimitry Andric HorizontalReduction HorRdx;
61162cab237bSDimitry Andric if (HorRdx.matchAssociativeReduction(P, Inst)) {
61177a7e6055SDimitry Andric if (HorRdx.tryToReduce(R, TTI)) {
61187a7e6055SDimitry Andric Res = true;
61196d97bb29SDimitry Andric // Set P to nullptr to avoid re-analysis of phi node in
61206d97bb29SDimitry Andric // matchAssociativeReduction function unless this is the root node.
61217a7e6055SDimitry Andric P = nullptr;
61227a7e6055SDimitry Andric continue;
61237a7e6055SDimitry Andric }
61247a7e6055SDimitry Andric }
61252cab237bSDimitry Andric if (P && BI) {
61267a7e6055SDimitry Andric Inst = dyn_cast<Instruction>(BI->getOperand(0));
61277a7e6055SDimitry Andric if (Inst == P)
61287a7e6055SDimitry Andric Inst = dyn_cast<Instruction>(BI->getOperand(1));
61297a7e6055SDimitry Andric if (!Inst) {
61306d97bb29SDimitry Andric // Set P to nullptr to avoid re-analysis of phi node in
61316d97bb29SDimitry Andric // matchAssociativeReduction function unless this is the root node.
61327a7e6055SDimitry Andric P = nullptr;
61337a7e6055SDimitry Andric continue;
61347a7e6055SDimitry Andric }
61357a7e6055SDimitry Andric }
61367a7e6055SDimitry Andric }
61376d97bb29SDimitry Andric // Set P to nullptr to avoid re-analysis of phi node in
61386d97bb29SDimitry Andric // matchAssociativeReduction function unless this is the root node.
61397a7e6055SDimitry Andric P = nullptr;
61402cab237bSDimitry Andric if (Vectorize(Inst, R)) {
61417a7e6055SDimitry Andric Res = true;
61427a7e6055SDimitry Andric continue;
61437a7e6055SDimitry Andric }
61447d523365SDimitry Andric
61456d97bb29SDimitry Andric // Try to vectorize operands.
61462cab237bSDimitry Andric // Continue analysis for the instruction from the same basic block only to
61472cab237bSDimitry Andric // save compile time.
61486d97bb29SDimitry Andric if (++Level < RecursionMaxDepth)
61496d97bb29SDimitry Andric for (auto *Op : Inst->operand_values())
61502cab237bSDimitry Andric if (VisitedInstrs.insert(Op).second)
61512cab237bSDimitry Andric if (auto *I = dyn_cast<Instruction>(Op))
61522cab237bSDimitry Andric if (!isa<PHINode>(I) && I->getParent() == BB)
61536d97bb29SDimitry Andric Stack.emplace_back(Op, Level);
61547a7e6055SDimitry Andric }
61557a7e6055SDimitry Andric return Res;
61567a7e6055SDimitry Andric }
61577a7e6055SDimitry Andric
vectorizeRootInstruction(PHINode * P,Value * V,BasicBlock * BB,BoUpSLP & R,TargetTransformInfo * TTI)61587a7e6055SDimitry Andric bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
61597a7e6055SDimitry Andric BasicBlock *BB, BoUpSLP &R,
61607a7e6055SDimitry Andric TargetTransformInfo *TTI) {
61617a7e6055SDimitry Andric if (!V)
61627a7e6055SDimitry Andric return false;
61637a7e6055SDimitry Andric auto *I = dyn_cast<Instruction>(V);
61647a7e6055SDimitry Andric if (!I)
61657a7e6055SDimitry Andric return false;
61667a7e6055SDimitry Andric
61677a7e6055SDimitry Andric if (!isa<BinaryOperator>(I))
61687a7e6055SDimitry Andric P = nullptr;
61697a7e6055SDimitry Andric // Try to match and vectorize a horizontal reduction.
61702cab237bSDimitry Andric auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
61712cab237bSDimitry Andric return tryToVectorize(I, R);
61722cab237bSDimitry Andric };
61732cab237bSDimitry Andric return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
61742cab237bSDimitry Andric ExtraVectorization);
61752cab237bSDimitry Andric }
61762cab237bSDimitry Andric
vectorizeInsertValueInst(InsertValueInst * IVI,BasicBlock * BB,BoUpSLP & R)61772cab237bSDimitry Andric bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
61782cab237bSDimitry Andric BasicBlock *BB, BoUpSLP &R) {
61792cab237bSDimitry Andric const DataLayout &DL = BB->getModule()->getDataLayout();
61802cab237bSDimitry Andric if (!R.canMapToVector(IVI->getType(), DL))
61812cab237bSDimitry Andric return false;
61822cab237bSDimitry Andric
61832cab237bSDimitry Andric SmallVector<Value *, 16> BuildVectorOpds;
6184782f2e69SDimitry Andric if (!findBuildAggregate(IVI, BuildVectorOpds))
61852cab237bSDimitry Andric return false;
61862cab237bSDimitry Andric
61874ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
61882cab237bSDimitry Andric // Aggregate value is unlikely to be processed in vector register, we need to
61892cab237bSDimitry Andric // extract scalars into scalar registers, so NeedExtraction is set true.
6190782f2e69SDimitry Andric return tryToVectorizeList(BuildVectorOpds, R);
61912cab237bSDimitry Andric }
61922cab237bSDimitry Andric
vectorizeInsertElementInst(InsertElementInst * IEI,BasicBlock * BB,BoUpSLP & R)61932cab237bSDimitry Andric bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
61942cab237bSDimitry Andric BasicBlock *BB, BoUpSLP &R) {
61954ba319b5SDimitry Andric int UserCost;
61962cab237bSDimitry Andric SmallVector<Value *, 16> BuildVectorOpds;
61974ba319b5SDimitry Andric if (!findBuildVector(IEI, TTI, BuildVectorOpds, UserCost) ||
61984ba319b5SDimitry Andric (llvm::all_of(BuildVectorOpds,
61994ba319b5SDimitry Andric [](Value *V) { return isa<ExtractElementInst>(V); }) &&
62004ba319b5SDimitry Andric isShuffle(BuildVectorOpds)))
62012cab237bSDimitry Andric return false;
62022cab237bSDimitry Andric
62032cab237bSDimitry Andric // Vectorize starting with the build vector operands ignoring the BuildVector
62042cab237bSDimitry Andric // instructions for the purpose of scheduling and user extraction.
62054ba319b5SDimitry Andric return tryToVectorizeList(BuildVectorOpds, R, UserCost);
62062cab237bSDimitry Andric }
62072cab237bSDimitry Andric
vectorizeCmpInst(CmpInst * CI,BasicBlock * BB,BoUpSLP & R)62082cab237bSDimitry Andric bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
62092cab237bSDimitry Andric BoUpSLP &R) {
62102cab237bSDimitry Andric if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
62112cab237bSDimitry Andric return true;
62122cab237bSDimitry Andric
62132cab237bSDimitry Andric bool OpsChanged = false;
62142cab237bSDimitry Andric for (int Idx = 0; Idx < 2; ++Idx) {
62152cab237bSDimitry Andric OpsChanged |=
62162cab237bSDimitry Andric vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
62172cab237bSDimitry Andric }
62182cab237bSDimitry Andric return OpsChanged;
62192cab237bSDimitry Andric }
62202cab237bSDimitry Andric
vectorizeSimpleInstructions(SmallVectorImpl<WeakVH> & Instructions,BasicBlock * BB,BoUpSLP & R)62212cab237bSDimitry Andric bool SLPVectorizerPass::vectorizeSimpleInstructions(
62222cab237bSDimitry Andric SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
62232cab237bSDimitry Andric bool OpsChanged = false;
62242cab237bSDimitry Andric for (auto &VH : reverse(Instructions)) {
62252cab237bSDimitry Andric auto *I = dyn_cast_or_null<Instruction>(VH);
62262cab237bSDimitry Andric if (!I)
62272cab237bSDimitry Andric continue;
62282cab237bSDimitry Andric if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
62292cab237bSDimitry Andric OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
62302cab237bSDimitry Andric else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
62312cab237bSDimitry Andric OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
62322cab237bSDimitry Andric else if (auto *CI = dyn_cast<CmpInst>(I))
62332cab237bSDimitry Andric OpsChanged |= vectorizeCmpInst(CI, BB, R);
62342cab237bSDimitry Andric }
62352cab237bSDimitry Andric Instructions.clear();
62362cab237bSDimitry Andric return OpsChanged;
62377d523365SDimitry Andric }
62387d523365SDimitry Andric
vectorizeChainsInBlock(BasicBlock * BB,BoUpSLP & R)62393ca95b02SDimitry Andric bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
6240284c1978SDimitry Andric bool Changed = false;
6241f785676fSDimitry Andric SmallVector<Value *, 4> Incoming;
62424ba319b5SDimitry Andric SmallPtrSet<Value *, 16> VisitedInstrs;
6243f785676fSDimitry Andric
6244f785676fSDimitry Andric bool HaveVectorizedPhiNodes = true;
6245f785676fSDimitry Andric while (HaveVectorizedPhiNodes) {
6246f785676fSDimitry Andric HaveVectorizedPhiNodes = false;
6247f785676fSDimitry Andric
6248f785676fSDimitry Andric // Collect the incoming values from the PHIs.
6249f785676fSDimitry Andric Incoming.clear();
6250444ed5c5SDimitry Andric for (Instruction &I : *BB) {
6251444ed5c5SDimitry Andric PHINode *P = dyn_cast<PHINode>(&I);
6252f785676fSDimitry Andric if (!P)
6253f785676fSDimitry Andric break;
6254f785676fSDimitry Andric
6255f785676fSDimitry Andric if (!VisitedInstrs.count(P))
6256f785676fSDimitry Andric Incoming.push_back(P);
6257f785676fSDimitry Andric }
6258f785676fSDimitry Andric
6259f785676fSDimitry Andric // Sort by type.
6260f785676fSDimitry Andric std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
6261f785676fSDimitry Andric
6262f785676fSDimitry Andric // Try to vectorize elements base on their type.
6263f785676fSDimitry Andric for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
6264f785676fSDimitry Andric E = Incoming.end();
6265f785676fSDimitry Andric IncIt != E;) {
6266f785676fSDimitry Andric
6267f785676fSDimitry Andric // Look for the next elements with the same type.
6268f785676fSDimitry Andric SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
6269f785676fSDimitry Andric while (SameTypeIt != E &&
6270f785676fSDimitry Andric (*SameTypeIt)->getType() == (*IncIt)->getType()) {
6271f785676fSDimitry Andric VisitedInstrs.insert(*SameTypeIt);
6272f785676fSDimitry Andric ++SameTypeIt;
6273f785676fSDimitry Andric }
6274f785676fSDimitry Andric
6275f785676fSDimitry Andric // Try to vectorize them.
6276f785676fSDimitry Andric unsigned NumElts = (SameTypeIt - IncIt);
62774ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
62784ba319b5SDimitry Andric << NumElts << ")\n");
62796bc11b14SDimitry Andric // The order in which the phi nodes appear in the program does not matter.
62806bc11b14SDimitry Andric // So allow tryToVectorizeList to reorder them if it is beneficial. This
62816bc11b14SDimitry Andric // is done when there are exactly two elements since tryToVectorizeList
62826bc11b14SDimitry Andric // asserts that there are only two values when AllowReorder is true.
62836bc11b14SDimitry Andric bool AllowReorder = NumElts == 2;
62844ba319b5SDimitry Andric if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
62854ba319b5SDimitry Andric /*UserCost=*/0, AllowReorder)) {
6286f785676fSDimitry Andric // Success start over because instructions might have been changed.
6287f785676fSDimitry Andric HaveVectorizedPhiNodes = true;
6288f785676fSDimitry Andric Changed = true;
6289f785676fSDimitry Andric break;
6290f785676fSDimitry Andric }
6291f785676fSDimitry Andric
629291bc56edSDimitry Andric // Start over at the next instruction of a different type (or the end).
6293f785676fSDimitry Andric IncIt = SameTypeIt;
6294f785676fSDimitry Andric }
6295f785676fSDimitry Andric }
6296f785676fSDimitry Andric
6297f785676fSDimitry Andric VisitedInstrs.clear();
6298f785676fSDimitry Andric
62992cab237bSDimitry Andric SmallVector<WeakVH, 8> PostProcessInstructions;
63002cab237bSDimitry Andric SmallDenseSet<Instruction *, 4> KeyNodes;
6301f785676fSDimitry Andric for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
6302f785676fSDimitry Andric // We may go through BB multiple times so skip the one we have checked.
63032cab237bSDimitry Andric if (!VisitedInstrs.insert(&*it).second) {
63042cab237bSDimitry Andric if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
63052cab237bSDimitry Andric vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
63062cab237bSDimitry Andric // We would like to start over since some instructions are deleted
63072cab237bSDimitry Andric // and the iterator may become invalid value.
63082cab237bSDimitry Andric Changed = true;
63092cab237bSDimitry Andric it = BB->begin();
63102cab237bSDimitry Andric e = BB->end();
63112cab237bSDimitry Andric }
6312f785676fSDimitry Andric continue;
63132cab237bSDimitry Andric }
6314f785676fSDimitry Andric
6315f785676fSDimitry Andric if (isa<DbgInfoIntrinsic>(it))
6316f785676fSDimitry Andric continue;
6317284c1978SDimitry Andric
6318284c1978SDimitry Andric // Try to vectorize reductions that use PHINodes.
6319284c1978SDimitry Andric if (PHINode *P = dyn_cast<PHINode>(it)) {
6320284c1978SDimitry Andric // Check that the PHI is a reduction PHI.
6321f785676fSDimitry Andric if (P->getNumIncomingValues() != 2)
6322f785676fSDimitry Andric return Changed;
63237d523365SDimitry Andric
6324f785676fSDimitry Andric // Try to match and vectorize a horizontal reduction.
63257a7e6055SDimitry Andric if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
63267a7e6055SDimitry Andric TTI)) {
6327f785676fSDimitry Andric Changed = true;
6328f785676fSDimitry Andric it = BB->begin();
6329f785676fSDimitry Andric e = BB->end();
6330284c1978SDimitry Andric continue;
6331284c1978SDimitry Andric }
63327a7e6055SDimitry Andric continue;
63337a7e6055SDimitry Andric }
6334284c1978SDimitry Andric
63352cab237bSDimitry Andric // Ran into an instruction without users, like terminator, or function call
63362cab237bSDimitry Andric // with ignored return value, store. Ignore unused instructions (basing on
63372cab237bSDimitry Andric // instruction type, except for CallInst and InvokeInst).
63382cab237bSDimitry Andric if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
63392cab237bSDimitry Andric isa<InvokeInst>(it))) {
63402cab237bSDimitry Andric KeyNodes.insert(&*it);
63412cab237bSDimitry Andric bool OpsChanged = false;
63422cab237bSDimitry Andric if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
63432cab237bSDimitry Andric for (auto *V : it->operand_values()) {
63447a7e6055SDimitry Andric // Try to match and vectorize a horizontal reduction.
63452cab237bSDimitry Andric OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
6346f785676fSDimitry Andric }
6347f785676fSDimitry Andric }
63482cab237bSDimitry Andric // Start vectorization of post-process list of instructions from the
63492cab237bSDimitry Andric // top-tree instructions to try to vectorize as many instructions as
63502cab237bSDimitry Andric // possible.
63512cab237bSDimitry Andric OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
63522cab237bSDimitry Andric if (OpsChanged) {
6353f785676fSDimitry Andric // We would like to start over since some instructions are deleted
6354f785676fSDimitry Andric // and the iterator may become invalid value.
6355f785676fSDimitry Andric Changed = true;
6356f785676fSDimitry Andric it = BB->begin();
6357f785676fSDimitry Andric e = BB->end();
63583ca95b02SDimitry Andric continue;
63593ca95b02SDimitry Andric }
63603ca95b02SDimitry Andric }
63612cab237bSDimitry Andric
63622cab237bSDimitry Andric if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
63632cab237bSDimitry Andric isa<InsertValueInst>(it))
63642cab237bSDimitry Andric PostProcessInstructions.push_back(&*it);
6365284c1978SDimitry Andric }
6366284c1978SDimitry Andric
6367284c1978SDimitry Andric return Changed;
6368284c1978SDimitry Andric }
6369284c1978SDimitry Andric
vectorizeGEPIndices(BasicBlock * BB,BoUpSLP & R)63703ca95b02SDimitry Andric bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
63713ca95b02SDimitry Andric auto Changed = false;
63723ca95b02SDimitry Andric for (auto &Entry : GEPs) {
63733ca95b02SDimitry Andric // If the getelementptr list has fewer than two elements, there's nothing
63743ca95b02SDimitry Andric // to do.
63753ca95b02SDimitry Andric if (Entry.second.size() < 2)
63763ca95b02SDimitry Andric continue;
63773ca95b02SDimitry Andric
63784ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
63793ca95b02SDimitry Andric << Entry.second.size() << ".\n");
63803ca95b02SDimitry Andric
63813ca95b02SDimitry Andric // We process the getelementptr list in chunks of 16 (like we do for
63823ca95b02SDimitry Andric // stores) to minimize compile-time.
63833ca95b02SDimitry Andric for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
63843ca95b02SDimitry Andric auto Len = std::min<unsigned>(BE - BI, 16);
63853ca95b02SDimitry Andric auto GEPList = makeArrayRef(&Entry.second[BI], Len);
63863ca95b02SDimitry Andric
63873ca95b02SDimitry Andric // Initialize a set a candidate getelementptrs. Note that we use a
63883ca95b02SDimitry Andric // SetVector here to preserve program order. If the index computations
63893ca95b02SDimitry Andric // are vectorizable and begin with loads, we want to minimize the chance
63903ca95b02SDimitry Andric // of having to reorder them later.
63913ca95b02SDimitry Andric SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
63923ca95b02SDimitry Andric
63933ca95b02SDimitry Andric // Some of the candidates may have already been vectorized after we
6394f37b6182SDimitry Andric // initially collected them. If so, the WeakTrackingVHs will have
6395f37b6182SDimitry Andric // nullified the
63963ca95b02SDimitry Andric // values, so remove them from the set of candidates.
63973ca95b02SDimitry Andric Candidates.remove(nullptr);
63983ca95b02SDimitry Andric
63993ca95b02SDimitry Andric // Remove from the set of candidates all pairs of getelementptrs with
64003ca95b02SDimitry Andric // constant differences. Such getelementptrs are likely not good
64013ca95b02SDimitry Andric // candidates for vectorization in a bottom-up phase since one can be
64023ca95b02SDimitry Andric // computed from the other. We also ensure all candidate getelementptr
64033ca95b02SDimitry Andric // indices are unique.
64043ca95b02SDimitry Andric for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
64053ca95b02SDimitry Andric auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
64063ca95b02SDimitry Andric if (!Candidates.count(GEPI))
64073ca95b02SDimitry Andric continue;
64083ca95b02SDimitry Andric auto *SCEVI = SE->getSCEV(GEPList[I]);
64093ca95b02SDimitry Andric for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
64103ca95b02SDimitry Andric auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
64113ca95b02SDimitry Andric auto *SCEVJ = SE->getSCEV(GEPList[J]);
64123ca95b02SDimitry Andric if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
64133ca95b02SDimitry Andric Candidates.remove(GEPList[I]);
64143ca95b02SDimitry Andric Candidates.remove(GEPList[J]);
64153ca95b02SDimitry Andric } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
64163ca95b02SDimitry Andric Candidates.remove(GEPList[J]);
64173ca95b02SDimitry Andric }
64183ca95b02SDimitry Andric }
64193ca95b02SDimitry Andric }
64203ca95b02SDimitry Andric
64213ca95b02SDimitry Andric // We break out of the above computation as soon as we know there are
64223ca95b02SDimitry Andric // fewer than two candidates remaining.
64233ca95b02SDimitry Andric if (Candidates.size() < 2)
64243ca95b02SDimitry Andric continue;
64253ca95b02SDimitry Andric
64263ca95b02SDimitry Andric // Add the single, non-constant index of each candidate to the bundle. We
64273ca95b02SDimitry Andric // ensured the indices met these constraints when we originally collected
64283ca95b02SDimitry Andric // the getelementptrs.
64293ca95b02SDimitry Andric SmallVector<Value *, 16> Bundle(Candidates.size());
64303ca95b02SDimitry Andric auto BundleIndex = 0u;
64313ca95b02SDimitry Andric for (auto *V : Candidates) {
64323ca95b02SDimitry Andric auto *GEP = cast<GetElementPtrInst>(V);
64333ca95b02SDimitry Andric auto *GEPIdx = GEP->idx_begin()->get();
64343ca95b02SDimitry Andric assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
64353ca95b02SDimitry Andric Bundle[BundleIndex++] = GEPIdx;
64363ca95b02SDimitry Andric }
64373ca95b02SDimitry Andric
64383ca95b02SDimitry Andric // Try and vectorize the indices. We are currently only interested in
64393ca95b02SDimitry Andric // gather-like cases of the form:
64403ca95b02SDimitry Andric //
64413ca95b02SDimitry Andric // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
64423ca95b02SDimitry Andric //
64433ca95b02SDimitry Andric // where the loads of "a", the loads of "b", and the subtractions can be
64443ca95b02SDimitry Andric // performed in parallel. It's likely that detecting this pattern in a
64453ca95b02SDimitry Andric // bottom-up phase will be simpler and less costly than building a
64463ca95b02SDimitry Andric // full-blown top-down phase beginning at the consecutive loads.
64473ca95b02SDimitry Andric Changed |= tryToVectorizeList(Bundle, R);
64483ca95b02SDimitry Andric }
64493ca95b02SDimitry Andric }
64503ca95b02SDimitry Andric return Changed;
64513ca95b02SDimitry Andric }
64523ca95b02SDimitry Andric
vectorizeStoreChains(BoUpSLP & R)64533ca95b02SDimitry Andric bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
6454284c1978SDimitry Andric bool Changed = false;
6455284c1978SDimitry Andric // Attempt to sort and vectorize each of the store-groups.
64563ca95b02SDimitry Andric for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
64573ca95b02SDimitry Andric ++it) {
6458284c1978SDimitry Andric if (it->second.size() < 2)
6459284c1978SDimitry Andric continue;
6460284c1978SDimitry Andric
64614ba319b5SDimitry Andric LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
6462f785676fSDimitry Andric << it->second.size() << ".\n");
6463284c1978SDimitry Andric
6464f785676fSDimitry Andric // Process the stores in chunks of 16.
6465875ed548SDimitry Andric // TODO: The limit of 16 inhibits greater vectorization factors.
6466875ed548SDimitry Andric // For example, AVX2 supports v32i8. Increasing this limit, however,
6467875ed548SDimitry Andric // may cause a significant compile-time increase.
6468f785676fSDimitry Andric for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI += 16) {
6469f785676fSDimitry Andric unsigned Len = std::min<unsigned>(CE - CI, 16);
6470d88c1a5aSDimitry Andric Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
6471f785676fSDimitry Andric }
6472284c1978SDimitry Andric }
6473284c1978SDimitry Andric return Changed;
6474284c1978SDimitry Andric }
6475284c1978SDimitry Andric
6476284c1978SDimitry Andric char SLPVectorizer::ID = 0;
64772cab237bSDimitry Andric
6478284c1978SDimitry Andric static const char lv_name[] = "SLP Vectorizer";
64792cab237bSDimitry Andric
INITIALIZE_PASS_BEGIN(SLPVectorizer,SV_NAME,lv_name,false,false)6480284c1978SDimitry Andric INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
64817d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6482ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
648339d628a0SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
64847d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6485284c1978SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
64863ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
64875517e702SDimitry Andric INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6488284c1978SDimitry Andric INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
6489284c1978SDimitry Andric
64902cab237bSDimitry Andric Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
6491