Bug Summary

File:lib/Transforms/Vectorize/LoopVectorize.cpp
Warning:line 6387, column 60
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LoopVectorize.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/lib/Transforms/Vectorize -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp
1//===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11// and generates target-independent LLVM-IR.
12// The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13// of instructions in order to estimate the profitability of vectorization.
14//
15// The loop vectorizer combines consecutive loop iterations into a single
16// 'wide' iteration. After this transformation the index is incremented
17// by the SIMD vector width, and not by one.
18//
19// This pass has three parts:
20// 1. The main loop pass that drives the different parts.
21// 2. LoopVectorizationLegality - A unit that checks for the legality
22// of the vectorization.
23// 3. InnerLoopVectorizer - A unit that performs the actual
24// widening of instructions.
25// 4. LoopVectorizationCostModel - A unit that checks for the profitability
26// of vectorization. It decides on the optimal vector width, which
27// can be one, if vectorization is not profitable.
28//
29//===----------------------------------------------------------------------===//
30//
31// The reduction-variable vectorization is based on the paper:
32// D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33//
34// Variable uniformity checks are inspired by:
35// Karrenberg, R. and Hack, S. Whole Function Vectorization.
36//
37// The interleaved access vectorization is based on the paper:
38// Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
39// Data for SIMD
40//
41// Other ideas/concepts are from:
42// A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
43//
44// S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
45// Vectorizing Compilers.
46//
47//===----------------------------------------------------------------------===//
48
49#include "llvm/Transforms/Vectorize/LoopVectorize.h"
50#include "LoopVectorizationPlanner.h"
51#include "llvm/ADT/APInt.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/DenseMap.h"
54#include "llvm/ADT/DenseMapInfo.h"
55#include "llvm/ADT/Hashing.h"
56#include "llvm/ADT/MapVector.h"
57#include "llvm/ADT/None.h"
58#include "llvm/ADT/Optional.h"
59#include "llvm/ADT/SCCIterator.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallPtrSet.h"
63#include "llvm/ADT/SmallSet.h"
64#include "llvm/ADT/SmallVector.h"
65#include "llvm/ADT/Statistic.h"
66#include "llvm/ADT/StringRef.h"
67#include "llvm/ADT/Twine.h"
68#include "llvm/ADT/iterator_range.h"
69#include "llvm/Analysis/AssumptionCache.h"
70#include "llvm/Analysis/BasicAliasAnalysis.h"
71#include "llvm/Analysis/BlockFrequencyInfo.h"
72#include "llvm/Analysis/CodeMetrics.h"
73#include "llvm/Analysis/DemandedBits.h"
74#include "llvm/Analysis/GlobalsModRef.h"
75#include "llvm/Analysis/LoopAccessAnalysis.h"
76#include "llvm/Analysis/LoopAnalysisManager.h"
77#include "llvm/Analysis/LoopInfo.h"
78#include "llvm/Analysis/LoopIterator.h"
79#include "llvm/Analysis/OptimizationRemarkEmitter.h"
80#include "llvm/Analysis/ScalarEvolution.h"
81#include "llvm/Analysis/ScalarEvolutionExpander.h"
82#include "llvm/Analysis/ScalarEvolutionExpressions.h"
83#include "llvm/Analysis/TargetLibraryInfo.h"
84#include "llvm/Analysis/TargetTransformInfo.h"
85#include "llvm/Analysis/VectorUtils.h"
86#include "llvm/IR/Attributes.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/CFG.h"
89#include "llvm/IR/Constant.h"
90#include "llvm/IR/Constants.h"
91#include "llvm/IR/DataLayout.h"
92#include "llvm/IR/DebugInfoMetadata.h"
93#include "llvm/IR/DebugLoc.h"
94#include "llvm/IR/DerivedTypes.h"
95#include "llvm/IR/DiagnosticInfo.h"
96#include "llvm/IR/Dominators.h"
97#include "llvm/IR/Function.h"
98#include "llvm/IR/IRBuilder.h"
99#include "llvm/IR/InstrTypes.h"
100#include "llvm/IR/Instruction.h"
101#include "llvm/IR/Instructions.h"
102#include "llvm/IR/IntrinsicInst.h"
103#include "llvm/IR/Intrinsics.h"
104#include "llvm/IR/LLVMContext.h"
105#include "llvm/IR/Metadata.h"
106#include "llvm/IR/Module.h"
107#include "llvm/IR/Operator.h"
108#include "llvm/IR/Type.h"
109#include "llvm/IR/Use.h"
110#include "llvm/IR/User.h"
111#include "llvm/IR/Value.h"
112#include "llvm/IR/ValueHandle.h"
113#include "llvm/IR/Verifier.h"
114#include "llvm/Pass.h"
115#include "llvm/Support/Casting.h"
116#include "llvm/Support/CommandLine.h"
117#include "llvm/Support/Compiler.h"
118#include "llvm/Support/Debug.h"
119#include "llvm/Support/ErrorHandling.h"
120#include "llvm/Support/MathExtras.h"
121#include "llvm/Support/raw_ostream.h"
122#include "llvm/Transforms/Utils/BasicBlockUtils.h"
123#include "llvm/Transforms/Utils/LoopSimplify.h"
124#include "llvm/Transforms/Utils/LoopUtils.h"
125#include "llvm/Transforms/Utils/LoopVersioning.h"
126#include <algorithm>
127#include <cassert>
128#include <cstdint>
129#include <cstdlib>
130#include <functional>
131#include <iterator>
132#include <limits>
133#include <memory>
134#include <string>
135#include <tuple>
136#include <utility>
137#include <vector>
138
139using namespace llvm;
140
141#define LV_NAME"loop-vectorize" "loop-vectorize"
142#define DEBUG_TYPE"loop-vectorize" LV_NAME"loop-vectorize"
143
144STATISTIC(LoopsVectorized, "Number of loops vectorized")static llvm::Statistic LoopsVectorized = {"loop-vectorize", "LoopsVectorized"
, "Number of loops vectorized", {0}, {false}}
;
145STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization")static llvm::Statistic LoopsAnalyzed = {"loop-vectorize", "LoopsAnalyzed"
, "Number of loops analyzed for vectorization", {0}, {false}}
;
146
147static cl::opt<bool>
148 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
149 cl::desc("Enable if-conversion during vectorization."));
150
151/// Loops with a known constant trip count below this number are vectorized only
152/// if no scalar iteration overheads are incurred.
153static cl::opt<unsigned> TinyTripCountVectorThreshold(
154 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
155 cl::desc("Loops with a constant trip count that is smaller than this "
156 "value are vectorized only if no scalar iteration overheads "
157 "are incurred."));
158
159static cl::opt<bool> MaximizeBandwidth(
160 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
161 cl::desc("Maximize bandwidth when selecting vectorization factor which "
162 "will be determined by the smallest type in loop."));
163
164static cl::opt<bool> EnableInterleavedMemAccesses(
165 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
166 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
167
168/// Maximum factor for an interleaved memory access.
169static cl::opt<unsigned> MaxInterleaveGroupFactor(
170 "max-interleave-group-factor", cl::Hidden,
171 cl::desc("Maximum factor for an interleaved access group (default = 8)"),
172 cl::init(8));
173
174/// We don't interleave loops with a known constant trip count below this
175/// number.
176static const unsigned TinyTripCountInterleaveThreshold = 128;
177
178static cl::opt<unsigned> ForceTargetNumScalarRegs(
179 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
180 cl::desc("A flag that overrides the target's number of scalar registers."));
181
182static cl::opt<unsigned> ForceTargetNumVectorRegs(
183 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
184 cl::desc("A flag that overrides the target's number of vector registers."));
185
186/// Maximum vectorization interleave count.
187static const unsigned MaxInterleaveFactor = 16;
188
189static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
190 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
191 cl::desc("A flag that overrides the target's max interleave factor for "
192 "scalar loops."));
193
194static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
195 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
196 cl::desc("A flag that overrides the target's max interleave factor for "
197 "vectorized loops."));
198
199static cl::opt<unsigned> ForceTargetInstructionCost(
200 "force-target-instruction-cost", cl::init(0), cl::Hidden,
201 cl::desc("A flag that overrides the target's expected cost for "
202 "an instruction to a single constant value. Mostly "
203 "useful for getting consistent testing."));
204
205static cl::opt<unsigned> SmallLoopCost(
206 "small-loop-cost", cl::init(20), cl::Hidden,
207 cl::desc(
208 "The cost of a loop that is considered 'small' by the interleaver."));
209
210static cl::opt<bool> LoopVectorizeWithBlockFrequency(
211 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
212 cl::desc("Enable the use of the block frequency analysis to access PGO "
213 "heuristics minimizing code growth in cold regions and being more "
214 "aggressive in hot regions."));
215
216// Runtime interleave loops for load/store throughput.
217static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
218 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
219 cl::desc(
220 "Enable runtime interleaving until load/store ports are saturated"));
221
222/// The number of stores in a loop that are allowed to need predication.
223static cl::opt<unsigned> NumberOfStoresToPredicate(
224 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
225 cl::desc("Max number of stores to be predicated behind an if."));
226
227static cl::opt<bool> EnableIndVarRegisterHeur(
228 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
229 cl::desc("Count the induction variable only once when interleaving"));
230
231static cl::opt<bool> EnableCondStoresVectorization(
232 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
233 cl::desc("Enable if predication of stores during vectorization."));
234
235static cl::opt<unsigned> MaxNestedScalarReductionIC(
236 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
237 cl::desc("The maximum interleave count to use when interleaving a scalar "
238 "reduction in a nested loop."));
239
240static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
241 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
242 cl::desc("The maximum allowed number of runtime memory checks with a "
243 "vectorize(enable) pragma."));
244
245static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
246 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
247 cl::desc("The maximum number of SCEV checks allowed."));
248
249static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
250 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
251 cl::desc("The maximum number of SCEV checks allowed with a "
252 "vectorize(enable) pragma"));
253
254/// Create an analysis remark that explains why vectorization failed
255///
256/// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
257/// RemarkName is the identifier for the remark. If \p I is passed it is an
258/// instruction that prevents vectorization. Otherwise \p TheLoop is used for
259/// the location of the remark. \return the remark object that can be
260/// streamed to.
261static OptimizationRemarkAnalysis
262createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
263 Instruction *I = nullptr) {
264 Value *CodeRegion = TheLoop->getHeader();
265 DebugLoc DL = TheLoop->getStartLoc();
266
267 if (I) {
268 CodeRegion = I->getParent();
269 // If there is no debug location attached to the instruction, revert back to
270 // using the loop's.
271 if (I->getDebugLoc())
272 DL = I->getDebugLoc();
273 }
274
275 OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
276 R << "loop not vectorized: ";
277 return R;
278}
279
280namespace {
281
282class LoopVectorizationRequirements;
283
284} // end anonymous namespace
285
286/// Returns true if the given loop body has a cycle, excluding the loop
287/// itself.
288static bool hasCyclesInLoopBody(const Loop &L) {
289 if (!L.empty())
290 return true;
291
292 for (const auto &SCC :
293 make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L),
294 scc_iterator<Loop, LoopBodyTraits>::end(L))) {
295 if (SCC.size() > 1) {
296 DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LVL: Detected a cycle in the loop body:\n"
; } } while (false)
;
297 DEBUG(L.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { L.dump(); } } while (false)
;
298 return true;
299 }
300 }
301 return false;
302}
303
304/// A helper function for converting Scalar types to vector types.
305/// If the incoming type is void, we return void. If the VF is 1, we return
306/// the scalar type.
307static Type *ToVectorTy(Type *Scalar, unsigned VF) {
308 if (Scalar->isVoidTy() || VF == 1)
309 return Scalar;
310 return VectorType::get(Scalar, VF);
311}
312
313// FIXME: The following helper functions have multiple implementations
314// in the project. They can be effectively organized in a common Load/Store
315// utilities unit.
316
317/// A helper function that returns the pointer operand of a load or store
318/// instruction.
319static Value *getPointerOperand(Value *I) {
320 if (auto *LI = dyn_cast<LoadInst>(I))
321 return LI->getPointerOperand();
322 if (auto *SI = dyn_cast<StoreInst>(I))
323 return SI->getPointerOperand();
324 return nullptr;
325}
326
327/// A helper function that returns the type of loaded or stored value.
328static Type *getMemInstValueType(Value *I) {
329 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 330, __extension__ __PRETTY_FUNCTION__))
330 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 330, __extension__ __PRETTY_FUNCTION__))
;
331 if (auto *LI = dyn_cast<LoadInst>(I))
332 return LI->getType();
333 return cast<StoreInst>(I)->getValueOperand()->getType();
334}
335
336/// A helper function that returns the alignment of load or store instruction.
337static unsigned getMemInstAlignment(Value *I) {
338 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 339, __extension__ __PRETTY_FUNCTION__))
339 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 339, __extension__ __PRETTY_FUNCTION__))
;
340 if (auto *LI = dyn_cast<LoadInst>(I))
341 return LI->getAlignment();
342 return cast<StoreInst>(I)->getAlignment();
343}
344
345/// A helper function that returns the address space of the pointer operand of
346/// load or store instruction.
347static unsigned getMemInstAddressSpace(Value *I) {
348 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 349, __extension__ __PRETTY_FUNCTION__))
349 "Expected Load or Store instruction")(static_cast <bool> ((isa<LoadInst>(I) || isa<
StoreInst>(I)) && "Expected Load or Store instruction"
) ? void (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 if (auto *LI = dyn_cast<LoadInst>(I))
351 return LI->getPointerAddressSpace();
352 return cast<StoreInst>(I)->getPointerAddressSpace();
353}
354
355/// A helper function that returns true if the given type is irregular. The
356/// type is irregular if its allocated size doesn't equal the store size of an
357/// element of the corresponding vector type at the given vectorization factor.
358static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
359 // Determine if an array of VF elements of type Ty is "bitcast compatible"
360 // with a <VF x Ty> vector.
361 if (VF > 1) {
362 auto *VectorTy = VectorType::get(Ty, VF);
363 return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
364 }
365
366 // If the vectorization factor is one, we just check if an array of type Ty
367 // requires padding between elements.
368 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
369}
370
371/// A helper function that returns the reciprocal of the block probability of
372/// predicated blocks. If we return X, we are assuming the predicated block
373/// will execute once for every X iterations of the loop header.
374///
375/// TODO: We should use actual block probability here, if available. Currently,
376/// we always assume predicated blocks have a 50% chance of executing.
377static unsigned getReciprocalPredBlockProb() { return 2; }
378
379/// A helper function that adds a 'fast' flag to floating-point operations.
380static Value *addFastMathFlag(Value *V) {
381 if (isa<FPMathOperator>(V)) {
382 FastMathFlags Flags;
383 Flags.setFast();
384 cast<Instruction>(V)->setFastMathFlags(Flags);
385 }
386 return V;
387}
388
389/// A helper function that returns an integer or floating-point constant with
390/// value C.
391static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
392 return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
393 : ConstantFP::get(Ty, C);
394}
395
396namespace llvm {
397
398/// InnerLoopVectorizer vectorizes loops which contain only one basic
399/// block to a specified vectorization factor (VF).
400/// This class performs the widening of scalars into vectors, or multiple
401/// scalars. This class also implements the following features:
402/// * It inserts an epilogue loop for handling loops that don't have iteration
403/// counts that are known to be a multiple of the vectorization factor.
404/// * It handles the code generation for reduction variables.
405/// * Scalarization (implementation using scalars) of un-vectorizable
406/// instructions.
407/// InnerLoopVectorizer does not perform any vectorization-legality
408/// checks, and relies on the caller to check for the different legality
409/// aspects. The InnerLoopVectorizer relies on the
410/// LoopVectorizationLegality class to provide information about the induction
411/// and reduction variables that were found to a given vectorization factor.
412class InnerLoopVectorizer {
413public:
414 InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
415 LoopInfo *LI, DominatorTree *DT,
416 const TargetLibraryInfo *TLI,
417 const TargetTransformInfo *TTI, AssumptionCache *AC,
418 OptimizationRemarkEmitter *ORE, unsigned VecWidth,
419 unsigned UnrollFactor, LoopVectorizationLegality *LVL,
420 LoopVectorizationCostModel *CM)
421 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
422 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
423 Builder(PSE.getSE()->getContext()),
424 VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
425 virtual ~InnerLoopVectorizer() = default;
426
427 /// Create a new empty loop. Unlink the old loop and connect the new one.
428 /// Return the pre-header block of the new loop.
429 BasicBlock *createVectorizedLoopSkeleton();
430
431 /// Widen a single instruction within the innermost loop.
432 void widenInstruction(Instruction &I);
433
434 /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
435 void fixVectorizedLoop();
436
437 // Return true if any runtime check is added.
438 bool areSafetyChecksAdded() { return AddedSafetyChecks; }
439
440 /// A type for vectorized values in the new loop. Each value from the
441 /// original loop, when vectorized, is represented by UF vector values in the
442 /// new unrolled loop, where UF is the unroll factor.
443 using VectorParts = SmallVector<Value *, 2>;
444
445 /// Vectorize a single PHINode in a block. This method handles the induction
446 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
447 /// arbitrary length vectors.
448 void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
449
450 /// A helper function to scalarize a single Instruction in the innermost loop.
451 /// Generates a sequence of scalar instances for each lane between \p MinLane
452 /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
453 /// inclusive..
454 void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
455 bool IfPredicateInstr);
456
457 /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
458 /// is provided, the integer induction variable will first be truncated to
459 /// the corresponding type.
460 void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
461
462 /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
463 /// vector or scalar value on-demand if one is not yet available. When
464 /// vectorizing a loop, we visit the definition of an instruction before its
465 /// uses. When visiting the definition, we either vectorize or scalarize the
466 /// instruction, creating an entry for it in the corresponding map. (In some
467 /// cases, such as induction variables, we will create both vector and scalar
468 /// entries.) Then, as we encounter uses of the definition, we derive values
469 /// for each scalar or vector use unless such a value is already available.
470 /// For example, if we scalarize a definition and one of its uses is vector,
471 /// we build the required vector on-demand with an insertelement sequence
472 /// when visiting the use. Otherwise, if the use is scalar, we can use the
473 /// existing scalar definition.
474 ///
475 /// Return a value in the new loop corresponding to \p V from the original
476 /// loop at unroll index \p Part. If the value has already been vectorized,
477 /// the corresponding vector entry in VectorLoopValueMap is returned. If,
478 /// however, the value has a scalar entry in VectorLoopValueMap, we construct
479 /// a new vector value on-demand by inserting the scalar values into a vector
480 /// with an insertelement sequence. If the value has been neither vectorized
481 /// nor scalarized, it must be loop invariant, so we simply broadcast the
482 /// value into a vector.
483 Value *getOrCreateVectorValue(Value *V, unsigned Part);
484
485 /// Return a value in the new loop corresponding to \p V from the original
486 /// loop at unroll and vector indices \p Instance. If the value has been
487 /// vectorized but not scalarized, the necessary extractelement instruction
488 /// will be generated.
489 Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
490
491 /// Construct the vector value of a scalarized value \p V one lane at a time.
492 void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
493
494 /// Try to vectorize the interleaved access group that \p Instr belongs to.
495 void vectorizeInterleaveGroup(Instruction *Instr);
496
497 /// Vectorize Load and Store instructions, optionally masking the vector
498 /// operations if \p BlockInMask is non-null.
499 void vectorizeMemoryInstruction(Instruction *Instr,
500 VectorParts *BlockInMask = nullptr);
501
502 /// \brief Set the debug location in the builder using the debug location in
503 /// the instruction.
504 void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
505
506protected:
507 friend class LoopVectorizationPlanner;
508
509 /// A small list of PHINodes.
510 using PhiVector = SmallVector<PHINode *, 4>;
511
512 /// A type for scalarized values in the new loop. Each value from the
513 /// original loop, when scalarized, is represented by UF x VF scalar values
514 /// in the new unrolled loop, where UF is the unroll factor and VF is the
515 /// vectorization factor.
516 using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
517
518 /// Set up the values of the IVs correctly when exiting the vector loop.
519 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
520 Value *CountRoundDown, Value *EndValue,
521 BasicBlock *MiddleBlock);
522
523 /// Create a new induction variable inside L.
524 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
525 Value *Step, Instruction *DL);
526
527 /// Handle all cross-iteration phis in the header.
528 void fixCrossIterationPHIs();
529
530 /// Fix a first-order recurrence. This is the second phase of vectorizing
531 /// this phi node.
532 void fixFirstOrderRecurrence(PHINode *Phi);
533
534 /// Fix a reduction cross-iteration phi. This is the second phase of
535 /// vectorizing this phi node.
536 void fixReduction(PHINode *Phi);
537
538 /// \brief The Loop exit block may have single value PHI nodes with some
539 /// incoming value. While vectorizing we only handled real values
540 /// that were defined inside the loop and we should have one value for
541 /// each predecessor of its parent basic block. See PR14725.
542 void fixLCSSAPHIs();
543
544 /// Iteratively sink the scalarized operands of a predicated instruction into
545 /// the block that was created for it.
546 void sinkScalarOperands(Instruction *PredInst);
547
548 /// Shrinks vector element sizes to the smallest bitwidth they can be legally
549 /// represented as.
550 void truncateToMinimalBitwidths();
551
552 /// Insert the new loop to the loop hierarchy and pass manager
553 /// and update the analysis passes.
554 void updateAnalysis();
555
556 /// Create a broadcast instruction. This method generates a broadcast
557 /// instruction (shuffle) for loop invariant values and for the induction
558 /// value. If this is the induction variable then we extend it to N, N+1, ...
559 /// this is needed because each iteration in the loop corresponds to a SIMD
560 /// element.
561 virtual Value *getBroadcastInstrs(Value *V);
562
563 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
564 /// to each vector element of Val. The sequence starts at StartIndex.
565 /// \p Opcode is relevant for FP induction variable.
566 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
567 Instruction::BinaryOps Opcode =
568 Instruction::BinaryOpsEnd);
569
570 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
571 /// variable on which to base the steps, \p Step is the size of the step, and
572 /// \p EntryVal is the value from the original loop that maps to the steps.
573 /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
574 /// can be a truncate instruction).
575 void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal,
576 const InductionDescriptor &ID);
577
578 /// Create a vector induction phi node based on an existing scalar one. \p
579 /// EntryVal is the value from the original loop that maps to the vector phi
580 /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
581 /// truncate instruction, instead of widening the original IV, we widen a
582 /// version of the IV truncated to \p EntryVal's type.
583 void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
584 Value *Step, Instruction *EntryVal);
585
586 /// Returns true if an instruction \p I should be scalarized instead of
587 /// vectorized for the chosen vectorization factor.
588 bool shouldScalarizeInstruction(Instruction *I) const;
589
590 /// Returns true if we should generate a scalar version of \p IV.
591 bool needsScalarInduction(Instruction *IV) const;
592
593 /// If there is a cast involved in the induction variable \p ID, which should
594 /// be ignored in the vectorized loop body, this function records the
595 /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
596 /// cast. We had already proved that the casted Phi is equal to the uncasted
597 /// Phi in the vectorized loop (under a runtime guard), and therefore
598 /// there is no need to vectorize the cast - the same value can be used in the
599 /// vector loop for both the Phi and the cast.
600 /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
601 /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
602 void recordVectorLoopValueForInductionCast (const InductionDescriptor &ID,
603 Value *VectorLoopValue,
604 unsigned Part,
605 unsigned Lane = UINT_MAX(2147483647 *2U +1U));
606
607 /// Generate a shuffle sequence that will reverse the vector Vec.
608 virtual Value *reverseVector(Value *Vec);
609
610 /// Returns (and creates if needed) the original loop trip count.
611 Value *getOrCreateTripCount(Loop *NewLoop);
612
613 /// Returns (and creates if needed) the trip count of the widened loop.
614 Value *getOrCreateVectorTripCount(Loop *NewLoop);
615
616 /// Returns a bitcasted value to the requested vector type.
617 /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
618 Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
619 const DataLayout &DL);
620
621 /// Emit a bypass check to see if the vector trip count is zero, including if
622 /// it overflows.
623 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
624
625 /// Emit a bypass check to see if all of the SCEV assumptions we've
626 /// had to make are correct.
627 void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
628
629 /// Emit bypass checks to check any memory assumptions we may have made.
630 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
631
632 /// Add additional metadata to \p To that was not present on \p Orig.
633 ///
634 /// Currently this is used to add the noalias annotations based on the
635 /// inserted memchecks. Use this for instructions that are *cloned* into the
636 /// vector loop.
637 void addNewMetadata(Instruction *To, const Instruction *Orig);
638
639 /// Add metadata from one instruction to another.
640 ///
641 /// This includes both the original MDs from \p From and additional ones (\see
642 /// addNewMetadata). Use this for *newly created* instructions in the vector
643 /// loop.
644 void addMetadata(Instruction *To, Instruction *From);
645
646 /// \brief Similar to the previous function but it adds the metadata to a
647 /// vector of instructions.
648 void addMetadata(ArrayRef<Value *> To, Instruction *From);
649
650 /// The original loop.
651 Loop *OrigLoop;
652
653 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
654 /// dynamic knowledge to simplify SCEV expressions and converts them to a
655 /// more usable form.
656 PredicatedScalarEvolution &PSE;
657
658 /// Loop Info.
659 LoopInfo *LI;
660
661 /// Dominator Tree.
662 DominatorTree *DT;
663
664 /// Alias Analysis.
665 AliasAnalysis *AA;
666
667 /// Target Library Info.
668 const TargetLibraryInfo *TLI;
669
670 /// Target Transform Info.
671 const TargetTransformInfo *TTI;
672
673 /// Assumption Cache.
674 AssumptionCache *AC;
675
676 /// Interface to emit optimization remarks.
677 OptimizationRemarkEmitter *ORE;
678
679 /// \brief LoopVersioning. It's only set up (non-null) if memchecks were
680 /// used.
681 ///
682 /// This is currently only used to add no-alias metadata based on the
683 /// memchecks. The actually versioning is performed manually.
684 std::unique_ptr<LoopVersioning> LVer;
685
686 /// The vectorization SIMD factor to use. Each vector will have this many
687 /// vector elements.
688 unsigned VF;
689
690 /// The vectorization unroll factor to use. Each scalar is vectorized to this
691 /// many different vector instructions.
692 unsigned UF;
693
694 /// The builder that we use
695 IRBuilder<> Builder;
696
697 // --- Vectorization state ---
698
699 /// The vector-loop preheader.
700 BasicBlock *LoopVectorPreHeader;
701
702 /// The scalar-loop preheader.
703 BasicBlock *LoopScalarPreHeader;
704
705 /// Middle Block between the vector and the scalar.
706 BasicBlock *LoopMiddleBlock;
707
708 /// The ExitBlock of the scalar loop.
709 BasicBlock *LoopExitBlock;
710
711 /// The vector loop body.
712 BasicBlock *LoopVectorBody;
713
714 /// The scalar loop body.
715 BasicBlock *LoopScalarBody;
716
717 /// A list of all bypass blocks. The first block is the entry of the loop.
718 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
719
720 /// The new Induction variable which was added to the new block.
721 PHINode *Induction = nullptr;
722
723 /// The induction variable of the old basic block.
724 PHINode *OldInduction = nullptr;
725
726 /// Maps values from the original loop to their corresponding values in the
727 /// vectorized loop. A key value can map to either vector values, scalar
728 /// values or both kinds of values, depending on whether the key was
729 /// vectorized and scalarized.
730 VectorizerValueMap VectorLoopValueMap;
731
732 /// Store instructions that were predicated.
733 SmallVector<Instruction *, 4> PredicatedInstructions;
734
735 /// Trip count of the original loop.
736 Value *TripCount = nullptr;
737
738 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
739 Value *VectorTripCount = nullptr;
740
741 /// The legality analysis.
742 LoopVectorizationLegality *Legal;
743
744 /// The profitablity analysis.
745 LoopVectorizationCostModel *Cost;
746
747 // Record whether runtime checks are added.
748 bool AddedSafetyChecks = false;
749
750 // Holds the end values for each induction variable. We save the end values
751 // so we can later fix-up the external users of the induction variables.
752 DenseMap<PHINode *, Value *> IVEndValues;
753};
754
755class InnerLoopUnroller : public InnerLoopVectorizer {
756public:
757 InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
758 LoopInfo *LI, DominatorTree *DT,
759 const TargetLibraryInfo *TLI,
760 const TargetTransformInfo *TTI, AssumptionCache *AC,
761 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
762 LoopVectorizationLegality *LVL,
763 LoopVectorizationCostModel *CM)
764 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
765 UnrollFactor, LVL, CM) {}
766
767private:
768 Value *getBroadcastInstrs(Value *V) override;
769 Value *getStepVector(Value *Val, int StartIdx, Value *Step,
770 Instruction::BinaryOps Opcode =
771 Instruction::BinaryOpsEnd) override;
772 Value *reverseVector(Value *Vec) override;
773};
774
775} // end namespace llvm
776
777/// \brief Look for a meaningful debug location on the instruction or it's
778/// operands.
779static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
780 if (!I)
781 return I;
782
783 DebugLoc Empty;
784 if (I->getDebugLoc() != Empty)
785 return I;
786
787 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
788 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
789 if (OpInst->getDebugLoc() != Empty)
790 return OpInst;
791 }
792
793 return I;
794}
795
796void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
797 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
798 const DILocation *DIL = Inst->getDebugLoc();
799 if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
800 !isa<DbgInfoIntrinsic>(Inst))
801 B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
802 else
803 B.SetCurrentDebugLocation(DIL);
804 } else
805 B.SetCurrentDebugLocation(DebugLoc());
806}
807
808#ifndef NDEBUG
809/// \return string containing a file name and a line # for the given loop.
810static std::string getDebugLocString(const Loop *L) {
811 std::string Result;
812 if (L) {
813 raw_string_ostream OS(Result);
814 if (const DebugLoc LoopDbgLoc = L->getStartLoc())
815 LoopDbgLoc.print(OS);
816 else
817 // Just print the module name.
818 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
819 OS.flush();
820 }
821 return Result;
822}
823#endif
824
825void InnerLoopVectorizer::addNewMetadata(Instruction *To,
826 const Instruction *Orig) {
827 // If the loop was versioned with memchecks, add the corresponding no-alias
828 // metadata.
829 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
830 LVer->annotateInstWithNoAlias(To, Orig);
831}
832
833void InnerLoopVectorizer::addMetadata(Instruction *To,
834 Instruction *From) {
835 propagateMetadata(To, From);
836 addNewMetadata(To, From);
837}
838
839void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
840 Instruction *From) {
841 for (Value *V : To) {
842 if (Instruction *I = dyn_cast<Instruction>(V))
843 addMetadata(I, From);
844 }
845}
846
847namespace llvm {
848
849/// \brief The group of interleaved loads/stores sharing the same stride and
850/// close to each other.
851///
852/// Each member in this group has an index starting from 0, and the largest
853/// index should be less than interleaved factor, which is equal to the absolute
854/// value of the access's stride.
855///
856/// E.g. An interleaved load group of factor 4:
857/// for (unsigned i = 0; i < 1024; i+=4) {
858/// a = A[i]; // Member of index 0
859/// b = A[i+1]; // Member of index 1
860/// d = A[i+3]; // Member of index 3
861/// ...
862/// }
863///
864/// An interleaved store group of factor 4:
865/// for (unsigned i = 0; i < 1024; i+=4) {
866/// ...
867/// A[i] = a; // Member of index 0
868/// A[i+1] = b; // Member of index 1
869/// A[i+2] = c; // Member of index 2
870/// A[i+3] = d; // Member of index 3
871/// }
872///
873/// Note: the interleaved load group could have gaps (missing members), but
874/// the interleaved store group doesn't allow gaps.
875class InterleaveGroup {
876public:
877 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
878 : Align(Align), InsertPos(Instr) {
879 assert(Align && "The alignment should be non-zero")(static_cast <bool> (Align && "The alignment should be non-zero"
) ? void (0) : __assert_fail ("Align && \"The alignment should be non-zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 879, __extension__ __PRETTY_FUNCTION__))
;
880
881 Factor = std::abs(Stride);
882 assert(Factor > 1 && "Invalid interleave factor")(static_cast <bool> (Factor > 1 && "Invalid interleave factor"
) ? void (0) : __assert_fail ("Factor > 1 && \"Invalid interleave factor\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 882, __extension__ __PRETTY_FUNCTION__))
;
883
884 Reverse = Stride < 0;
885 Members[0] = Instr;
886 }
887
888 bool isReverse() const { return Reverse; }
889 unsigned getFactor() const { return Factor; }
890 unsigned getAlignment() const { return Align; }
891 unsigned getNumMembers() const { return Members.size(); }
892
893 /// \brief Try to insert a new member \p Instr with index \p Index and
894 /// alignment \p NewAlign. The index is related to the leader and it could be
895 /// negative if it is the new leader.
896 ///
897 /// \returns false if the instruction doesn't belong to the group.
898 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
899 assert(NewAlign && "The new member's alignment should be non-zero")(static_cast <bool> (NewAlign && "The new member's alignment should be non-zero"
) ? void (0) : __assert_fail ("NewAlign && \"The new member's alignment should be non-zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 899, __extension__ __PRETTY_FUNCTION__))
;
900
901 int Key = Index + SmallestKey;
902
903 // Skip if there is already a member with the same index.
904 if (Members.count(Key))
905 return false;
906
907 if (Key > LargestKey) {
908 // The largest index is always less than the interleave factor.
909 if (Index >= static_cast<int>(Factor))
910 return false;
911
912 LargestKey = Key;
913 } else if (Key < SmallestKey) {
914 // The largest index is always less than the interleave factor.
915 if (LargestKey - Key >= static_cast<int>(Factor))
916 return false;
917
918 SmallestKey = Key;
919 }
920
921 // It's always safe to select the minimum alignment.
922 Align = std::min(Align, NewAlign);
923 Members[Key] = Instr;
924 return true;
925 }
926
927 /// \brief Get the member with the given index \p Index
928 ///
929 /// \returns nullptr if contains no such member.
930 Instruction *getMember(unsigned Index) const {
931 int Key = SmallestKey + Index;
932 if (!Members.count(Key))
933 return nullptr;
934
935 return Members.find(Key)->second;
936 }
937
938 /// \brief Get the index for the given member. Unlike the key in the member
939 /// map, the index starts from 0.
940 unsigned getIndex(Instruction *Instr) const {
941 for (auto I : Members)
942 if (I.second == Instr)
943 return I.first - SmallestKey;
944
945 llvm_unreachable("InterleaveGroup contains no such member")::llvm::llvm_unreachable_internal("InterleaveGroup contains no such member"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 945)
;
946 }
947
948 Instruction *getInsertPos() const { return InsertPos; }
949 void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
950
951 /// Add metadata (e.g. alias info) from the instructions in this group to \p
952 /// NewInst.
953 ///
954 /// FIXME: this function currently does not add noalias metadata a'la
955 /// addNewMedata. To do that we need to compute the intersection of the
956 /// noalias info from all members.
957 void addMetadata(Instruction *NewInst) const {
958 SmallVector<Value *, 4> VL;
959 std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
960 [](std::pair<int, Instruction *> p) { return p.second; });
961 propagateMetadata(NewInst, VL);
962 }
963
964private:
965 unsigned Factor; // Interleave Factor.
966 bool Reverse;
967 unsigned Align;
968 DenseMap<int, Instruction *> Members;
969 int SmallestKey = 0;
970 int LargestKey = 0;
971
972 // To avoid breaking dependences, vectorized instructions of an interleave
973 // group should be inserted at either the first load or the last store in
974 // program order.
975 //
976 // E.g. %even = load i32 // Insert Position
977 // %add = add i32 %even // Use of %even
978 // %odd = load i32
979 //
980 // store i32 %even
981 // %odd = add i32 // Def of %odd
982 // store i32 %odd // Insert Position
983 Instruction *InsertPos;
984};
985} // end namespace llvm
986
987namespace {
988
989/// \brief Drive the analysis of interleaved memory accesses in the loop.
990///
991/// Use this class to analyze interleaved accesses only when we can vectorize
992/// a loop. Otherwise it's meaningless to do analysis as the vectorization
993/// on interleaved accesses is unsafe.
994///
995/// The analysis collects interleave groups and records the relationships
996/// between the member and the group in a map.
997class InterleavedAccessInfo {
998public:
999 InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
1000 DominatorTree *DT, LoopInfo *LI)
1001 : PSE(PSE), TheLoop(L), DT(DT), LI(LI) {}
1002
1003 ~InterleavedAccessInfo() {
1004 SmallSet<InterleaveGroup *, 4> DelSet;
1005 // Avoid releasing a pointer twice.
1006 for (auto &I : InterleaveGroupMap)
1007 DelSet.insert(I.second);
1008 for (auto *Ptr : DelSet)
1009 delete Ptr;
1010 }
1011
1012 /// \brief Analyze the interleaved accesses and collect them in interleave
1013 /// groups. Substitute symbolic strides using \p Strides.
1014 void analyzeInterleaving(const ValueToValueMap &Strides);
1015
1016 /// \brief Check if \p Instr belongs to any interleave group.
1017 bool isInterleaved(Instruction *Instr) const {
1018 return InterleaveGroupMap.count(Instr);
1019 }
1020
1021 /// \brief Get the interleave group that \p Instr belongs to.
1022 ///
1023 /// \returns nullptr if doesn't have such group.
1024 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
1025 if (InterleaveGroupMap.count(Instr))
1026 return InterleaveGroupMap.find(Instr)->second;
1027 return nullptr;
1028 }
1029
1030 /// \brief Returns true if an interleaved group that may access memory
1031 /// out-of-bounds requires a scalar epilogue iteration for correctness.
1032 bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
1033
1034 /// \brief Initialize the LoopAccessInfo used for dependence checking.
1035 void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
1036
1037private:
1038 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
1039 /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
1040 /// The interleaved access analysis can also add new predicates (for example
1041 /// by versioning strides of pointers).
1042 PredicatedScalarEvolution &PSE;
1043
1044 Loop *TheLoop;
1045 DominatorTree *DT;
1046 LoopInfo *LI;
1047 const LoopAccessInfo *LAI = nullptr;
1048
1049 /// True if the loop may contain non-reversed interleaved groups with
1050 /// out-of-bounds accesses. We ensure we don't speculatively access memory
1051 /// out-of-bounds by executing at least one scalar epilogue iteration.
1052 bool RequiresScalarEpilogue = false;
1053
1054 /// Holds the relationships between the members and the interleave group.
1055 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
1056
1057 /// Holds dependences among the memory accesses in the loop. It maps a source
1058 /// access to a set of dependent sink accesses.
1059 DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
1060
1061 /// \brief The descriptor for a strided memory access.
1062 struct StrideDescriptor {
1063 StrideDescriptor() = default;
1064 StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
1065 unsigned Align)
1066 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1067
1068 // The access's stride. It is negative for a reverse access.
1069 int64_t Stride = 0;
1070
1071 // The scalar expression of this access.
1072 const SCEV *Scev = nullptr;
1073
1074 // The size of the memory object.
1075 uint64_t Size = 0;
1076
1077 // The alignment of this access.
1078 unsigned Align = 0;
1079 };
1080
1081 /// \brief A type for holding instructions and their stride descriptors.
1082 using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
1083
1084 /// \brief Create a new interleave group with the given instruction \p Instr,
1085 /// stride \p Stride and alignment \p Align.
1086 ///
1087 /// \returns the newly created interleave group.
1088 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
1089 unsigned Align) {
1090 assert(!InterleaveGroupMap.count(Instr) &&(static_cast <bool> (!InterleaveGroupMap.count(Instr) &&
"Already in an interleaved access group") ? void (0) : __assert_fail
("!InterleaveGroupMap.count(Instr) && \"Already in an interleaved access group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1091, __extension__ __PRETTY_FUNCTION__))
1091 "Already in an interleaved access group")(static_cast <bool> (!InterleaveGroupMap.count(Instr) &&
"Already in an interleaved access group") ? void (0) : __assert_fail
("!InterleaveGroupMap.count(Instr) && \"Already in an interleaved access group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1091, __extension__ __PRETTY_FUNCTION__))
;
1092 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1093 return InterleaveGroupMap[Instr];
1094 }
1095
1096 /// \brief Release the group and remove all the relationships.
1097 void releaseGroup(InterleaveGroup *Group) {
1098 for (unsigned i = 0; i < Group->getFactor(); i++)
1099 if (Instruction *Member = Group->getMember(i))
1100 InterleaveGroupMap.erase(Member);
1101
1102 delete Group;
1103 }
1104
1105 /// \brief Collect all the accesses with a constant stride in program order.
1106 void collectConstStrideAccesses(
1107 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1108 const ValueToValueMap &Strides);
1109
1110 /// \brief Returns true if \p Stride is allowed in an interleaved group.
1111 static bool isStrided(int Stride) {
1112 unsigned Factor = std::abs(Stride);
1113 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1114 }
1115
1116 /// \brief Returns true if \p BB is a predicated block.
1117 bool isPredicated(BasicBlock *BB) const {
1118 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1119 }
1120
1121 /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
1122 bool areDependencesValid() const {
1123 return LAI && LAI->getDepChecker().getDependences();
1124 }
1125
1126 /// \brief Returns true if memory accesses \p A and \p B can be reordered, if
1127 /// necessary, when constructing interleaved groups.
1128 ///
1129 /// \p A must precede \p B in program order. We return false if reordering is
1130 /// not necessary or is prevented because \p A and \p B may be dependent.
1131 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1132 StrideEntry *B) const {
1133 // Code motion for interleaved accesses can potentially hoist strided loads
1134 // and sink strided stores. The code below checks the legality of the
1135 // following two conditions:
1136 //
1137 // 1. Potentially moving a strided load (B) before any store (A) that
1138 // precedes B, or
1139 //
1140 // 2. Potentially moving a strided store (A) after any load or store (B)
1141 // that A precedes.
1142 //
1143 // It's legal to reorder A and B if we know there isn't a dependence from A
1144 // to B. Note that this determination is conservative since some
1145 // dependences could potentially be reordered safely.
1146
1147 // A is potentially the source of a dependence.
1148 auto *Src = A->first;
1149 auto SrcDes = A->second;
1150
1151 // B is potentially the sink of a dependence.
1152 auto *Sink = B->first;
1153 auto SinkDes = B->second;
1154
1155 // Code motion for interleaved accesses can't violate WAR dependences.
1156 // Thus, reordering is legal if the source isn't a write.
1157 if (!Src->mayWriteToMemory())
1158 return true;
1159
1160 // At least one of the accesses must be strided.
1161 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1162 return true;
1163
1164 // If dependence information is not available from LoopAccessInfo,
1165 // conservatively assume the instructions can't be reordered.
1166 if (!areDependencesValid())
1167 return false;
1168
1169 // If we know there is a dependence from source to sink, assume the
1170 // instructions can't be reordered. Otherwise, reordering is legal.
1171 return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1172 }
1173
1174 /// \brief Collect the dependences from LoopAccessInfo.
1175 ///
1176 /// We process the dependences once during the interleaved access analysis to
1177 /// enable constant-time dependence queries.
1178 void collectDependences() {
1179 if (!areDependencesValid())
1180 return;
1181 auto *Deps = LAI->getDepChecker().getDependences();
1182 for (auto Dep : *Deps)
1183 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1184 }
1185};
1186
1187/// Utility class for getting and setting loop vectorizer hints in the form
1188/// of loop metadata.
1189/// This class keeps a number of loop annotations locally (as member variables)
1190/// and can, upon request, write them back as metadata on the loop. It will
1191/// initially scan the loop for existing metadata, and will update the local
1192/// values based on information in the loop.
1193/// We cannot write all values to metadata, as the mere presence of some info,
1194/// for example 'force', means a decision has been made. So, we need to be
1195/// careful NOT to add them if the user hasn't specifically asked so.
1196class LoopVectorizeHints {
1197 enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE, HK_ISVECTORIZED };
1198
1199 /// Hint - associates name and validation with the hint value.
1200 struct Hint {
1201 const char *Name;
1202 unsigned Value; // This may have to change for non-numeric values.
1203 HintKind Kind;
1204
1205 Hint(const char *Name, unsigned Value, HintKind Kind)
1206 : Name(Name), Value(Value), Kind(Kind) {}
1207
1208 bool validate(unsigned Val) {
1209 switch (Kind) {
1210 case HK_WIDTH:
1211 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1212 case HK_UNROLL:
1213 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1214 case HK_FORCE:
1215 return (Val <= 1);
1216 case HK_ISVECTORIZED:
1217 return (Val==0 || Val==1);
1218 }
1219 return false;
1220 }
1221 };
1222
1223 /// Vectorization width.
1224 Hint Width;
1225
1226 /// Vectorization interleave factor.
1227 Hint Interleave;
1228
1229 /// Vectorization forced
1230 Hint Force;
1231
1232 /// Already Vectorized
1233 Hint IsVectorized;
1234
1235 /// Return the loop metadata prefix.
1236 static StringRef Prefix() { return "llvm.loop."; }
1237
1238 /// True if there is any unsafe math in the loop.
1239 bool PotentiallyUnsafe = false;
1240
1241public:
1242 enum ForceKind {
1243 FK_Undefined = -1, ///< Not selected.
1244 FK_Disabled = 0, ///< Forcing disabled.
1245 FK_Enabled = 1, ///< Forcing enabled.
1246 };
1247
1248 LoopVectorizeHints(const Loop *L, bool DisableInterleaving,
1249 OptimizationRemarkEmitter &ORE)
1250 : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1251 HK_WIDTH),
1252 Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1253 Force("vectorize.enable", FK_Undefined, HK_FORCE),
1254 IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) {
1255 // Populate values with existing loop metadata.
1256 getHintsFromMetadata();
1257
1258 // force-vector-interleave overrides DisableInterleaving.
1259 if (VectorizerParams::isInterleaveForced())
1260 Interleave.Value = VectorizerParams::VectorizationInterleave;
1261
1262 if (IsVectorized.Value != 1)
1263 // If the vectorization width and interleaving count are both 1 then
1264 // consider the loop to have been already vectorized because there's
1265 // nothing more that we can do.
1266 IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1;
1267 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { if (DisableInterleaving && Interleave
.Value == 1) dbgs() << "LV: Interleaving disabled by the pass manager\n"
; } } while (false)
1268 << "LV: Interleaving disabled by the pass manager\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { if (DisableInterleaving && Interleave
.Value == 1) dbgs() << "LV: Interleaving disabled by the pass manager\n"
; } } while (false)
;
1269 }
1270
1271 /// Mark the loop L as already vectorized by setting the width to 1.
1272 void setAlreadyVectorized() {
1273 IsVectorized.Value = 1;
1274 Hint Hints[] = {IsVectorized};
1275 writeHintsToMetadata(Hints);
1276 }
1277
1278 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1279 if (getForce() == LoopVectorizeHints::FK_Disabled) {
1280 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"
; } } while (false)
;
1281 emitRemarkWithHints();
1282 return false;
1283 }
1284
1285 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1286 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"
; } } while (false)
;
1287 emitRemarkWithHints();
1288 return false;
1289 }
1290
1291 if (getIsVectorized() == 1) {
1292 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"
; } } while (false)
;
1293 // FIXME: Add interleave.disable metadata. This will allow
1294 // vectorize.disable to be used without disabling the pass and errors
1295 // to differentiate between disabled vectorization and a width of 1.
1296 ORE.emit([&]() {
1297 return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
1298 "AllDisabled", L->getStartLoc(),
1299 L->getHeader())
1300 << "loop not vectorized: vectorization and interleaving are "
1301 "explicitly disabled, or the loop has already been "
1302 "vectorized";
1303 });
1304 return false;
1305 }
1306
1307 return true;
1308 }
1309
1310 /// Dumps all the hint information.
1311 void emitRemarkWithHints() const {
1312 using namespace ore;
1313
1314 ORE.emit([&]() {
1315 if (Force.Value == LoopVectorizeHints::FK_Disabled)
1316 return OptimizationRemarkMissed(LV_NAME"loop-vectorize", "MissedExplicitlyDisabled",
1317 TheLoop->getStartLoc(),
1318 TheLoop->getHeader())
1319 << "loop not vectorized: vectorization is explicitly disabled";
1320 else {
1321 OptimizationRemarkMissed R(LV_NAME"loop-vectorize", "MissedDetails",
1322 TheLoop->getStartLoc(),
1323 TheLoop->getHeader());
1324 R << "loop not vectorized";
1325 if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1326 R << " (Force=" << NV("Force", true);
1327 if (Width.Value != 0)
1328 R << ", Vector Width=" << NV("VectorWidth", Width.Value);
1329 if (Interleave.Value != 0)
1330 R << ", Interleave Count="
1331 << NV("InterleaveCount", Interleave.Value);
1332 R << ")";
1333 }
1334 return R;
1335 }
1336 });
1337 }
1338
1339 unsigned getWidth() const { return Width.Value; }
1340 unsigned getInterleave() const { return Interleave.Value; }
1341 unsigned getIsVectorized() const { return IsVectorized.Value; }
1342 enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1343
1344 /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1345 /// pass name to force the frontend to print the diagnostic.
1346 const char *vectorizeAnalysisPassName() const {
1347 if (getWidth() == 1)
1348 return LV_NAME"loop-vectorize";
1349 if (getForce() == LoopVectorizeHints::FK_Disabled)
1350 return LV_NAME"loop-vectorize";
1351 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1352 return LV_NAME"loop-vectorize";
1353 return OptimizationRemarkAnalysis::AlwaysPrint;
1354 }
1355
1356 bool allowReordering() const {
1357 // When enabling loop hints are provided we allow the vectorizer to change
1358 // the order of operations that is given by the scalar loop. This is not
1359 // enabled by default because can be unsafe or inefficient. For example,
1360 // reordering floating-point operations will change the way round-off
1361 // error accumulates in the loop.
1362 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1363 }
1364
1365 bool isPotentiallyUnsafe() const {
1366 // Avoid FP vectorization if the target is unsure about proper support.
1367 // This may be related to the SIMD unit in the target not handling
1368 // IEEE 754 FP ops properly, or bad single-to-double promotions.
1369 // Otherwise, a sequence of vectorized loops, even without reduction,
1370 // could lead to different end results on the destination vectors.
1371 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1372 }
1373
1374 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1375
1376private:
1377 /// Find hints specified in the loop metadata and update local values.
1378 void getHintsFromMetadata() {
1379 MDNode *LoopID = TheLoop->getLoopID();
1380 if (!LoopID)
1381 return;
1382
1383 // First operand should refer to the loop id itself.
1384 assert(LoopID->getNumOperands() > 0 && "requires at least one operand")(static_cast <bool> (LoopID->getNumOperands() > 0
&& "requires at least one operand") ? void (0) : __assert_fail
("LoopID->getNumOperands() > 0 && \"requires at least one operand\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1384, __extension__ __PRETTY_FUNCTION__))
;
1385 assert(LoopID->getOperand(0) == LoopID && "invalid loop id")(static_cast <bool> (LoopID->getOperand(0) == LoopID
&& "invalid loop id") ? void (0) : __assert_fail ("LoopID->getOperand(0) == LoopID && \"invalid loop id\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1385, __extension__ __PRETTY_FUNCTION__))
;
1386
1387 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1388 const MDString *S = nullptr;
1389 SmallVector<Metadata *, 4> Args;
1390
1391 // The expected hint is either a MDString or a MDNode with the first
1392 // operand a MDString.
1393 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1394 if (!MD || MD->getNumOperands() == 0)
1395 continue;
1396 S = dyn_cast<MDString>(MD->getOperand(0));
1397 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1398 Args.push_back(MD->getOperand(i));
1399 } else {
1400 S = dyn_cast<MDString>(LoopID->getOperand(i));
1401 assert(Args.size() == 0 && "too many arguments for MDString")(static_cast <bool> (Args.size() == 0 && "too many arguments for MDString"
) ? void (0) : __assert_fail ("Args.size() == 0 && \"too many arguments for MDString\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1401, __extension__ __PRETTY_FUNCTION__))
;
1402 }
1403
1404 if (!S)
1405 continue;
1406
1407 // Check if the hint starts with the loop metadata prefix.
1408 StringRef Name = S->getString();
1409 if (Args.size() == 1)
1410 setHint(Name, Args[0]);
1411 }
1412 }
1413
1414 /// Checks string hint with one operand and set value if valid.
1415 void setHint(StringRef Name, Metadata *Arg) {
1416 if (!Name.startswith(Prefix()))
1417 return;
1418 Name = Name.substr(Prefix().size(), StringRef::npos);
1419
1420 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1421 if (!C)
1422 return;
1423 unsigned Val = C->getZExtValue();
1424
1425 Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized};
1426 for (auto H : Hints) {
1427 if (Name == H->Name) {
1428 if (H->validate(Val))
1429 H->Value = Val;
1430 else
1431 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: ignoring invalid hint '"
<< Name << "'\n"; } } while (false)
;
1432 break;
1433 }
1434 }
1435 }
1436
1437 /// Create a new hint from name / value pair.
1438 MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1439 LLVMContext &Context = TheLoop->getHeader()->getContext();
1440 Metadata *MDs[] = {MDString::get(Context, Name),
1441 ConstantAsMetadata::get(
1442 ConstantInt::get(Type::getInt32Ty(Context), V))};
1443 return MDNode::get(Context, MDs);
1444 }
1445
1446 /// Matches metadata with hint name.
1447 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1448 MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1449 if (!Name)
1450 return false;
1451
1452 for (auto H : HintTypes)
1453 if (Name->getString().endswith(H.Name))
1454 return true;
1455 return false;
1456 }
1457
1458 /// Sets current hints into loop metadata, keeping other values intact.
1459 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1460 if (HintTypes.empty())
1461 return;
1462
1463 // Reserve the first element to LoopID (see below).
1464 SmallVector<Metadata *, 4> MDs(1);
1465 // If the loop already has metadata, then ignore the existing operands.
1466 MDNode *LoopID = TheLoop->getLoopID();
1467 if (LoopID) {
1468 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1469 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1470 // If node in update list, ignore old value.
1471 if (!matchesHintMetadataName(Node, HintTypes))
1472 MDs.push_back(Node);
1473 }
1474 }
1475
1476 // Now, add the missing hints.
1477 for (auto H : HintTypes)
1478 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1479
1480 // Replace current metadata node with new one.
1481 LLVMContext &Context = TheLoop->getHeader()->getContext();
1482 MDNode *NewLoopID = MDNode::get(Context, MDs);
1483 // Set operand 0 to refer to the loop id itself.
1484 NewLoopID->replaceOperandWith(0, NewLoopID);
1485
1486 TheLoop->setLoopID(NewLoopID);
1487 }
1488
1489 /// The loop these hints belong to.
1490 const Loop *TheLoop;
1491
1492 /// Interface to emit optimization remarks.
1493 OptimizationRemarkEmitter &ORE;
1494};
1495
1496} // end anonymous namespace
1497
1498static void emitMissedWarning(Function *F, Loop *L,
1499 const LoopVectorizeHints &LH,
1500 OptimizationRemarkEmitter *ORE) {
1501 LH.emitRemarkWithHints();
1502
1503 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1504 if (LH.getWidth() != 1)
1505 ORE->emit(DiagnosticInfoOptimizationFailure(
1506 DEBUG_TYPE"loop-vectorize", "FailedRequestedVectorization",
1507 L->getStartLoc(), L->getHeader())
1508 << "loop not vectorized: "
1509 << "failed explicitly specified loop vectorization");
1510 else if (LH.getInterleave() != 1)
1511 ORE->emit(DiagnosticInfoOptimizationFailure(
1512 DEBUG_TYPE"loop-vectorize", "FailedRequestedInterleaving", L->getStartLoc(),
1513 L->getHeader())
1514 << "loop not interleaved: "
1515 << "failed explicitly specified loop interleaving");
1516 }
1517}
1518
1519namespace llvm {
1520
1521/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1522/// to what vectorization factor.
1523/// This class does not look at the profitability of vectorization, only the
1524/// legality. This class has two main kinds of checks:
1525/// * Memory checks - The code in canVectorizeMemory checks if vectorization
1526/// will change the order of memory accesses in a way that will change the
1527/// correctness of the program.
1528/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1529/// checks for a number of different conditions, such as the availability of a
1530/// single induction variable, that all types are supported and vectorize-able,
1531/// etc. This code reflects the capabilities of InnerLoopVectorizer.
1532/// This class is also used by InnerLoopVectorizer for identifying
1533/// induction variable and the different reduction variables.
1534class LoopVectorizationLegality {
1535public:
1536 LoopVectorizationLegality(
1537 Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
1538 TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
1539 const TargetTransformInfo *TTI,
1540 std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1541 OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R,
1542 LoopVectorizeHints *H, DemandedBits *DB, AssumptionCache *AC)
1543 : TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT), GetLAA(GetLAA),
1544 ORE(ORE), InterleaveInfo(PSE, L, DT, LI), Requirements(R), Hints(H),
1545 DB(DB), AC(AC) {}
1546
1547 /// ReductionList contains the reduction descriptors for all
1548 /// of the reductions that were found in the loop.
1549 using ReductionList = DenseMap<PHINode *, RecurrenceDescriptor>;
1550
1551 /// InductionList saves induction variables and maps them to the
1552 /// induction descriptor.
1553 using InductionList = MapVector<PHINode *, InductionDescriptor>;
1554
1555 /// RecurrenceSet contains the phi nodes that are recurrences other than
1556 /// inductions and reductions.
1557 using RecurrenceSet = SmallPtrSet<const PHINode *, 8>;
1558
1559 /// Returns true if it is legal to vectorize this loop.
1560 /// This does not mean that it is profitable to vectorize this
1561 /// loop, only that it is legal to do so.
1562 bool canVectorize();
1563
1564 /// Returns the primary induction variable.
1565 PHINode *getPrimaryInduction() { return PrimaryInduction; }
1566
1567 /// Returns the reduction variables found in the loop.
1568 ReductionList *getReductionVars() { return &Reductions; }
1569
1570 /// Returns the induction variables found in the loop.
1571 InductionList *getInductionVars() { return &Inductions; }
1572
1573 /// Return the first-order recurrences found in the loop.
1574 RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1575
1576 /// Return the set of instructions to sink to handle first-order recurrences.
1577 DenseMap<Instruction *, Instruction *> &getSinkAfter() { return SinkAfter; }
1578
1579 /// Returns the widest induction type.
1580 Type *getWidestInductionType() { return WidestIndTy; }
1581
1582 /// Returns True if V is a Phi node of an induction variable in this loop.
1583 bool isInductionPhi(const Value *V);
1584
1585 /// Returns True if V is a cast that is part of an induction def-use chain,
1586 /// and had been proven to be redundant under a runtime guard (in other
1587 /// words, the cast has the same SCEV expression as the induction phi).
1588 bool isCastedInductionVariable(const Value *V);
1589
1590 /// Returns True if V can be considered as an induction variable in this
1591 /// loop. V can be the induction phi, or some redundant cast in the def-use
1592 /// chain of the inducion phi.
1593 bool isInductionVariable(const Value *V);
1594
1595 /// Returns True if PN is a reduction variable in this loop.
1596 bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1597
1598 /// Returns True if Phi is a first-order recurrence in this loop.
1599 bool isFirstOrderRecurrence(const PHINode *Phi);
1600
1601 /// Return true if the block BB needs to be predicated in order for the loop
1602 /// to be vectorized.
1603 bool blockNeedsPredication(BasicBlock *BB);
1604
1605 /// Check if this pointer is consecutive when vectorizing. This happens
1606 /// when the last index of the GEP is the induction variable, or that the
1607 /// pointer itself is an induction variable.
1608 /// This check allows us to vectorize A[idx] into a wide load/store.
1609 /// Returns:
1610 /// 0 - Stride is unknown or non-consecutive.
1611 /// 1 - Address is consecutive.
1612 /// -1 - Address is consecutive, and decreasing.
1613 /// NOTE: This method must only be used before modifying the original scalar
1614 /// loop. Do not use after invoking 'createVectorizedLoopSkeleton' (PR34965).
1615 int isConsecutivePtr(Value *Ptr);
1616
1617 /// Returns true if the value V is uniform within the loop.
1618 bool isUniform(Value *V);
1619
1620 /// Returns the information that we collected about runtime memory check.
1621 const RuntimePointerChecking *getRuntimePointerChecking() const {
1622 return LAI->getRuntimePointerChecking();
1623 }
1624
1625 const LoopAccessInfo *getLAI() const { return LAI; }
1626
1627 /// \brief Check if \p Instr belongs to any interleaved access group.
1628 bool isAccessInterleaved(Instruction *Instr) {
1629 return InterleaveInfo.isInterleaved(Instr);
1630 }
1631
1632 /// \brief Get the interleaved access group that \p Instr belongs to.
1633 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1634 return InterleaveInfo.getInterleaveGroup(Instr);
1635 }
1636
1637 /// \brief Returns true if an interleaved group requires a scalar iteration
1638 /// to handle accesses with gaps.
1639 bool requiresScalarEpilogue() const {
1640 return InterleaveInfo.requiresScalarEpilogue();
1641 }
1642
1643 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1644
1645 uint64_t getMaxSafeRegisterWidth() const {
1646 return LAI->getDepChecker().getMaxSafeRegisterWidth();
1647 }
1648
1649 bool hasStride(Value *V) { return LAI->hasStride(V); }
1650
1651 /// Returns true if vector representation of the instruction \p I
1652 /// requires mask.
1653 bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1654
1655 unsigned getNumStores() const { return LAI->getNumStores(); }
1656 unsigned getNumLoads() const { return LAI->getNumLoads(); }
1657
1658 // Returns true if the NoNaN attribute is set on the function.
1659 bool hasFunNoNaNAttr() const { return HasFunNoNaNAttr; }
1660
1661private:
1662 /// Check if a single basic block loop is vectorizable.
1663 /// At this point we know that this is a loop with a constant trip count
1664 /// and we only need to check individual instructions.
1665 bool canVectorizeInstrs();
1666
1667 /// When we vectorize loops we may change the order in which
1668 /// we read and write from memory. This method checks if it is
1669 /// legal to vectorize the code, considering only memory constrains.
1670 /// Returns true if the loop is vectorizable
1671 bool canVectorizeMemory();
1672
1673 /// Return true if we can vectorize this loop using the IF-conversion
1674 /// transformation.
1675 bool canVectorizeWithIfConvert();
1676
1677 /// Return true if all of the instructions in the block can be speculatively
1678 /// executed. \p SafePtrs is a list of addresses that are known to be legal
1679 /// and we know that we can read from them without segfault.
1680 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1681
1682 /// Updates the vectorization state by adding \p Phi to the inductions list.
1683 /// This can set \p Phi as the main induction of the loop if \p Phi is a
1684 /// better choice for the main induction than the existing one.
1685 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1686 SmallPtrSetImpl<Value *> &AllowedExit);
1687
1688 /// Create an analysis remark that explains why vectorization failed
1689 ///
1690 /// \p RemarkName is the identifier for the remark. If \p I is passed it is
1691 /// an instruction that prevents vectorization. Otherwise the loop is used
1692 /// for the location of the remark. \return the remark object that can be
1693 /// streamed to.
1694 OptimizationRemarkAnalysis
1695 createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const {
1696 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1697 RemarkName, TheLoop, I);
1698 }
1699
1700 /// \brief If an access has a symbolic strides, this maps the pointer value to
1701 /// the stride symbol.
1702 const ValueToValueMap *getSymbolicStrides() {
1703 // FIXME: Currently, the set of symbolic strides is sometimes queried before
1704 // it's collected. This happens from canVectorizeWithIfConvert, when the
1705 // pointer is checked to reference consecutive elements suitable for a
1706 // masked access.
1707 return LAI ? &LAI->getSymbolicStrides() : nullptr;
1708 }
1709
1710 /// The loop that we evaluate.
1711 Loop *TheLoop;
1712
1713 /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1714 /// Applies dynamic knowledge to simplify SCEV expressions in the context
1715 /// of existing SCEV assumptions. The analysis will also add a minimal set
1716 /// of new predicates if this is required to enable vectorization and
1717 /// unrolling.
1718 PredicatedScalarEvolution &PSE;
1719
1720 /// Target Library Info.
1721 TargetLibraryInfo *TLI;
1722
1723 /// Target Transform Info
1724 const TargetTransformInfo *TTI;
1725
1726 /// Dominator Tree.
1727 DominatorTree *DT;
1728
1729 // LoopAccess analysis.
1730 std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1731
1732 // And the loop-accesses info corresponding to this loop. This pointer is
1733 // null until canVectorizeMemory sets it up.
1734 const LoopAccessInfo *LAI = nullptr;
1735
1736 /// Interface to emit optimization remarks.
1737 OptimizationRemarkEmitter *ORE;
1738
1739 /// The interleave access information contains groups of interleaved accesses
1740 /// with the same stride and close to each other.
1741 InterleavedAccessInfo InterleaveInfo;
1742
1743 // --- vectorization state --- //
1744
1745 /// Holds the primary induction variable. This is the counter of the
1746 /// loop.
1747 PHINode *PrimaryInduction = nullptr;
1748
1749 /// Holds the reduction variables.
1750 ReductionList Reductions;
1751
1752 /// Holds all of the induction variables that we found in the loop.
1753 /// Notice that inductions don't need to start at zero and that induction
1754 /// variables can be pointers.
1755 InductionList Inductions;
1756
1757 /// Holds all the casts that participate in the update chain of the induction
1758 /// variables, and that have been proven to be redundant (possibly under a
1759 /// runtime guard). These casts can be ignored when creating the vectorized
1760 /// loop body.
1761 SmallPtrSet<Instruction *, 4> InductionCastsToIgnore;
1762
1763 /// Holds the phi nodes that are first-order recurrences.
1764 RecurrenceSet FirstOrderRecurrences;
1765
1766 /// Holds instructions that need to sink past other instructions to handle
1767 /// first-order recurrences.
1768 DenseMap<Instruction *, Instruction *> SinkAfter;
1769
1770 /// Holds the widest induction type encountered.
1771 Type *WidestIndTy = nullptr;
1772
1773 /// Allowed outside users. This holds the induction and reduction
1774 /// vars which can be accessed from outside the loop.
1775 SmallPtrSet<Value *, 4> AllowedExit;
1776
1777 /// Can we assume the absence of NaNs.
1778 bool HasFunNoNaNAttr = false;
1779
1780 /// Vectorization requirements that will go through late-evaluation.
1781 LoopVectorizationRequirements *Requirements;
1782
1783 /// Used to emit an analysis of any legality issues.
1784 LoopVectorizeHints *Hints;
1785
1786 /// The demanded bits analsyis is used to compute the minimum type size in
1787 /// which a reduction can be computed.
1788 DemandedBits *DB;
1789
1790 /// The assumption cache analysis is used to compute the minimum type size in
1791 /// which a reduction can be computed.
1792 AssumptionCache *AC;
1793
1794 /// While vectorizing these instructions we have to generate a
1795 /// call to the appropriate masked intrinsic
1796 SmallPtrSet<const Instruction *, 8> MaskedOp;
1797};
1798
1799/// LoopVectorizationCostModel - estimates the expected speedups due to
1800/// vectorization.
1801/// In many cases vectorization is not profitable. This can happen because of
1802/// a number of reasons. In this class we mainly attempt to predict the
1803/// expected speedup/slowdowns due to the supported instruction set. We use the
1804/// TargetTransformInfo to query the different backends for the cost of
1805/// different operations.
1806class LoopVectorizationCostModel {
1807public:
1808 LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1809 LoopInfo *LI, LoopVectorizationLegality *Legal,
1810 const TargetTransformInfo &TTI,
1811 const TargetLibraryInfo *TLI, DemandedBits *DB,
1812 AssumptionCache *AC,
1813 OptimizationRemarkEmitter *ORE, const Function *F,
1814 const LoopVectorizeHints *Hints)
1815 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1816 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1817
1818 /// \return An upper bound for the vectorization factor, or None if
1819 /// vectorization should be avoided up front.
1820 Optional<unsigned> computeMaxVF(bool OptForSize);
1821
1822 /// \return The most profitable vectorization factor and the cost of that VF.
1823 /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1824 /// then this vectorization factor will be selected if vectorization is
1825 /// possible.
1826 VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1827
1828 /// Setup cost-based decisions for user vectorization factor.
1829 void selectUserVectorizationFactor(unsigned UserVF) {
1830 collectUniformsAndScalars(UserVF);
1831 collectInstsToScalarize(UserVF);
1832 }
1833
1834 /// \return The size (in bits) of the smallest and widest types in the code
1835 /// that needs to be vectorized. We ignore values that remain scalar such as
1836 /// 64 bit loop indices.
1837 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1838
1839 /// \return The desired interleave count.
1840 /// If interleave count has been specified by metadata it will be returned.
1841 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1842 /// are the selected vectorization factor and the cost of the selected VF.
1843 unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1844 unsigned LoopCost);
1845
1846 /// Memory access instruction may be vectorized in more than one way.
1847 /// Form of instruction after vectorization depends on cost.
1848 /// This function takes cost-based decisions for Load/Store instructions
1849 /// and collects them in a map. This decisions map is used for building
1850 /// the lists of loop-uniform and loop-scalar instructions.
1851 /// The calculated cost is saved with widening decision in order to
1852 /// avoid redundant calculations.
1853 void setCostBasedWideningDecision(unsigned VF);
1854
1855 /// \brief A struct that represents some properties of the register usage
1856 /// of a loop.
1857 struct RegisterUsage {
1858 /// Holds the number of loop invariant values that are used in the loop.
1859 unsigned LoopInvariantRegs;
1860
1861 /// Holds the maximum number of concurrent live intervals in the loop.
1862 unsigned MaxLocalUsers;
1863
1864 /// Holds the number of instructions in the loop.
1865 unsigned NumInstructions;
1866 };
1867
1868 /// \return Returns information about the register usages of the loop for the
1869 /// given vectorization factors.
1870 SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1871
1872 /// Collect values we want to ignore in the cost model.
1873 void collectValuesToIgnore();
1874
1875 /// \returns The smallest bitwidth each instruction can be represented with.
1876 /// The vector equivalents of these instructions should be truncated to this
1877 /// type.
1878 const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1879 return MinBWs;
1880 }
1881
1882 /// \returns True if it is more profitable to scalarize instruction \p I for
1883 /// vectorization factor \p VF.
1884 bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1885 assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.")(static_cast <bool> (VF > 1 && "Profitable to scalarize relevant only for VF > 1."
) ? void (0) : __assert_fail ("VF > 1 && \"Profitable to scalarize relevant only for VF > 1.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1885, __extension__ __PRETTY_FUNCTION__))
;
1886 auto Scalars = InstsToScalarize.find(VF);
1887 assert(Scalars != InstsToScalarize.end() &&(static_cast <bool> (Scalars != InstsToScalarize.end() &&
"VF not yet analyzed for scalarization profitability") ? void
(0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1888, __extension__ __PRETTY_FUNCTION__))
1888 "VF not yet analyzed for scalarization profitability")(static_cast <bool> (Scalars != InstsToScalarize.end() &&
"VF not yet analyzed for scalarization profitability") ? void
(0) : __assert_fail ("Scalars != InstsToScalarize.end() && \"VF not yet analyzed for scalarization profitability\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1888, __extension__ __PRETTY_FUNCTION__))
;
1889 return Scalars->second.count(I);
1890 }
1891
1892 /// Returns true if \p I is known to be uniform after vectorization.
1893 bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1894 if (VF == 1)
1895 return true;
1896 assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity")(static_cast <bool> (Uniforms.count(VF) && "VF not yet analyzed for uniformity"
) ? void (0) : __assert_fail ("Uniforms.count(VF) && \"VF not yet analyzed for uniformity\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1896, __extension__ __PRETTY_FUNCTION__))
;
1897 auto UniformsPerVF = Uniforms.find(VF);
1898 return UniformsPerVF->second.count(I);
1899 }
1900
1901 /// Returns true if \p I is known to be scalar after vectorization.
1902 bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1903 if (VF == 1)
1904 return true;
1905 assert(Scalars.count(VF) && "Scalar values are not calculated for VF")(static_cast <bool> (Scalars.count(VF) && "Scalar values are not calculated for VF"
) ? void (0) : __assert_fail ("Scalars.count(VF) && \"Scalar values are not calculated for VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1905, __extension__ __PRETTY_FUNCTION__))
;
1906 auto ScalarsPerVF = Scalars.find(VF);
1907 return ScalarsPerVF->second.count(I);
1908 }
1909
1910 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1911 /// for vectorization factor \p VF.
1912 bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1913 return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1914 !isScalarAfterVectorization(I, VF);
1915 }
1916
1917 /// Decision that was taken during cost calculation for memory instruction.
1918 enum InstWidening {
1919 CM_Unknown,
1920 CM_Widen, // For consecutive accesses with stride +1.
1921 CM_Widen_Reverse, // For consecutive accesses with stride -1.
1922 CM_Interleave,
1923 CM_GatherScatter,
1924 CM_Scalarize
1925 };
1926
1927 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1928 /// instruction \p I and vector width \p VF.
1929 void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
1930 unsigned Cost) {
1931 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1931, __extension__ __PRETTY_FUNCTION__))
;
1932 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1933 }
1934
1935 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1936 /// interleaving group \p Grp and vector width \p VF.
1937 void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1938 InstWidening W, unsigned Cost) {
1939 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1939, __extension__ __PRETTY_FUNCTION__))
;
1940 /// Broadcast this decicion to all instructions inside the group.
1941 /// But the cost will be assigned to one instruction only.
1942 for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1943 if (auto *I = Grp->getMember(i)) {
1944 if (Grp->getInsertPos() == I)
1945 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1946 else
1947 WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1948 }
1949 }
1950 }
1951
1952 /// Return the cost model decision for the given instruction \p I and vector
1953 /// width \p VF. Return CM_Unknown if this instruction did not pass
1954 /// through the cost modeling.
1955 InstWidening getWideningDecision(Instruction *I, unsigned VF) {
1956 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1956, __extension__ __PRETTY_FUNCTION__))
;
1957 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1958 auto Itr = WideningDecisions.find(InstOnVF);
1959 if (Itr == WideningDecisions.end())
1960 return CM_Unknown;
1961 return Itr->second.first;
1962 }
1963
1964 /// Return the vectorization cost for the given instruction \p I and vector
1965 /// width \p VF.
1966 unsigned getWideningCost(Instruction *I, unsigned VF) {
1967 assert(VF >= 2 && "Expected VF >=2")(static_cast <bool> (VF >= 2 && "Expected VF >=2"
) ? void (0) : __assert_fail ("VF >= 2 && \"Expected VF >=2\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1967, __extension__ __PRETTY_FUNCTION__))
;
1968 std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1969 assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated")(static_cast <bool> (WideningDecisions.count(InstOnVF) &&
"The cost is not calculated") ? void (0) : __assert_fail ("WideningDecisions.count(InstOnVF) && \"The cost is not calculated\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 1969, __extension__ __PRETTY_FUNCTION__))
;
1970 return WideningDecisions[InstOnVF].second;
1971 }
1972
1973 /// Return True if instruction \p I is an optimizable truncate whose operand
1974 /// is an induction variable. Such a truncate will be removed by adding a new
1975 /// induction variable with the destination type.
1976 bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1977 // If the instruction is not a truncate, return false.
1978 auto *Trunc = dyn_cast<TruncInst>(I);
1979 if (!Trunc)
1980 return false;
1981
1982 // Get the source and destination types of the truncate.
1983 Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1984 Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1985
1986 // If the truncate is free for the given types, return false. Replacing a
1987 // free truncate with an induction variable would add an induction variable
1988 // update instruction to each iteration of the loop. We exclude from this
1989 // check the primary induction variable since it will need an update
1990 // instruction regardless.
1991 Value *Op = Trunc->getOperand(0);
1992 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1993 return false;
1994
1995 // If the truncated value is not an induction variable, return false.
1996 return Legal->isInductionPhi(Op);
1997 }
1998
1999 /// Collects the instructions to scalarize for each predicated instruction in
2000 /// the loop.
2001 void collectInstsToScalarize(unsigned VF);
2002
2003 /// Collect Uniform and Scalar values for the given \p VF.
2004 /// The sets depend on CM decision for Load/Store instructions
2005 /// that may be vectorized as interleave, gather-scatter or scalarized.
2006 void collectUniformsAndScalars(unsigned VF) {
2007 // Do the analysis once.
2008 if (VF == 1 || Uniforms.count(VF))
2009 return;
2010 setCostBasedWideningDecision(VF);
2011 collectLoopUniforms(VF);
2012 collectLoopScalars(VF);
2013 }
2014
2015 /// Returns true if the target machine supports masked store operation
2016 /// for the given \p DataType and kind of access to \p Ptr.
2017 bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
2018 return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
2019 }
2020
2021 /// Returns true if the target machine supports masked load operation
2022 /// for the given \p DataType and kind of access to \p Ptr.
2023 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
2024 return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
2025 }
2026
2027 /// Returns true if the target machine supports masked scatter operation
2028 /// for the given \p DataType.
2029 bool isLegalMaskedScatter(Type *DataType) {
2030 return TTI.isLegalMaskedScatter(DataType);
2031 }
2032
2033 /// Returns true if the target machine supports masked gather operation
2034 /// for the given \p DataType.
2035 bool isLegalMaskedGather(Type *DataType) {
2036 return TTI.isLegalMaskedGather(DataType);
2037 }
2038
2039 /// Returns true if the target machine can represent \p V as a masked gather
2040 /// or scatter operation.
2041 bool isLegalGatherOrScatter(Value *V) {
2042 bool LI = isa<LoadInst>(V);
2043 bool SI = isa<StoreInst>(V);
2044 if (!LI && !SI)
2045 return false;
2046 auto *Ty = getMemInstValueType(V);
2047 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
2048 }
2049
2050 /// Returns true if \p I is an instruction that will be scalarized with
2051 /// predication. Such instructions include conditional stores and
2052 /// instructions that may divide by zero.
2053 bool isScalarWithPredication(Instruction *I);
2054
2055 /// Returns true if \p I is a memory instruction with consecutive memory
2056 /// access that can be widened.
2057 bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
2058
2059private:
2060 unsigned NumPredStores = 0;
2061
2062 /// \return An upper bound for the vectorization factor, larger than zero.
2063 /// One is returned if vectorization should best be avoided due to cost.
2064 unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
2065
2066 /// The vectorization cost is a combination of the cost itself and a boolean
2067 /// indicating whether any of the contributing operations will actually
2068 /// operate on
2069 /// vector values after type legalization in the backend. If this latter value
2070 /// is
2071 /// false, then all operations will be scalarized (i.e. no vectorization has
2072 /// actually taken place).
2073 using VectorizationCostTy = std::pair<unsigned, bool>;
2074
2075 /// Returns the expected execution cost. The unit of the cost does
2076 /// not matter because we use the 'cost' units to compare different
2077 /// vector widths. The cost that is returned is *not* normalized by
2078 /// the factor width.
2079 VectorizationCostTy expectedCost(unsigned VF);
2080
2081 /// Returns the execution time cost of an instruction for a given vector
2082 /// width. Vector width of one means scalar.
2083 VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
2084
2085 /// The cost-computation logic from getInstructionCost which provides
2086 /// the vector type as an output parameter.
2087 unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
2088
2089 /// Calculate vectorization cost of memory instruction \p I.
2090 unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
2091
2092 /// The cost computation for scalarized memory instruction.
2093 unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
2094
2095 /// The cost computation for interleaving group of memory instructions.
2096 unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
2097
2098 /// The cost computation for Gather/Scatter instruction.
2099 unsigned getGatherScatterCost(Instruction *I, unsigned VF);
2100
2101 /// The cost computation for widening instruction \p I with consecutive
2102 /// memory access.
2103 unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
2104
2105 /// The cost calculation for Load instruction \p I with uniform pointer -
2106 /// scalar load + broadcast.
2107 unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
2108
2109 /// Returns whether the instruction is a load or store and will be a emitted
2110 /// as a vector operation.
2111 bool isConsecutiveLoadOrStore(Instruction *I);
2112
2113 /// Returns true if an artificially high cost for emulated masked memrefs
2114 /// should be used.
2115 bool useEmulatedMaskMemRefHack(Instruction *I);
2116
2117 /// Create an analysis remark that explains why vectorization failed
2118 ///
2119 /// \p RemarkName is the identifier for the remark. \return the remark object
2120 /// that can be streamed to.
2121 OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
2122 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
2123 RemarkName, TheLoop);
2124 }
2125
2126 /// Map of scalar integer values to the smallest bitwidth they can be legally
2127 /// represented as. The vector equivalents of these values should be truncated
2128 /// to this type.
2129 MapVector<Instruction *, uint64_t> MinBWs;
2130
2131 /// A type representing the costs for instructions if they were to be
2132 /// scalarized rather than vectorized. The entries are Instruction-Cost
2133 /// pairs.
2134 using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
2135
2136 /// A set containing all BasicBlocks that are known to present after
2137 /// vectorization as a predicated block.
2138 SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
2139
2140 /// A map holding scalar costs for different vectorization factors. The
2141 /// presence of a cost for an instruction in the mapping indicates that the
2142 /// instruction will be scalarized when vectorizing with the associated
2143 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
2144 DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
2145
2146 /// Holds the instructions known to be uniform after vectorization.
2147 /// The data is collected per VF.
2148 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
2149
2150 /// Holds the instructions known to be scalar after vectorization.
2151 /// The data is collected per VF.
2152 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
2153
2154 /// Holds the instructions (address computations) that are forced to be
2155 /// scalarized.
2156 DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
2157
2158 /// Returns the expected difference in cost from scalarizing the expression
2159 /// feeding a predicated instruction \p PredInst. The instructions to
2160 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
2161 /// non-negative return value implies the expression will be scalarized.
2162 /// Currently, only single-use chains are considered for scalarization.
2163 int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2164 unsigned VF);
2165
2166 /// Collect the instructions that are uniform after vectorization. An
2167 /// instruction is uniform if we represent it with a single scalar value in
2168 /// the vectorized loop corresponding to each vector iteration. Examples of
2169 /// uniform instructions include pointer operands of consecutive or
2170 /// interleaved memory accesses. Note that although uniformity implies an
2171 /// instruction will be scalar, the reverse is not true. In general, a
2172 /// scalarized instruction will be represented by VF scalar values in the
2173 /// vectorized loop, each corresponding to an iteration of the original
2174 /// scalar loop.
2175 void collectLoopUniforms(unsigned VF);
2176
2177 /// Collect the instructions that are scalar after vectorization. An
2178 /// instruction is scalar if it is known to be uniform or will be scalarized
2179 /// during vectorization. Non-uniform scalarized instructions will be
2180 /// represented by VF values in the vectorized loop, each corresponding to an
2181 /// iteration of the original scalar loop.
2182 void collectLoopScalars(unsigned VF);
2183
2184 /// Keeps cost model vectorization decision and cost for instructions.
2185 /// Right now it is used for memory instructions only.
2186 using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
2187 std::pair<InstWidening, unsigned>>;
2188
2189 DecisionList WideningDecisions;
2190
2191public:
2192 /// The loop that we evaluate.
2193 Loop *TheLoop;
2194
2195 /// Predicated scalar evolution analysis.
2196 PredicatedScalarEvolution &PSE;
2197
2198 /// Loop Info analysis.
2199 LoopInfo *LI;
2200
2201 /// Vectorization legality.
2202 LoopVectorizationLegality *Legal;
2203
2204 /// Vector target information.
2205 const TargetTransformInfo &TTI;
2206
2207 /// Target Library Info.
2208 const TargetLibraryInfo *TLI;
2209
2210 /// Demanded bits analysis.
2211 DemandedBits *DB;
2212
2213 /// Assumption cache.
2214 AssumptionCache *AC;
2215
2216 /// Interface to emit optimization remarks.
2217 OptimizationRemarkEmitter *ORE;
2218
2219 const Function *TheFunction;
2220
2221 /// Loop Vectorize Hint.
2222 const LoopVectorizeHints *Hints;
2223
2224 /// Values to ignore in the cost model.
2225 SmallPtrSet<const Value *, 16> ValuesToIgnore;
2226
2227 /// Values to ignore in the cost model when VF > 1.
2228 SmallPtrSet<const Value *, 16> VecValuesToIgnore;
2229};
2230
2231} // end namespace llvm
2232
2233namespace {
2234
2235/// \brief This holds vectorization requirements that must be verified late in
2236/// the process. The requirements are set by legalize and costmodel. Once
2237/// vectorization has been determined to be possible and profitable the
2238/// requirements can be verified by looking for metadata or compiler options.
2239/// For example, some loops require FP commutativity which is only allowed if
2240/// vectorization is explicitly specified or if the fast-math compiler option
2241/// has been provided.
2242/// Late evaluation of these requirements allows helpful diagnostics to be
2243/// composed that tells the user what need to be done to vectorize the loop. For
2244/// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
2245/// evaluation should be used only when diagnostics can generated that can be
2246/// followed by a non-expert user.
2247class LoopVectorizationRequirements {
2248public:
2249 LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE) : ORE(ORE) {}
2250
2251 void addUnsafeAlgebraInst(Instruction *I) {
2252 // First unsafe algebra instruction.
2253 if (!UnsafeAlgebraInst)
2254 UnsafeAlgebraInst = I;
2255 }
2256
2257 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
2258
2259 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
2260 const char *PassName = Hints.vectorizeAnalysisPassName();
2261 bool Failed = false;
2262 if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2263 ORE.emit([&]() {
2264 return OptimizationRemarkAnalysisFPCommute(
2265 PassName, "CantReorderFPOps",
2266 UnsafeAlgebraInst->getDebugLoc(),
2267 UnsafeAlgebraInst->getParent())
2268 << "loop not vectorized: cannot prove it is safe to reorder "
2269 "floating-point operations";
2270 });
2271 Failed = true;
2272 }
2273
2274 // Test if runtime memcheck thresholds are exceeded.
2275 bool PragmaThresholdReached =
2276 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
2277 bool ThresholdReached =
2278 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
2279 if ((ThresholdReached && !Hints.allowReordering()) ||
2280 PragmaThresholdReached) {
2281 ORE.emit([&]() {
2282 return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
2283 L->getStartLoc(),
2284 L->getHeader())
2285 << "loop not vectorized: cannot prove it is safe to reorder "
2286 "memory operations";
2287 });
2288 DEBUG(dbgs() << "LV: Too many memory checks needed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Too many memory checks needed.\n"
; } } while (false)
;
2289 Failed = true;
2290 }
2291
2292 return Failed;
2293 }
2294
2295private:
2296 unsigned NumRuntimePointerChecks = 0;
2297 Instruction *UnsafeAlgebraInst = nullptr;
2298
2299 /// Interface to emit optimization remarks.
2300 OptimizationRemarkEmitter &ORE;
2301};
2302
2303} // end anonymous namespace
2304
2305static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
2306 if (L.empty()) {
2307 if (!hasCyclesInLoopBody(L))
2308 V.push_back(&L);
2309 return;
2310 }
2311 for (Loop *InnerL : L)
2312 addAcyclicInnerLoop(*InnerL, V);
2313}
2314
2315namespace {
2316
2317/// The LoopVectorize Pass.
2318struct LoopVectorize : public FunctionPass {
2319 /// Pass identification, replacement for typeid
2320 static char ID;
2321
2322 LoopVectorizePass Impl;
2323
2324 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
2325 : FunctionPass(ID) {
2326 Impl.DisableUnrolling = NoUnrolling;
2327 Impl.AlwaysVectorize = AlwaysVectorize;
2328 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2329 }
2330
2331 bool runOnFunction(Function &F) override {
2332 if (skipFunction(F))
2333 return false;
2334
2335 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2336 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2337 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2338 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2339 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2340 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2341 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2342 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2343 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2344 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2345 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2346 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2347
2348 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2349 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2350
2351 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2352 GetLAA, *ORE);
2353 }
2354
2355 void getAnalysisUsage(AnalysisUsage &AU) const override {
2356 AU.addRequired<AssumptionCacheTracker>();
2357 AU.addRequired<BlockFrequencyInfoWrapperPass>();
2358 AU.addRequired<DominatorTreeWrapperPass>();
2359 AU.addRequired<LoopInfoWrapperPass>();
2360 AU.addRequired<ScalarEvolutionWrapperPass>();
2361 AU.addRequired<TargetTransformInfoWrapperPass>();
2362 AU.addRequired<AAResultsWrapperPass>();
2363 AU.addRequired<LoopAccessLegacyAnalysis>();
2364 AU.addRequired<DemandedBitsWrapperPass>();
2365 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2366 AU.addPreserved<LoopInfoWrapperPass>();
2367 AU.addPreserved<DominatorTreeWrapperPass>();
2368 AU.addPreserved<BasicAAWrapperPass>();
2369 AU.addPreserved<GlobalsAAWrapperPass>();
2370 }
2371};
2372
2373} // end anonymous namespace
2374
2375//===----------------------------------------------------------------------===//
2376// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2377// LoopVectorizationCostModel and LoopVectorizationPlanner.
2378//===----------------------------------------------------------------------===//
2379
2380Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2381 // We need to place the broadcast of invariant variables outside the loop.
2382 Instruction *Instr = dyn_cast<Instruction>(V);
2383 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
2384 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2385
2386 // Place the code for broadcasting invariant variables in the new preheader.
2387 IRBuilder<>::InsertPointGuard Guard(Builder);
2388 if (Invariant)
2389 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2390
2391 // Broadcast the scalar into all locations in the vector.
2392 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2393
2394 return Shuf;
2395}
2396
2397void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2398 const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
2399 Value *Start = II.getStartValue();
2400
2401 // Construct the initial value of the vector IV in the vector loop preheader
2402 auto CurrIP = Builder.saveIP();
2403 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2404 if (isa<TruncInst>(EntryVal)) {
2405 assert(Start->getType()->isIntegerTy() &&(static_cast <bool> (Start->getType()->isIntegerTy
() && "Truncation requires an integer type") ? void (
0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2406, __extension__ __PRETTY_FUNCTION__))
2406 "Truncation requires an integer type")(static_cast <bool> (Start->getType()->isIntegerTy
() && "Truncation requires an integer type") ? void (
0) : __assert_fail ("Start->getType()->isIntegerTy() && \"Truncation requires an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2406, __extension__ __PRETTY_FUNCTION__))
;
2407 auto *TruncType = cast<IntegerType>(EntryVal->getType());
2408 Step = Builder.CreateTrunc(Step, TruncType);
2409 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2410 }
2411 Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2412 Value *SteppedStart =
2413 getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2414
2415 // We create vector phi nodes for both integer and floating-point induction
2416 // variables. Here, we determine the kind of arithmetic we will perform.
2417 Instruction::BinaryOps AddOp;
2418 Instruction::BinaryOps MulOp;
2419 if (Step->getType()->isIntegerTy()) {
2420 AddOp = Instruction::Add;
2421 MulOp = Instruction::Mul;
2422 } else {
2423 AddOp = II.getInductionOpcode();
2424 MulOp = Instruction::FMul;
2425 }
2426
2427 // Multiply the vectorization factor by the step using integer or
2428 // floating-point arithmetic as appropriate.
2429 Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2430 Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2431
2432 // Create a vector splat to use in the induction update.
2433 //
2434 // FIXME: If the step is non-constant, we create the vector splat with
2435 // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2436 // handle a constant vector splat.
2437 Value *SplatVF = isa<Constant>(Mul)
2438 ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2439 : Builder.CreateVectorSplat(VF, Mul);
2440 Builder.restoreIP(CurrIP);
2441
2442 // We may need to add the step a number of times, depending on the unroll
2443 // factor. The last of those goes into the PHI.
2444 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2445 &*LoopVectorBody->getFirstInsertionPt());
2446 Instruction *LastInduction = VecInd;
2447 for (unsigned Part = 0; Part < UF; ++Part) {
2448 VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
2449
2450 if (isa<TruncInst>(EntryVal))
2451 addMetadata(LastInduction, EntryVal);
2452 else
2453 recordVectorLoopValueForInductionCast(II, LastInduction, Part);
2454
2455 LastInduction = cast<Instruction>(addFastMathFlag(
2456 Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2457 }
2458
2459 // Move the last step to the end of the latch block. This ensures consistent
2460 // placement of all induction updates.
2461 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2462 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2463 auto *ICmp = cast<Instruction>(Br->getCondition());
2464 LastInduction->moveBefore(ICmp);
2465 LastInduction->setName("vec.ind.next");
2466
2467 VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2468 VecInd->addIncoming(LastInduction, LoopVectorLatch);
2469}
2470
2471bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2472 return Cost->isScalarAfterVectorization(I, VF) ||
2473 Cost->isProfitableToScalarize(I, VF);
2474}
2475
2476bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2477 if (shouldScalarizeInstruction(IV))
2478 return true;
2479 auto isScalarInst = [&](User *U) -> bool {
2480 auto *I = cast<Instruction>(U);
2481 return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2482 };
2483 return llvm::any_of(IV->users(), isScalarInst);
2484}
2485
2486void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2487 const InductionDescriptor &ID, Value *VectorLoopVal, unsigned Part,
2488 unsigned Lane) {
2489 const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2490 if (Casts.empty())
2491 return;
2492 // Only the first Cast instruction in the Casts vector is of interest.
2493 // The rest of the Casts (if exist) have no uses outside the
2494 // induction update chain itself.
2495 Instruction *CastInst = *Casts.begin();
2496 if (Lane < UINT_MAX(2147483647 *2U +1U))
2497 VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
2498 else
2499 VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
2500}
2501
2502void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
2503 assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&(static_cast <bool> ((IV->getType()->isIntegerTy(
) || IV != OldInduction) && "Primary induction variable must have an integer type"
) ? void (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2504, __extension__ __PRETTY_FUNCTION__))
2504 "Primary induction variable must have an integer type")(static_cast <bool> ((IV->getType()->isIntegerTy(
) || IV != OldInduction) && "Primary induction variable must have an integer type"
) ? void (0) : __assert_fail ("(IV->getType()->isIntegerTy() || IV != OldInduction) && \"Primary induction variable must have an integer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2504, __extension__ __PRETTY_FUNCTION__))
;
2505
2506 auto II = Legal->getInductionVars()->find(IV);
2507 assert(II != Legal->getInductionVars()->end() && "IV is not an induction")(static_cast <bool> (II != Legal->getInductionVars()
->end() && "IV is not an induction") ? void (0) : __assert_fail
("II != Legal->getInductionVars()->end() && \"IV is not an induction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2507, __extension__ __PRETTY_FUNCTION__))
;
2508
2509 auto ID = II->second;
2510 assert(IV->getType() == ID.getStartValue()->getType() && "Types must match")(static_cast <bool> (IV->getType() == ID.getStartValue
()->getType() && "Types must match") ? void (0) : __assert_fail
("IV->getType() == ID.getStartValue()->getType() && \"Types must match\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2510, __extension__ __PRETTY_FUNCTION__))
;
2511
2512 // The scalar value to broadcast. This will be derived from the canonical
2513 // induction variable.
2514 Value *ScalarIV = nullptr;
2515
2516 // The value from the original loop to which we are mapping the new induction
2517 // variable.
2518 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2519
2520 // True if we have vectorized the induction variable.
2521 auto VectorizedIV = false;
2522
2523 // Determine if we want a scalar version of the induction variable. This is
2524 // true if the induction variable itself is not widened, or if it has at
2525 // least one user in the loop that is not widened.
2526 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2527
2528 // Generate code for the induction step. Note that induction steps are
2529 // required to be loop-invariant
2530 assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&(static_cast <bool> (PSE.getSE()->isLoopInvariant(ID
.getStep(), OrigLoop) && "Induction step should be loop invariant"
) ? void (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2531, __extension__ __PRETTY_FUNCTION__))
2531 "Induction step should be loop invariant")(static_cast <bool> (PSE.getSE()->isLoopInvariant(ID
.getStep(), OrigLoop) && "Induction step should be loop invariant"
) ? void (0) : __assert_fail ("PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) && \"Induction step should be loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2531, __extension__ __PRETTY_FUNCTION__))
;
2532 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2533 Value *Step = nullptr;
2534 if (PSE.getSE()->isSCEVable(IV->getType())) {
2535 SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2536 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2537 LoopVectorPreHeader->getTerminator());
2538 } else {
2539 Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2540 }
2541
2542 // Try to create a new independent vector induction variable. If we can't
2543 // create the phi node, we will splat the scalar induction variable in each
2544 // loop iteration.
2545 if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2546 createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2547 VectorizedIV = true;
2548 }
2549
2550 // If we haven't yet vectorized the induction variable, or if we will create
2551 // a scalar one, we need to define the scalar induction variable and step
2552 // values. If we were given a truncation type, truncate the canonical
2553 // induction variable and step. Otherwise, derive these values from the
2554 // induction descriptor.
2555 if (!VectorizedIV || NeedsScalarIV) {
2556 ScalarIV = Induction;
2557 if (IV != OldInduction) {
2558 ScalarIV = IV->getType()->isIntegerTy()
2559 ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2560 : Builder.CreateCast(Instruction::SIToFP, Induction,
2561 IV->getType());
2562 ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2563 ScalarIV->setName("offset.idx");
2564 }
2565 if (Trunc) {
2566 auto *TruncType = cast<IntegerType>(Trunc->getType());
2567 assert(Step->getType()->isIntegerTy() &&(static_cast <bool> (Step->getType()->isIntegerTy
() && "Truncation requires an integer step") ? void (
0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2568, __extension__ __PRETTY_FUNCTION__))
2568 "Truncation requires an integer step")(static_cast <bool> (Step->getType()->isIntegerTy
() && "Truncation requires an integer step") ? void (
0) : __assert_fail ("Step->getType()->isIntegerTy() && \"Truncation requires an integer step\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2568, __extension__ __PRETTY_FUNCTION__))
;
2569 ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2570 Step = Builder.CreateTrunc(Step, TruncType);
2571 }
2572 }
2573
2574 // If we haven't yet vectorized the induction variable, splat the scalar
2575 // induction variable, and build the necessary step vectors.
2576 // TODO: Don't do it unless the vectorized IV is really required.
2577 if (!VectorizedIV) {
2578 Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2579 for (unsigned Part = 0; Part < UF; ++Part) {
2580 Value *EntryPart =
2581 getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2582 VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
2583 if (Trunc)
2584 addMetadata(EntryPart, Trunc);
2585 else
2586 recordVectorLoopValueForInductionCast(ID, EntryPart, Part);
2587 }
2588 }
2589
2590 // If an induction variable is only used for counting loop iterations or
2591 // calculating addresses, it doesn't need to be widened. Create scalar steps
2592 // that can be used by instructions we will later scalarize. Note that the
2593 // addition of the scalar steps will not increase the number of instructions
2594 // in the loop in the common case prior to InstCombine. We will be trading
2595 // one vector extract for each scalar step.
2596 if (NeedsScalarIV)
2597 buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2598}
2599
2600Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2601 Instruction::BinaryOps BinOp) {
2602 // Create and check the types.
2603 assert(Val->getType()->isVectorTy() && "Must be a vector")(static_cast <bool> (Val->getType()->isVectorTy()
&& "Must be a vector") ? void (0) : __assert_fail ("Val->getType()->isVectorTy() && \"Must be a vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2603, __extension__ __PRETTY_FUNCTION__))
;
2604 int VLen = Val->getType()->getVectorNumElements();
2605
2606 Type *STy = Val->getType()->getScalarType();
2607 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&(static_cast <bool> ((STy->isIntegerTy() || STy->
isFloatingPointTy()) && "Induction Step must be an integer or FP"
) ? void (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2608, __extension__ __PRETTY_FUNCTION__))
2608 "Induction Step must be an integer or FP")(static_cast <bool> ((STy->isIntegerTy() || STy->
isFloatingPointTy()) && "Induction Step must be an integer or FP"
) ? void (0) : __assert_fail ("(STy->isIntegerTy() || STy->isFloatingPointTy()) && \"Induction Step must be an integer or FP\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2608, __extension__ __PRETTY_FUNCTION__))
;
2609 assert(Step->getType() == STy && "Step has wrong type")(static_cast <bool> (Step->getType() == STy &&
"Step has wrong type") ? void (0) : __assert_fail ("Step->getType() == STy && \"Step has wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2609, __extension__ __PRETTY_FUNCTION__))
;
2610
2611 SmallVector<Constant *, 8> Indices;
2612
2613 if (STy->isIntegerTy()) {
2614 // Create a vector of consecutive numbers from zero to VF.
2615 for (int i = 0; i < VLen; ++i)
2616 Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2617
2618 // Add the consecutive indices to the vector value.
2619 Constant *Cv = ConstantVector::get(Indices);
2620 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec")(static_cast <bool> (Cv->getType() == Val->getType
() && "Invalid consecutive vec") ? void (0) : __assert_fail
("Cv->getType() == Val->getType() && \"Invalid consecutive vec\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2620, __extension__ __PRETTY_FUNCTION__))
;
2621 Step = Builder.CreateVectorSplat(VLen, Step);
2622 assert(Step->getType() == Val->getType() && "Invalid step vec")(static_cast <bool> (Step->getType() == Val->getType
() && "Invalid step vec") ? void (0) : __assert_fail (
"Step->getType() == Val->getType() && \"Invalid step vec\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2622, __extension__ __PRETTY_FUNCTION__))
;
2623 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2624 // which can be found from the original scalar operations.
2625 Step = Builder.CreateMul(Cv, Step);
2626 return Builder.CreateAdd(Val, Step, "induction");
2627 }
2628
2629 // Floating point induction.
2630 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&(static_cast <bool> ((BinOp == Instruction::FAdd || BinOp
== Instruction::FSub) && "Binary Opcode should be specified for FP induction"
) ? void (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2631, __extension__ __PRETTY_FUNCTION__))
2631 "Binary Opcode should be specified for FP induction")(static_cast <bool> ((BinOp == Instruction::FAdd || BinOp
== Instruction::FSub) && "Binary Opcode should be specified for FP induction"
) ? void (0) : __assert_fail ("(BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && \"Binary Opcode should be specified for FP induction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2631, __extension__ __PRETTY_FUNCTION__))
;
2632 // Create a vector of consecutive numbers from zero to VF.
2633 for (int i = 0; i < VLen; ++i)
2634 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2635
2636 // Add the consecutive indices to the vector value.
2637 Constant *Cv = ConstantVector::get(Indices);
2638
2639 Step = Builder.CreateVectorSplat(VLen, Step);
2640
2641 // Floating point operations had to be 'fast' to enable the induction.
2642 FastMathFlags Flags;
2643 Flags.setFast();
2644
2645 Value *MulOp = Builder.CreateFMul(Cv, Step);
2646 if (isa<Instruction>(MulOp))
2647 // Have to check, MulOp may be a constant
2648 cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2649
2650 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2651 if (isa<Instruction>(BOp))
2652 cast<Instruction>(BOp)->setFastMathFlags(Flags);
2653 return BOp;
2654}
2655
2656void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2657 Value *EntryVal,
2658 const InductionDescriptor &ID) {
2659 // We shouldn't have to build scalar steps if we aren't vectorizing.
2660 assert(VF > 1 && "VF should be greater than one")(static_cast <bool> (VF > 1 && "VF should be greater than one"
) ? void (0) : __assert_fail ("VF > 1 && \"VF should be greater than one\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2660, __extension__ __PRETTY_FUNCTION__))
;
2661
2662 // Get the value type and ensure it and the step have the same integer type.
2663 Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2664 assert(ScalarIVTy == Step->getType() &&(static_cast <bool> (ScalarIVTy == Step->getType() &&
"Val and Step should have the same type") ? void (0) : __assert_fail
("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2665, __extension__ __PRETTY_FUNCTION__))
2665 "Val and Step should have the same type")(static_cast <bool> (ScalarIVTy == Step->getType() &&
"Val and Step should have the same type") ? void (0) : __assert_fail
("ScalarIVTy == Step->getType() && \"Val and Step should have the same type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2665, __extension__ __PRETTY_FUNCTION__))
;
2666
2667 // We build scalar steps for both integer and floating-point induction
2668 // variables. Here, we determine the kind of arithmetic we will perform.
2669 Instruction::BinaryOps AddOp;
2670 Instruction::BinaryOps MulOp;
2671 if (ScalarIVTy->isIntegerTy()) {
2672 AddOp = Instruction::Add;
2673 MulOp = Instruction::Mul;
2674 } else {
2675 AddOp = ID.getInductionOpcode();
2676 MulOp = Instruction::FMul;
2677 }
2678
2679 // Determine the number of scalars we need to generate for each unroll
2680 // iteration. If EntryVal is uniform, we only need to generate the first
2681 // lane. Otherwise, we generate all VF values.
2682 unsigned Lanes =
2683 Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
2684 : VF;
2685 // Compute the scalar steps and save the results in VectorLoopValueMap.
2686 for (unsigned Part = 0; Part < UF; ++Part) {
2687 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2688 auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2689 auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2690 auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2691 VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2692 recordVectorLoopValueForInductionCast(ID, Add, Part, Lane);
2693 }
2694 }
2695}
2696
2697int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2698 const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2699 ValueToValueMap();
2700
2701 int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
2702 if (Stride == 1 || Stride == -1)
2703 return Stride;
2704 return 0;
2705}
2706
2707bool LoopVectorizationLegality::isUniform(Value *V) {
2708 return LAI->isUniform(V);
2709}
2710
2711Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
2712 assert(V != Induction && "The new induction variable should not be used.")(static_cast <bool> (V != Induction && "The new induction variable should not be used."
) ? void (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2712, __extension__ __PRETTY_FUNCTION__))
;
2713 assert(!V->getType()->isVectorTy() && "Can't widen a vector")(static_cast <bool> (!V->getType()->isVectorTy() &&
"Can't widen a vector") ? void (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't widen a vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
;
2714 assert(!V->getType()->isVoidTy() && "Type does not produce a value")(static_cast <bool> (!V->getType()->isVoidTy() &&
"Type does not produce a value") ? void (0) : __assert_fail (
"!V->getType()->isVoidTy() && \"Type does not produce a value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2714, __extension__ __PRETTY_FUNCTION__))
;
2715
2716 // If we have a stride that is replaced by one, do it here.
2717 if (Legal->hasStride(V))
2718 V = ConstantInt::get(V->getType(), 1);
2719
2720 // If we have a vector mapped to this value, return it.
2721 if (VectorLoopValueMap.hasVectorValue(V, Part))
2722 return VectorLoopValueMap.getVectorValue(V, Part);
2723
2724 // If the value has not been vectorized, check if it has been scalarized
2725 // instead. If it has been scalarized, and we actually need the value in
2726 // vector form, we will construct the vector values on demand.
2727 if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2728 Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2729
2730 // If we've scalarized a value, that value should be an instruction.
2731 auto *I = cast<Instruction>(V);
2732
2733 // If we aren't vectorizing, we can just copy the scalar map values over to
2734 // the vector map.
2735 if (VF == 1) {
2736 VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2737 return ScalarValue;
2738 }
2739
2740 // Get the last scalar instruction we generated for V and Part. If the value
2741 // is known to be uniform after vectorization, this corresponds to lane zero
2742 // of the Part unroll iteration. Otherwise, the last instruction is the one
2743 // we created for the last vector lane of the Part unroll iteration.
2744 unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2745 auto *LastInst = cast<Instruction>(
2746 VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2747
2748 // Set the insert point after the last scalarized instruction. This ensures
2749 // the insertelement sequence will directly follow the scalar definitions.
2750 auto OldIP = Builder.saveIP();
2751 auto NewIP = std::next(BasicBlock::iterator(LastInst));
2752 Builder.SetInsertPoint(&*NewIP);
2753
2754 // However, if we are vectorizing, we need to construct the vector values.
2755 // If the value is known to be uniform after vectorization, we can just
2756 // broadcast the scalar value corresponding to lane zero for each unroll
2757 // iteration. Otherwise, we construct the vector values using insertelement
2758 // instructions. Since the resulting vectors are stored in
2759 // VectorLoopValueMap, we will only generate the insertelements once.
2760 Value *VectorValue = nullptr;
2761 if (Cost->isUniformAfterVectorization(I, VF)) {
2762 VectorValue = getBroadcastInstrs(ScalarValue);
2763 VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2764 } else {
2765 // Initialize packing with insertelements to start from undef.
2766 Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
2767 VectorLoopValueMap.setVectorValue(V, Part, Undef);
2768 for (unsigned Lane = 0; Lane < VF; ++Lane)
2769 packScalarIntoVectorValue(V, {Part, Lane});
2770 VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2771 }
2772 Builder.restoreIP(OldIP);
2773 return VectorValue;
2774 }
2775
2776 // If this scalar is unknown, assume that it is a constant or that it is
2777 // loop invariant. Broadcast V and save the value for future uses.
2778 Value *B = getBroadcastInstrs(V);
2779 VectorLoopValueMap.setVectorValue(V, Part, B);
2780 return B;
2781}
2782
2783Value *
2784InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
2785 const VPIteration &Instance) {
2786 // If the value is not an instruction contained in the loop, it should
2787 // already be scalar.
2788 if (OrigLoop->isLoopInvariant(V))
2789 return V;
2790
2791 assert(Instance.Lane > 0(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2793, __extension__ __PRETTY_FUNCTION__))
2792 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2793, __extension__ __PRETTY_FUNCTION__))
2793 : true && "Uniform values only have lane zero")(static_cast <bool> (Instance.Lane > 0 ? !Cost->isUniformAfterVectorization
(cast<Instruction>(V), VF) : true && "Uniform values only have lane zero"
) ? void (0) : __assert_fail ("Instance.Lane > 0 ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF) : true && \"Uniform values only have lane zero\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2793, __extension__ __PRETTY_FUNCTION__))
;
2794
2795 // If the value from the original loop has not been vectorized, it is
2796 // represented by UF x VF scalar values in the new loop. Return the requested
2797 // scalar value.
2798 if (VectorLoopValueMap.hasScalarValue(V, Instance))
2799 return VectorLoopValueMap.getScalarValue(V, Instance);
2800
2801 // If the value has not been scalarized, get its entry in VectorLoopValueMap
2802 // for the given unroll part. If this entry is not a vector type (i.e., the
2803 // vectorization factor is one), there is no need to generate an
2804 // extractelement instruction.
2805 auto *U = getOrCreateVectorValue(V, Instance.Part);
2806 if (!U->getType()->isVectorTy()) {
2807 assert(VF == 1 && "Value not scalarized has non-vector type")(static_cast <bool> (VF == 1 && "Value not scalarized has non-vector type"
) ? void (0) : __assert_fail ("VF == 1 && \"Value not scalarized has non-vector type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2807, __extension__ __PRETTY_FUNCTION__))
;
2808 return U;
2809 }
2810
2811 // Otherwise, the value from the original loop has been vectorized and is
2812 // represented by UF vector values. Extract and return the requested scalar
2813 // value from the appropriate vector lane.
2814 return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2815}
2816
2817void InnerLoopVectorizer::packScalarIntoVectorValue(
2818 Value *V, const VPIteration &Instance) {
2819 assert(V != Induction && "The new induction variable should not be used.")(static_cast <bool> (V != Induction && "The new induction variable should not be used."
) ? void (0) : __assert_fail ("V != Induction && \"The new induction variable should not be used.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2819, __extension__ __PRETTY_FUNCTION__))
;
2820 assert(!V->getType()->isVectorTy() && "Can't pack a vector")(static_cast <bool> (!V->getType()->isVectorTy() &&
"Can't pack a vector") ? void (0) : __assert_fail ("!V->getType()->isVectorTy() && \"Can't pack a vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2820, __extension__ __PRETTY_FUNCTION__))
;
2821 assert(!V->getType()->isVoidTy() && "Type does not produce a value")(static_cast <bool> (!V->getType()->isVoidTy() &&
"Type does not produce a value") ? void (0) : __assert_fail (
"!V->getType()->isVoidTy() && \"Type does not produce a value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2821, __extension__ __PRETTY_FUNCTION__))
;
2822
2823 Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2824 Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2825 VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2826 Builder.getInt32(Instance.Lane));
2827 VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2828}
2829
2830Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2831 assert(Vec->getType()->isVectorTy() && "Invalid type")(static_cast <bool> (Vec->getType()->isVectorTy()
&& "Invalid type") ? void (0) : __assert_fail ("Vec->getType()->isVectorTy() && \"Invalid type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2831, __extension__ __PRETTY_FUNCTION__))
;
2832 SmallVector<Constant *, 8> ShuffleMask;
2833 for (unsigned i = 0; i < VF; ++i)
2834 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2835
2836 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2837 ConstantVector::get(ShuffleMask),
2838 "reverse");
2839}
2840
2841// Try to vectorize the interleave group that \p Instr belongs to.
2842//
2843// E.g. Translate following interleaved load group (factor = 3):
2844// for (i = 0; i < N; i+=3) {
2845// R = Pic[i]; // Member of index 0
2846// G = Pic[i+1]; // Member of index 1
2847// B = Pic[i+2]; // Member of index 2
2848// ... // do something to R, G, B
2849// }
2850// To:
2851// %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2852// %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
2853// %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
2854// %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
2855//
2856// Or translate following interleaved store group (factor = 3):
2857// for (i = 0; i < N; i+=3) {
2858// ... do something to R, G, B
2859// Pic[i] = R; // Member of index 0
2860// Pic[i+1] = G; // Member of index 1
2861// Pic[i+2] = B; // Member of index 2
2862// }
2863// To:
2864// %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2865// %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2866// %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2867// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2868// store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2869void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2870 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2871 assert(Group && "Fail to get an interleaved access group.")(static_cast <bool> (Group && "Fail to get an interleaved access group."
) ? void (0) : __assert_fail ("Group && \"Fail to get an interleaved access group.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2871, __extension__ __PRETTY_FUNCTION__))
;
2872
2873 // Skip if current instruction is not the insert position.
2874 if (Instr != Group->getInsertPos())
2875 return;
2876
2877 const DataLayout &DL = Instr->getModule()->getDataLayout();
2878 Value *Ptr = getPointerOperand(Instr);
2879
2880 // Prepare for the vector type of the interleaved load/store.
2881 Type *ScalarTy = getMemInstValueType(Instr);
2882 unsigned InterleaveFactor = Group->getFactor();
2883 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2884 Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2885
2886 // Prepare for the new pointers.
2887 setDebugLocFromInst(Builder, Ptr);
2888 SmallVector<Value *, 2> NewPtrs;
2889 unsigned Index = Group->getIndex(Instr);
2890
2891 // If the group is reverse, adjust the index to refer to the last vector lane
2892 // instead of the first. We adjust the index from the first vector lane,
2893 // rather than directly getting the pointer for lane VF - 1, because the
2894 // pointer operand of the interleaved access is supposed to be uniform. For
2895 // uniform instructions, we're only required to generate a value for the
2896 // first vector lane in each unroll iteration.
2897 if (Group->isReverse())
2898 Index += (VF - 1) * Group->getFactor();
2899
2900 for (unsigned Part = 0; Part < UF; Part++) {
2901 Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
2902
2903 // Notice current instruction could be any index. Need to adjust the address
2904 // to the member of index 0.
2905 //
2906 // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2907 // b = A[i]; // Member of index 0
2908 // Current pointer is pointed to A[i+1], adjust it to A[i].
2909 //
2910 // E.g. A[i+1] = a; // Member of index 1
2911 // A[i] = b; // Member of index 0
2912 // A[i+2] = c; // Member of index 2 (Current instruction)
2913 // Current pointer is pointed to A[i+2], adjust it to A[i].
2914 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2915
2916 // Cast to the vector pointer type.
2917 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2918 }
2919
2920 setDebugLocFromInst(Builder, Instr);
2921 Value *UndefVec = UndefValue::get(VecTy);
2922
2923 // Vectorize the interleaved load group.
2924 if (isa<LoadInst>(Instr)) {
2925 // For each unroll part, create a wide load for the group.
2926 SmallVector<Value *, 2> NewLoads;
2927 for (unsigned Part = 0; Part < UF; Part++) {
2928 auto *NewLoad = Builder.CreateAlignedLoad(
2929 NewPtrs[Part], Group->getAlignment(), "wide.vec");
2930 Group->addMetadata(NewLoad);
2931 NewLoads.push_back(NewLoad);
2932 }
2933
2934 // For each member in the group, shuffle out the appropriate data from the
2935 // wide loads.
2936 for (unsigned I = 0; I < InterleaveFactor; ++I) {
2937 Instruction *Member = Group->getMember(I);
2938
2939 // Skip the gaps in the group.
2940 if (!Member)
2941 continue;
2942
2943 Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2944 for (unsigned Part = 0; Part < UF; Part++) {
2945 Value *StridedVec = Builder.CreateShuffleVector(
2946 NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2947
2948 // If this member has different type, cast the result type.
2949 if (Member->getType() != ScalarTy) {
2950 VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2951 StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2952 }
2953
2954 if (Group->isReverse())
2955 StridedVec = reverseVector(StridedVec);
2956
2957 VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2958 }
2959 }
2960 return;
2961 }
2962
2963 // The sub vector type for current instruction.
2964 VectorType *SubVT = VectorType::get(ScalarTy, VF);
2965
2966 // Vectorize the interleaved store group.
2967 for (unsigned Part = 0; Part < UF; Part++) {
2968 // Collect the stored vector from each member.
2969 SmallVector<Value *, 4> StoredVecs;
2970 for (unsigned i = 0; i < InterleaveFactor; i++) {
2971 // Interleaved store group doesn't allow a gap, so each index has a member
2972 Instruction *Member = Group->getMember(i);
2973 assert(Member && "Fail to get a member from an interleaved store group")(static_cast <bool> (Member && "Fail to get a member from an interleaved store group"
) ? void (0) : __assert_fail ("Member && \"Fail to get a member from an interleaved store group\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 2973, __extension__ __PRETTY_FUNCTION__))
;
2974
2975 Value *StoredVec = getOrCreateVectorValue(
2976 cast<StoreInst>(Member)->getValueOperand(), Part);
2977 if (Group->isReverse())
2978 StoredVec = reverseVector(StoredVec);
2979
2980 // If this member has different type, cast it to a unified type.
2981
2982 if (StoredVec->getType() != SubVT)
2983 StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2984
2985 StoredVecs.push_back(StoredVec);
2986 }
2987
2988 // Concatenate all vectors into a wide vector.
2989 Value *WideVec = concatenateVectors(Builder, StoredVecs);
2990
2991 // Interleave the elements in the wide vector.
2992 Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2993 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2994 "interleaved.vec");
2995
2996 Instruction *NewStoreInstr =
2997 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2998
2999 Group->addMetadata(NewStoreInstr);
3000 }
3001}
3002
3003void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
3004 VectorParts *BlockInMask) {
3005 // Attempt to issue a wide load.
3006 LoadInst *LI = dyn_cast<LoadInst>(Instr);
3007 StoreInst *SI = dyn_cast<StoreInst>(Instr);
3008
3009 assert((LI || SI) && "Invalid Load/Store instruction")(static_cast <bool> ((LI || SI) && "Invalid Load/Store instruction"
) ? void (0) : __assert_fail ("(LI || SI) && \"Invalid Load/Store instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3009, __extension__ __PRETTY_FUNCTION__))
;
3010
3011 LoopVectorizationCostModel::InstWidening Decision =
3012 Cost->getWideningDecision(Instr, VF);
3013 assert(Decision != LoopVectorizationCostModel::CM_Unknown &&(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Unknown && "CM decision should be taken at this point"
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3014, __extension__ __PRETTY_FUNCTION__))
3014 "CM decision should be taken at this point")(static_cast <bool> (Decision != LoopVectorizationCostModel
::CM_Unknown && "CM decision should be taken at this point"
) ? void (0) : __assert_fail ("Decision != LoopVectorizationCostModel::CM_Unknown && \"CM decision should be taken at this point\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3014, __extension__ __PRETTY_FUNCTION__))
;
3015 if (Decision == LoopVectorizationCostModel::CM_Interleave)
3016 return vectorizeInterleaveGroup(Instr);
3017
3018 Type *ScalarDataTy = getMemInstValueType(Instr);
3019 Type *DataTy = VectorType::get(ScalarDataTy, VF);
3020 Value *Ptr = getPointerOperand(Instr);
3021 unsigned Alignment = getMemInstAlignment(Instr);
3022 // An alignment of 0 means target abi alignment. We need to use the scalar's
3023 // target abi alignment in such a case.
3024 const DataLayout &DL = Instr->getModule()->getDataLayout();
3025 if (!Alignment)
3026 Alignment = DL.getABITypeAlignment(ScalarDataTy);
3027 unsigned AddressSpace = getMemInstAddressSpace(Instr);
3028
3029 // Determine if the pointer operand of the access is either consecutive or
3030 // reverse consecutive.
3031 bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
3032 bool ConsecutiveStride =
3033 Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
3034 bool CreateGatherScatter =
3035 (Decision == LoopVectorizationCostModel::CM_GatherScatter);
3036
3037 // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
3038 // gather/scatter. Otherwise Decision should have been to Scalarize.
3039 assert((ConsecutiveStride || CreateGatherScatter) &&(static_cast <bool> ((ConsecutiveStride || CreateGatherScatter
) && "The instruction should be scalarized") ? void (
0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3040, __extension__ __PRETTY_FUNCTION__))
3040 "The instruction should be scalarized")(static_cast <bool> ((ConsecutiveStride || CreateGatherScatter
) && "The instruction should be scalarized") ? void (
0) : __assert_fail ("(ConsecutiveStride || CreateGatherScatter) && \"The instruction should be scalarized\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3040, __extension__ __PRETTY_FUNCTION__))
;
3041
3042 // Handle consecutive loads/stores.
3043 if (ConsecutiveStride)
3044 Ptr = getOrCreateScalarValue(Ptr, {0, 0});
3045
3046 VectorParts Mask;
3047 bool isMaskRequired = BlockInMask;
3048 if (isMaskRequired)
3049 Mask = *BlockInMask;
3050
3051 // Handle Stores:
3052 if (SI) {
3053 assert(!Legal->isUniform(SI->getPointerOperand()) &&(static_cast <bool> (!Legal->isUniform(SI->getPointerOperand
()) && "We do not allow storing to uniform addresses"
) ? void (0) : __assert_fail ("!Legal->isUniform(SI->getPointerOperand()) && \"We do not allow storing to uniform addresses\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3054, __extension__ __PRETTY_FUNCTION__))
3054 "We do not allow storing to uniform addresses")(static_cast <bool> (!Legal->isUniform(SI->getPointerOperand
()) && "We do not allow storing to uniform addresses"
) ? void (0) : __assert_fail ("!Legal->isUniform(SI->getPointerOperand()) && \"We do not allow storing to uniform addresses\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3054, __extension__ __PRETTY_FUNCTION__))
;
3055 setDebugLocFromInst(Builder, SI);
3056
3057 for (unsigned Part = 0; Part < UF; ++Part) {
3058 Instruction *NewSI = nullptr;
3059 Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
3060 if (CreateGatherScatter) {
3061 Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
3062 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3063 NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
3064 MaskPart);
3065 } else {
3066 // Calculate the pointer for the specific unroll-part.
3067 Value *PartPtr =
3068 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3069
3070 if (Reverse) {
3071 // If we store to reverse consecutive memory locations, then we need
3072 // to reverse the order of elements in the stored value.
3073 StoredVal = reverseVector(StoredVal);
3074 // We don't want to update the value in the map as it might be used in
3075 // another expression. So don't call resetVectorValue(StoredVal).
3076
3077 // If the address is consecutive but reversed, then the
3078 // wide store needs to start at the last vector element.
3079 PartPtr =
3080 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3081 PartPtr =
3082 Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3083 if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3084 Mask[Part] = reverseVector(Mask[Part]);
3085 }
3086
3087 Value *VecPtr =
3088 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3089
3090 if (isMaskRequired)
3091 NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3092 Mask[Part]);
3093 else
3094 NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3095 }
3096 addMetadata(NewSI, SI);
3097 }
3098 return;
3099 }
3100
3101 // Handle loads.
3102 assert(LI && "Must have a load instruction")(static_cast <bool> (LI && "Must have a load instruction"
) ? void (0) : __assert_fail ("LI && \"Must have a load instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3102, __extension__ __PRETTY_FUNCTION__))
;
3103 setDebugLocFromInst(Builder, LI);
3104 for (unsigned Part = 0; Part < UF; ++Part) {
3105 Value *NewLI;
3106 if (CreateGatherScatter) {
3107 Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
3108 Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
3109 NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
3110 nullptr, "wide.masked.gather");
3111 addMetadata(NewLI, LI);
3112 } else {
3113 // Calculate the pointer for the specific unroll-part.
3114 Value *PartPtr =
3115 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3116
3117 if (Reverse) {
3118 // If the address is consecutive but reversed, then the
3119 // wide load needs to start at the last vector element.
3120 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3121 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3122 if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3123 Mask[Part] = reverseVector(Mask[Part]);
3124 }
3125
3126 Value *VecPtr =
3127 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3128 if (isMaskRequired)
3129 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3130 UndefValue::get(DataTy),
3131 "wide.masked.load");
3132 else
3133 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
3134
3135 // Add metadata to the load, but setVectorValue to the reverse shuffle.
3136 addMetadata(NewLI, LI);
3137 if (Reverse)
3138 NewLI = reverseVector(NewLI);
3139 }
3140 VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
3141 }
3142}
3143
3144void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
3145 const VPIteration &Instance,
3146 bool IfPredicateInstr) {
3147 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors")(static_cast <bool> (!Instr->getType()->isAggregateType
() && "Can't handle vectors") ? void (0) : __assert_fail
("!Instr->getType()->isAggregateType() && \"Can't handle vectors\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3147, __extension__ __PRETTY_FUNCTION__))
;
3148
3149 setDebugLocFromInst(Builder, Instr);
3150
3151 // Does this instruction return a value ?
3152 bool IsVoidRetTy = Instr->getType()->isVoidTy();
3153
3154 Instruction *Cloned = Instr->clone();
3155 if (!IsVoidRetTy)
3156 Cloned->setName(Instr->getName() + ".cloned");
3157
3158 // Replace the operands of the cloned instructions with their scalar
3159 // equivalents in the new loop.
3160 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
3161 auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
3162 Cloned->setOperand(op, NewOp);
3163 }
3164 addNewMetadata(Cloned, Instr);
3165
3166 // Place the cloned scalar in the new loop.
3167 Builder.Insert(Cloned);
3168
3169 // Add the cloned scalar to the scalar map entry.
3170 VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
3171
3172 // If we just cloned a new assumption, add it the assumption cache.
3173 if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
3174 if (II->getIntrinsicID() == Intrinsic::assume)
3175 AC->registerAssumption(II);
3176
3177 // End if-block.
3178 if (IfPredicateInstr)
3179 PredicatedInstructions.push_back(Cloned);
3180}
3181
3182PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3183 Value *End, Value *Step,
3184 Instruction *DL) {
3185 BasicBlock *Header = L->getHeader();
3186 BasicBlock *Latch = L->getLoopLatch();
3187 // As we're just creating this loop, it's possible no latch exists
3188 // yet. If so, use the header as this will be a single block loop.
3189 if (!Latch)
3190 Latch = Header;
3191
3192 IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3193 Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3194 setDebugLocFromInst(Builder, OldInst);
3195 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3196
3197 Builder.SetInsertPoint(Latch->getTerminator());
3198 setDebugLocFromInst(Builder, OldInst);
3199
3200 // Create i+1 and fill the PHINode.
3201 Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3202 Induction->addIncoming(Start, L->getLoopPreheader());
3203 Induction->addIncoming(Next, Latch);
3204 // Create the compare.
3205 Value *ICmp = Builder.CreateICmpEQ(Next, End);
3206 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
3207
3208 // Now we have two terminators. Remove the old one from the block.
3209 Latch->getTerminator()->eraseFromParent();
3210
3211 return Induction;
3212}
3213
3214Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3215 if (TripCount)
3216 return TripCount;
3217
3218 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3219 // Find the loop boundaries.
3220 ScalarEvolution *SE = PSE.getSE();
3221 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3222 assert(BackedgeTakenCount != SE->getCouldNotCompute() &&(static_cast <bool> (BackedgeTakenCount != SE->getCouldNotCompute
() && "Invalid loop count") ? void (0) : __assert_fail
("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3223, __extension__ __PRETTY_FUNCTION__))
3223 "Invalid loop count")(static_cast <bool> (BackedgeTakenCount != SE->getCouldNotCompute
() && "Invalid loop count") ? void (0) : __assert_fail
("BackedgeTakenCount != SE->getCouldNotCompute() && \"Invalid loop count\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3223, __extension__ __PRETTY_FUNCTION__))
;
3224
3225 Type *IdxTy = Legal->getWidestInductionType();
3226
3227 // The exit count might have the type of i64 while the phi is i32. This can
3228 // happen if we have an induction variable that is sign extended before the
3229 // compare. The only way that we get a backedge taken count is that the
3230 // induction variable was signed and as such will not overflow. In such a case
3231 // truncation is legal.
3232 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
3233 IdxTy->getPrimitiveSizeInBits())
3234 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3235 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3236
3237 // Get the total trip count from the count by adding 1.
3238 const SCEV *ExitCount = SE->getAddExpr(
3239 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3240
3241 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3242
3243 // Expand the trip count and place the new instructions in the preheader.
3244 // Notice that the pre-header does not change, only the loop body.
3245 SCEVExpander Exp(*SE, DL, "induction");
3246
3247 // Count holds the overall loop count (N).
3248 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3249 L->getLoopPreheader()->getTerminator());
3250
3251 if (TripCount->getType()->isPointerTy())
3252 TripCount =
3253 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3254 L->getLoopPreheader()->getTerminator());
3255
3256 return TripCount;
3257}
3258
3259Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3260 if (VectorTripCount)
3261 return VectorTripCount;
3262
3263 Value *TC = getOrCreateTripCount(L);
3264 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3265
3266 // Now we need to generate the expression for the part of the loop that the
3267 // vectorized body will execute. This is equal to N - (N % Step) if scalar
3268 // iterations are not required for correctness, or N - Step, otherwise. Step
3269 // is equal to the vectorization factor (number of SIMD elements) times the
3270 // unroll factor (number of SIMD instructions).
3271 Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
3272 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3273
3274 // If there is a non-reversed interleaved group that may speculatively access
3275 // memory out-of-bounds, we need to ensure that there will be at least one
3276 // iteration of the scalar epilogue loop. Thus, if the step evenly divides
3277 // the trip count, we set the remainder to be equal to the step. If the step
3278 // does not evenly divide the trip count, no adjustment is necessary since
3279 // there will already be scalar iterations. Note that the minimum iterations
3280 // check ensures that N >= Step.
3281 if (VF > 1 && Legal->requiresScalarEpilogue()) {
3282 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3283 R = Builder.CreateSelect(IsZero, Step, R);
3284 }
3285
3286 VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3287
3288 return VectorTripCount;
3289}
3290
3291Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3292 const DataLayout &DL) {
3293 // Verify that V is a vector type with same number of elements as DstVTy.
3294 unsigned VF = DstVTy->getNumElements();
3295 VectorType *SrcVecTy = cast<VectorType>(V->getType());
3296 assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match")(static_cast <bool> ((VF == SrcVecTy->getNumElements
()) && "Vector dimensions do not match") ? void (0) :
__assert_fail ("(VF == SrcVecTy->getNumElements()) && \"Vector dimensions do not match\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3296, __extension__ __PRETTY_FUNCTION__))
;
3297 Type *SrcElemTy = SrcVecTy->getElementType();
3298 Type *DstElemTy = DstVTy->getElementType();
3299 assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&(static_cast <bool> ((DL.getTypeSizeInBits(SrcElemTy) ==
DL.getTypeSizeInBits(DstElemTy)) && "Vector elements must have same size"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3300, __extension__ __PRETTY_FUNCTION__))
3300 "Vector elements must have same size")(static_cast <bool> ((DL.getTypeSizeInBits(SrcElemTy) ==
DL.getTypeSizeInBits(DstElemTy)) && "Vector elements must have same size"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) && \"Vector elements must have same size\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3300, __extension__ __PRETTY_FUNCTION__))
;
3301
3302 // Do a direct cast if element types are castable.
3303 if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3304 return Builder.CreateBitOrPointerCast(V, DstVTy);
3305 }
3306 // V cannot be directly casted to desired vector type.
3307 // May happen when V is a floating point vector but DstVTy is a vector of
3308 // pointers or vice-versa. Handle this using a two-step bitcast using an
3309 // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3310 assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&(static_cast <bool> ((DstElemTy->isPointerTy() != SrcElemTy
->isPointerTy()) && "Only one type should be a pointer type"
) ? void (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3311, __extension__ __PRETTY_FUNCTION__))
3311 "Only one type should be a pointer type")(static_cast <bool> ((DstElemTy->isPointerTy() != SrcElemTy
->isPointerTy()) && "Only one type should be a pointer type"
) ? void (0) : __assert_fail ("(DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) && \"Only one type should be a pointer type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3311, __extension__ __PRETTY_FUNCTION__))
;
3312 assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&(static_cast <bool> ((DstElemTy->isFloatingPointTy()
!= SrcElemTy->isFloatingPointTy()) && "Only one type should be a floating point type"
) ? void (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3313, __extension__ __PRETTY_FUNCTION__))
3313 "Only one type should be a floating point type")(static_cast <bool> ((DstElemTy->isFloatingPointTy()
!= SrcElemTy->isFloatingPointTy()) && "Only one type should be a floating point type"
) ? void (0) : __assert_fail ("(DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) && \"Only one type should be a floating point type\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3313, __extension__ __PRETTY_FUNCTION__))
;
3314 Type *IntTy =
3315 IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3316 VectorType *VecIntTy = VectorType::get(IntTy, VF);
3317 Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3318 return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
3319}
3320
3321void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3322 BasicBlock *Bypass) {
3323 Value *Count = getOrCreateTripCount(L);
3324 BasicBlock *BB = L->getLoopPreheader();
3325 IRBuilder<> Builder(BB->getTerminator());
3326
3327 // Generate code to check if the loop's trip count is less than VF * UF, or
3328 // equal to it in case a scalar epilogue is required; this implies that the
3329 // vector trip count is zero. This check also covers the case where adding one
3330 // to the backedge-taken count overflowed leading to an incorrect trip count
3331 // of zero. In this case we will also jump to the scalar loop.
3332 auto P = Legal->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3333 : ICmpInst::ICMP_ULT;
3334 Value *CheckMinIters = Builder.CreateICmp(
3335 P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
3336
3337 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3338 // Update dominator tree immediately if the generated block is a
3339 // LoopBypassBlock because SCEV expansions to generate loop bypass
3340 // checks may query it before the current function is finished.
3341 DT->addNewBlock(NewBB, BB);
3342 if (L->getParentLoop())
3343 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3344 ReplaceInstWithInst(BB->getTerminator(),
3345 BranchInst::Create(Bypass, NewBB, CheckMinIters));
3346 LoopBypassBlocks.push_back(BB);
3347}
3348
3349void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3350 BasicBlock *BB = L->getLoopPreheader();
3351
3352 // Generate the code to check that the SCEV assumptions that we made.
3353 // We want the new basic block to start at the first instruction in a
3354 // sequence of instructions that form a check.
3355 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3356 "scev.check");
3357 Value *SCEVCheck =
3358 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
3359
3360 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3361 if (C->isZero())
3362 return;
3363
3364 // Create a new block containing the stride check.
3365 BB->setName("vector.scevcheck");
3366 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3367 // Update dominator tree immediately if the generated block is a
3368 // LoopBypassBlock because SCEV expansions to generate loop bypass
3369 // checks may query it before the current function is finished.
3370 DT->addNewBlock(NewBB, BB);
3371 if (L->getParentLoop())
3372 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3373 ReplaceInstWithInst(BB->getTerminator(),
3374 BranchInst::Create(Bypass, NewBB, SCEVCheck));
3375 LoopBypassBlocks.push_back(BB);
3376 AddedSafetyChecks = true;
3377}
3378
3379void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
3380 BasicBlock *BB = L->getLoopPreheader();
3381
3382 // Generate the code that checks in runtime if arrays overlap. We put the
3383 // checks into a separate block to make the more common case of few elements
3384 // faster.
3385 Instruction *FirstCheckInst;
3386 Instruction *MemRuntimeCheck;
3387 std::tie(FirstCheckInst, MemRuntimeCheck) =
3388 Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
3389 if (!MemRuntimeCheck)
3390 return;
3391
3392 // Create a new block containing the memory check.
3393 BB->setName("vector.memcheck");
3394 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3395 // Update dominator tree immediately if the generated block is a
3396 // LoopBypassBlock because SCEV expansions to generate loop bypass
3397 // checks may query it before the current function is finished.
3398 DT->addNewBlock(NewBB, BB);
3399 if (L->getParentLoop())
3400 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3401 ReplaceInstWithInst(BB->getTerminator(),
3402 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3403 LoopBypassBlocks.push_back(BB);
3404 AddedSafetyChecks = true;
3405
3406 // We currently don't use LoopVersioning for the actual loop cloning but we
3407 // still use it to add the noalias metadata.
3408 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3409 PSE.getSE());
3410 LVer->prepareNoAliasMetadata();
3411}
3412
3413BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3414 /*
3415 In this function we generate a new loop. The new loop will contain
3416 the vectorized instructions while the old loop will continue to run the
3417 scalar remainder.
3418
3419 [ ] <-- loop iteration number check.
3420 / |
3421 / v
3422 | [ ] <-- vector loop bypass (may consist of multiple blocks).
3423 | / |
3424 | / v
3425 || [ ] <-- vector pre header.
3426 |/ |
3427 | v
3428 | [ ] \
3429 | [ ]_| <-- vector loop.
3430 | |
3431 | v
3432 | -[ ] <--- middle-block.
3433 | / |
3434 | / v
3435 -|- >[ ] <--- new preheader.
3436 | |
3437 | v
3438 | [ ] \
3439 | [ ]_| <-- old scalar loop to handle remainder.
3440 \ |
3441 \ v
3442 >[ ] <-- exit block.
3443 ...
3444 */
3445
3446 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3447 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3448 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3449 assert(VectorPH && "Invalid loop structure")(static_cast <bool> (VectorPH && "Invalid loop structure"
) ? void (0) : __assert_fail ("VectorPH && \"Invalid loop structure\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3449, __extension__ __PRETTY_FUNCTION__))
;
3450 assert(ExitBlock && "Must have an exit block")(static_cast <bool> (ExitBlock && "Must have an exit block"
) ? void (0) : __assert_fail ("ExitBlock && \"Must have an exit block\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3450, __extension__ __PRETTY_FUNCTION__))
;
3451
3452 // Some loops have a single integer induction variable, while other loops
3453 // don't. One example is c++ iterators that often have multiple pointer
3454 // induction variables. In the code below we also support a case where we
3455 // don't have a single induction variable.
3456 //
3457 // We try to obtain an induction variable from the original loop as hard
3458 // as possible. However if we don't find one that:
3459 // - is an integer
3460 // - counts from zero, stepping by one
3461 // - is the size of the widest induction variable type
3462 // then we create a new one.
3463 OldInduction = Legal->getPrimaryInduction();
3464 Type *IdxTy = Legal->getWidestInductionType();
3465
3466 // Split the single block loop into the two loop structure described above.
3467 BasicBlock *VecBody =
3468 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3469 BasicBlock *MiddleBlock =
3470 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3471 BasicBlock *ScalarPH =
3472 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3473
3474 // Create and register the new vector loop.
3475 Loop *Lp = LI->AllocateLoop();
3476 Loop *ParentLoop = OrigLoop->getParentLoop();
3477
3478 // Insert the new loop into the loop nest and register the new basic blocks
3479 // before calling any utilities such as SCEV that require valid LoopInfo.
3480 if (ParentLoop) {
3481 ParentLoop->addChildLoop(Lp);
3482 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3483 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3484 } else {
3485 LI->addTopLevelLoop(Lp);
3486 }
3487 Lp->addBasicBlockToLoop(VecBody, *LI);
3488
3489 // Find the loop boundaries.
3490 Value *Count = getOrCreateTripCount(Lp);
3491
3492 Value *StartIdx = ConstantInt::get(IdxTy, 0);
3493
3494 // Now, compare the new count to zero. If it is zero skip the vector loop and
3495 // jump to the scalar loop. This check also covers the case where the
3496 // backedge-taken count is uint##_max: adding one to it will overflow leading
3497 // to an incorrect trip count of zero. In this (rare) case we will also jump
3498 // to the scalar loop.
3499 emitMinimumIterationCountCheck(Lp, ScalarPH);
3500
3501 // Generate the code to check any assumptions that we've made for SCEV
3502 // expressions.
3503 emitSCEVChecks(Lp, ScalarPH);
3504
3505 // Generate the code that checks in runtime if arrays overlap. We put the
3506 // checks into a separate block to make the more common case of few elements
3507 // faster.
3508 emitMemRuntimeChecks(Lp, ScalarPH);
3509
3510 // Generate the induction variable.
3511 // The loop step is equal to the vectorization factor (num of SIMD elements)
3512 // times the unroll factor (num of SIMD instructions).
3513 Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3514 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3515 Induction =
3516 createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3517 getDebugLocFromInstOrOperands(OldInduction));
3518
3519 // We are going to resume the execution of the scalar loop.
3520 // Go over all of the induction variables that we found and fix the
3521 // PHIs that are left in the scalar version of the loop.
3522 // The starting values of PHI nodes depend on the counter of the last
3523 // iteration in the vectorized loop.
3524 // If we come from a bypass edge then we need to start from the original
3525 // start value.
3526
3527 // This variable saves the new starting index for the scalar loop. It is used
3528 // to test if there are any tail iterations left once the vector loop has
3529 // completed.
3530 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3531 for (auto &InductionEntry : *List) {
3532 PHINode *OrigPhi = InductionEntry.first;
3533 InductionDescriptor II = InductionEntry.second;
3534
3535 // Create phi nodes to merge from the backedge-taken check block.
3536 PHINode *BCResumeVal = PHINode::Create(
3537 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3538 Value *&EndValue = IVEndValues[OrigPhi];
3539 if (OrigPhi == OldInduction) {
3540 // We know what the end value is.
3541 EndValue = CountRoundDown;
3542 } else {
3543 IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
3544 Type *StepType = II.getStep()->getType();
3545 Instruction::CastOps CastOp =
3546 CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
3547 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
3548 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3549 EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3550 EndValue->setName("ind.end");
3551 }
3552
3553 // The new PHI merges the original incoming value, in case of a bypass,
3554 // or the value at the end of the vectorized loop.
3555 BCResumeVal->addIncoming(EndValue, MiddleBlock);
3556
3557 // Fix the scalar body counter (PHI node).
3558 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3559
3560 // The old induction's phi node in the scalar body needs the truncated
3561 // value.
3562 for (BasicBlock *BB : LoopBypassBlocks)
3563 BCResumeVal->addIncoming(II.getStartValue(), BB);
3564 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3565 }
3566
3567 // Add a check in the middle block to see if we have completed
3568 // all of the iterations in the first vector loop.
3569 // If (N - N%VF) == N, then we *don't* need to run the remainder.
3570 Value *CmpN =
3571 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3572 CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3573 ReplaceInstWithInst(MiddleBlock->getTerminator(),
3574 BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3575
3576 // Get ready to start creating new instructions into the vectorized body.
3577 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3578
3579 // Save the state.
3580 LoopVectorPreHeader = Lp->getLoopPreheader();
3581 LoopScalarPreHeader = ScalarPH;
3582 LoopMiddleBlock = MiddleBlock;
3583 LoopExitBlock = ExitBlock;
3584 LoopVectorBody = VecBody;
3585 LoopScalarBody = OldBasicBlock;
3586
3587 // Keep all loop hints from the original loop on the vector loop (we'll
3588 // replace the vectorizer-specific hints below).
3589 if (MDNode *LID = OrigLoop->getLoopID())
3590 Lp->setLoopID(LID);
3591
3592 LoopVectorizeHints Hints(Lp, true, *ORE);
3593 Hints.setAlreadyVectorized();
3594
3595 return LoopVectorPreHeader;
3596}
3597
3598// Fix up external users of the induction variable. At this point, we are
3599// in LCSSA form, with all external PHIs that use the IV having one input value,
3600// coming from the remainder loop. We need those PHIs to also have a correct
3601// value for the IV when arriving directly from the middle block.
3602void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3603 const InductionDescriptor &II,
3604 Value *CountRoundDown, Value *EndValue,
3605 BasicBlock *MiddleBlock) {
3606 // There are two kinds of external IV usages - those that use the value
3607 // computed in the last iteration (the PHI) and those that use the penultimate
3608 // value (the value that feeds into the phi from the loop latch).
3609 // We allow both, but they, obviously, have different values.
3610
3611 assert(OrigLoop->getExitBlock() && "Expected a single exit block")(static_cast <bool> (OrigLoop->getExitBlock() &&
"Expected a single exit block") ? void (0) : __assert_fail (
"OrigLoop->getExitBlock() && \"Expected a single exit block\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3611, __extension__ __PRETTY_FUNCTION__))
;
3612
3613 DenseMap<Value *, Value *> MissingVals;
3614
3615 // An external user of the last iteration's value should see the value that
3616 // the remainder loop uses to initialize its own IV.
3617 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3618 for (User *U : PostInc->users()) {
3619 Instruction *UI = cast<Instruction>(U);
3620 if (!OrigLoop->contains(UI)) {
3621 assert(isa<PHINode>(UI) && "Expected LCSSA form")(static_cast <bool> (isa<PHINode>(UI) && "Expected LCSSA form"
) ? void (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3621, __extension__ __PRETTY_FUNCTION__))
;
3622 MissingVals[UI] = EndValue;
3623 }
3624 }
3625
3626 // An external user of the penultimate value need to see EndValue - Step.
3627 // The simplest way to get this is to recompute it from the constituent SCEVs,
3628 // that is Start + (Step * (CRD - 1)).
3629 for (User *U : OrigPhi->users()) {
3630 auto *UI = cast<Instruction>(U);
3631 if (!OrigLoop->contains(UI)) {
3632 const DataLayout &DL =
3633 OrigLoop->getHeader()->getModule()->getDataLayout();
3634 assert(isa<PHINode>(UI) && "Expected LCSSA form")(static_cast <bool> (isa<PHINode>(UI) && "Expected LCSSA form"
) ? void (0) : __assert_fail ("isa<PHINode>(UI) && \"Expected LCSSA form\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3634, __extension__ __PRETTY_FUNCTION__))
;
3635
3636 IRBuilder<> B(MiddleBlock->getTerminator());
3637 Value *CountMinusOne = B.CreateSub(
3638 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3639 Value *CMO =
3640 !II.getStep()->getType()->isIntegerTy()
3641 ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3642 II.getStep()->getType())
3643 : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3644 CMO->setName("cast.cmo");
3645 Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3646 Escape->setName("ind.escape");
3647 MissingVals[UI] = Escape;
3648 }
3649 }
3650
3651 for (auto &I : MissingVals) {
3652 PHINode *PHI = cast<PHINode>(I.first);
3653 // One corner case we have to handle is two IVs "chasing" each-other,
3654 // that is %IV2 = phi [...], [ %IV1, %latch ]
3655 // In this case, if IV1 has an external use, we need to avoid adding both
3656 // "last value of IV1" and "penultimate value of IV2". So, verify that we
3657 // don't already have an incoming value for the middle block.
3658 if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3659 PHI->addIncoming(I.second, MiddleBlock);
3660 }
3661}
3662
3663namespace {
3664
3665struct CSEDenseMapInfo {
3666 static bool canHandle(const Instruction *I) {
3667 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3668 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3669 }
3670
3671 static inline Instruction *getEmptyKey() {
3672 return DenseMapInfo<Instruction *>::getEmptyKey();
3673 }
3674
3675 static inline Instruction *getTombstoneKey() {
3676 return DenseMapInfo<Instruction *>::getTombstoneKey();
3677 }
3678
3679 static unsigned getHashValue(const Instruction *I) {
3680 assert(canHandle(I) && "Unknown instruction!")(static_cast <bool> (canHandle(I) && "Unknown instruction!"
) ? void (0) : __assert_fail ("canHandle(I) && \"Unknown instruction!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3680, __extension__ __PRETTY_FUNCTION__))
;
3681 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3682 I->value_op_end()));
3683 }
3684
3685 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3686 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3687 LHS == getTombstoneKey() || RHS == getTombstoneKey())
3688 return LHS == RHS;
3689 return LHS->isIdenticalTo(RHS);
3690 }
3691};
3692
3693} // end anonymous namespace
3694
3695///\brief Perform cse of induction variable instructions.
3696static void cse(BasicBlock *BB) {
3697 // Perform simple cse.
3698 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3699 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3700 Instruction *In = &*I++;
3701
3702 if (!CSEDenseMapInfo::canHandle(In))
3703 continue;
3704
3705 // Check if we can replace this instruction with any of the
3706 // visited instructions.
3707 if (Instruction *V = CSEMap.lookup(In)) {
3708 In->replaceAllUsesWith(V);
3709 In->eraseFromParent();
3710 continue;
3711 }
3712
3713 CSEMap[In] = In;
3714 }
3715}
3716
3717/// \brief Estimate the overhead of scalarizing an instruction. This is a
3718/// convenience wrapper for the type-based getScalarizationOverhead API.
3719static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3720 const TargetTransformInfo &TTI) {
3721 if (VF == 1)
3722 return 0;
3723
3724 unsigned Cost = 0;
3725 Type *RetTy = ToVectorTy(I->getType(), VF);
3726 if (!RetTy->isVoidTy() &&
3727 (!isa<LoadInst>(I) ||
3728 !TTI.supportsEfficientVectorElementLoadStore()))
3729 Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3730
3731 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3732 SmallVector<const Value *, 4> Operands(CI->arg_operands());
3733 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3734 }
3735 else if (!isa<StoreInst>(I) ||
3736 !TTI.supportsEfficientVectorElementLoadStore()) {
3737 SmallVector<const Value *, 4> Operands(I->operand_values());
3738 Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3739 }
3740
3741 return Cost;
3742}
3743
3744// Estimate cost of a call instruction CI if it were vectorized with factor VF.
3745// Return the cost of the instruction, including scalarization overhead if it's
3746// needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3747// i.e. either vector version isn't available, or is too expensive.
3748static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3749 const TargetTransformInfo &TTI,
3750 const TargetLibraryInfo *TLI,
3751 bool &NeedToScalarize) {
3752 Function *F = CI->getCalledFunction();
3753 StringRef FnName = CI->getCalledFunction()->getName();
3754 Type *ScalarRetTy = CI->getType();
3755 SmallVector<Type *, 4> Tys, ScalarTys;
3756 for (auto &ArgOp : CI->arg_operands())
3757 ScalarTys.push_back(ArgOp->getType());
3758
3759 // Estimate cost of scalarized vector call. The source operands are assumed
3760 // to be vectors, so we need to extract individual elements from there,
3761 // execute VF scalar calls, and then gather the result into the vector return
3762 // value.
3763 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3764 if (VF == 1)
3765 return ScalarCallCost;
3766
3767 // Compute corresponding vector type for return value and arguments.
3768 Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3769 for (Type *ScalarTy : ScalarTys)
3770 Tys.push_back(ToVectorTy(ScalarTy, VF));
3771
3772 // Compute costs of unpacking argument values for the scalar calls and
3773 // packing the return values to a vector.
3774 unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3775
3776 unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3777
3778 // If we can't emit a vector call for this function, then the currently found
3779 // cost is the cost we need to return.
3780 NeedToScalarize = true;
3781 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3782 return Cost;
3783
3784 // If the corresponding vector cost is cheaper, return its cost.
3785 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3786 if (VectorCallCost < Cost) {
3787 NeedToScalarize = false;
3788 return VectorCallCost;
3789 }
3790 return Cost;
3791}
3792
3793// Estimate cost of an intrinsic call instruction CI if it were vectorized with
3794// factor VF. Return the cost of the instruction, including scalarization
3795// overhead if it's needed.
3796static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3797 const TargetTransformInfo &TTI,
3798 const TargetLibraryInfo *TLI) {
3799 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3800 assert(ID && "Expected intrinsic call!")(static_cast <bool> (ID && "Expected intrinsic call!"
) ? void (0) : __assert_fail ("ID && \"Expected intrinsic call!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3800, __extension__ __PRETTY_FUNCTION__))
;
3801
3802 FastMathFlags FMF;
3803 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3804 FMF = FPMO->getFastMathFlags();
3805
3806 SmallVector<Value *, 4> Operands(CI->arg_operands());
3807 return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3808}
3809
3810static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3811 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3812 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3813 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3814}
3815static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3816 auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3817 auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3818 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3819}
3820
3821void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3822 // For every instruction `I` in MinBWs, truncate the operands, create a
3823 // truncated version of `I` and reextend its result. InstCombine runs
3824 // later and will remove any ext/trunc pairs.
3825 SmallPtrSet<Value *, 4> Erased;
3826 for (const auto &KV : Cost->getMinimalBitwidths()) {
3827 // If the value wasn't vectorized, we must maintain the original scalar
3828 // type. The absence of the value from VectorLoopValueMap indicates that it
3829 // wasn't vectorized.
3830 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3831 continue;
3832 for (unsigned Part = 0; Part < UF; ++Part) {
3833 Value *I = getOrCreateVectorValue(KV.first, Part);
3834 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3835 continue;
3836 Type *OriginalTy = I->getType();
3837 Type *ScalarTruncatedTy =
3838 IntegerType::get(OriginalTy->getContext(), KV.second);
3839 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3840 OriginalTy->getVectorNumElements());
3841 if (TruncatedTy == OriginalTy)
3842 continue;
3843
3844 IRBuilder<> B(cast<Instruction>(I));
3845 auto ShrinkOperand = [&](Value *V) -> Value * {
3846 if (auto *ZI = dyn_cast<ZExtInst>(V))
3847 if (ZI->getSrcTy() == TruncatedTy)
3848 return ZI->getOperand(0);
3849 return B.CreateZExtOrTrunc(V, TruncatedTy);
3850 };
3851
3852 // The actual instruction modification depends on the instruction type,
3853 // unfortunately.
3854 Value *NewI = nullptr;
3855 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3856 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3857 ShrinkOperand(BO->getOperand(1)));
3858
3859 // Any wrapping introduced by shrinking this operation shouldn't be
3860 // considered undefined behavior. So, we can't unconditionally copy
3861 // arithmetic wrapping flags to NewI.
3862 cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3863 } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3864 NewI =
3865 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3866 ShrinkOperand(CI->getOperand(1)));
3867 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3868 NewI = B.CreateSelect(SI->getCondition(),
3869 ShrinkOperand(SI->getTrueValue()),
3870 ShrinkOperand(SI->getFalseValue()));
3871 } else if (auto *CI = dyn_cast<CastInst>(I)) {
3872 switch (CI->getOpcode()) {
3873 default:
3874 llvm_unreachable("Unhandled cast!")::llvm::llvm_unreachable_internal("Unhandled cast!", "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3874)
;
3875 case Instruction::Trunc:
3876 NewI = ShrinkOperand(CI->getOperand(0));
3877 break;
3878 case Instruction::SExt:
3879 NewI = B.CreateSExtOrTrunc(
3880 CI->getOperand(0),
3881 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3882 break;
3883 case Instruction::ZExt:
3884 NewI = B.CreateZExtOrTrunc(
3885 CI->getOperand(0),
3886 smallestIntegerVectorType(OriginalTy, TruncatedTy));
3887 break;
3888 }
3889 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3890 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3891 auto *O0 = B.CreateZExtOrTrunc(
3892 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3893 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3894 auto *O1 = B.CreateZExtOrTrunc(
3895 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3896
3897 NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3898 } else if (isa<LoadInst>(I)) {
3899 // Don't do anything with the operands, just extend the result.
3900 continue;
3901 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3902 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3903 auto *O0 = B.CreateZExtOrTrunc(
3904 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3905 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3906 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3907 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3908 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3909 auto *O0 = B.CreateZExtOrTrunc(
3910 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3911 NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3912 } else {
3913 llvm_unreachable("Unhandled instruction type!")::llvm::llvm_unreachable_internal("Unhandled instruction type!"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 3913)
;
3914 }
3915
3916 // Lastly, extend the result.
3917 NewI->takeName(cast<Instruction>(I));
3918 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3919 I->replaceAllUsesWith(Res);
3920 cast<Instruction>(I)->eraseFromParent();
3921 Erased.insert(I);
3922 VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3923 }
3924 }
3925
3926 // We'll have created a bunch of ZExts that are now parentless. Clean up.
3927 for (const auto &KV : Cost->getMinimalBitwidths()) {
3928 // If the value wasn't vectorized, we must maintain the original scalar
3929 // type. The absence of the value from VectorLoopValueMap indicates that it
3930 // wasn't vectorized.
3931 if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3932 continue;
3933 for (unsigned Part = 0; Part < UF; ++Part) {
3934 Value *I = getOrCreateVectorValue(KV.first, Part);
3935 ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3936 if (Inst && Inst->use_empty()) {
3937 Value *NewI = Inst->getOperand(0);
3938 Inst->eraseFromParent();
3939 VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3940 }
3941 }
3942 }
3943}
3944
3945void InnerLoopVectorizer::fixVectorizedLoop() {
3946 // Insert truncates and extends for any truncated instructions as hints to
3947 // InstCombine.
3948 if (VF > 1)
3949 truncateToMinimalBitwidths();
3950
3951 // At this point every instruction in the original loop is widened to a
3952 // vector form. Now we need to fix the recurrences in the loop. These PHI
3953 // nodes are currently empty because we did not want to introduce cycles.
3954 // This is the second stage of vectorizing recurrences.
3955 fixCrossIterationPHIs();
3956
3957 // Update the dominator tree.
3958 //
3959 // FIXME: After creating the structure of the new loop, the dominator tree is
3960 // no longer up-to-date, and it remains that way until we update it
3961 // here. An out-of-date dominator tree is problematic for SCEV,
3962 // because SCEVExpander uses it to guide code generation. The
3963 // vectorizer use SCEVExpanders in several places. Instead, we should
3964 // keep the dominator tree up-to-date as we go.
3965 updateAnalysis();
3966
3967 // Fix-up external users of the induction variables.
3968 for (auto &Entry : *Legal->getInductionVars())
3969 fixupIVUsers(Entry.first, Entry.second,
3970 getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3971 IVEndValues[Entry.first], LoopMiddleBlock);
3972
3973 fixLCSSAPHIs();
3974 for (Instruction *PI : PredicatedInstructions)
3975 sinkScalarOperands(&*PI);
3976
3977 // Remove redundant induction instructions.
3978 cse(LoopVectorBody);
3979}
3980
3981void InnerLoopVectorizer::fixCrossIterationPHIs() {
3982 // In order to support recurrences we need to be able to vectorize Phi nodes.
3983 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3984 // stage #2: We now need to fix the recurrences by adding incoming edges to
3985 // the currently empty PHI nodes. At this point every instruction in the
3986 // original loop is widened to a vector form so we can use them to construct
3987 // the incoming edges.
3988 for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3989 // Handle first-order recurrences and reductions that need to be fixed.
3990 if (Legal->isFirstOrderRecurrence(&Phi))
3991 fixFirstOrderRecurrence(&Phi);
3992 else if (Legal->isReductionVariable(&Phi))
3993 fixReduction(&Phi);
3994 }
3995}
3996
3997void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3998 // This is the second phase of vectorizing first-order recurrences. An
3999 // overview of the transformation is described below. Suppose we have the
4000 // following loop.
4001 //
4002 // for (int i = 0; i < n; ++i)
4003 // b[i] = a[i] - a[i - 1];
4004 //
4005 // There is a first-order recurrence on "a". For this loop, the shorthand
4006 // scalar IR looks like:
4007 //
4008 // scalar.ph:
4009 // s_init = a[-1]
4010 // br scalar.body
4011 //
4012 // scalar.body:
4013 // i = phi [0, scalar.ph], [i+1, scalar.body]
4014 // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4015 // s2 = a[i]
4016 // b[i] = s2 - s1
4017 // br cond, scalar.body, ...
4018 //
4019 // In this example, s1 is a recurrence because it's value depends on the
4020 // previous iteration. In the first phase of vectorization, we created a
4021 // temporary value for s1. We now complete the vectorization and produce the
4022 // shorthand vector IR shown below (for VF = 4, UF = 1).
4023 //
4024 // vector.ph:
4025 // v_init = vector(..., ..., ..., a[-1])
4026 // br vector.body
4027 //
4028 // vector.body
4029 // i = phi [0, vector.ph], [i+4, vector.body]
4030 // v1 = phi [v_init, vector.ph], [v2, vector.body]
4031 // v2 = a[i, i+1, i+2, i+3];
4032 // v3 = vector(v1(3), v2(0, 1, 2))
4033 // b[i, i+1, i+2, i+3] = v2 - v3
4034 // br cond, vector.body, middle.block
4035 //
4036 // middle.block:
4037 // x = v2(3)
4038 // br scalar.ph
4039 //
4040 // scalar.ph:
4041 // s_init = phi [x, middle.block], [a[-1], otherwise]
4042 // br scalar.body
4043 //
4044 // After execution completes the vector loop, we extract the next value of
4045 // the recurrence (x) to use as the initial value in the scalar loop.
4046
4047 // Get the original loop preheader and single loop latch.
4048 auto *Preheader = OrigLoop->getLoopPreheader();
4049 auto *Latch = OrigLoop->getLoopLatch();
4050
4051 // Get the initial and previous values of the scalar recurrence.
4052 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4053 auto *Previous = Phi->getIncomingValueForBlock(Latch);
4054
4055 // Create a vector from the initial value.
4056 auto *VectorInit = ScalarInit;
4057 if (VF > 1) {
4058 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4059 VectorInit = Builder.CreateInsertElement(
4060 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4061 Builder.getInt32(VF - 1), "vector.recur.init");
4062 }
4063
4064 // We constructed a temporary phi node in the first phase of vectorization.
4065 // This phi node will eventually be deleted.
4066 Builder.SetInsertPoint(
4067 cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
4068
4069 // Create a phi node for the new recurrence. The current value will either be
4070 // the initial value inserted into a vector or loop-varying vector value.
4071 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4072 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4073
4074 // Get the vectorized previous value of the last part UF - 1. It appears last
4075 // among all unrolled iterations, due to the order of their construction.
4076 Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
4077
4078 // Set the insertion point after the previous value if it is an instruction.
4079 // Note that the previous value may have been constant-folded so it is not
4080 // guaranteed to be an instruction in the vector loop. Also, if the previous
4081 // value is a phi node, we should insert after all the phi nodes to avoid
4082 // breaking basic block verification.
4083 if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
4084 isa<PHINode>(PreviousLastPart))
4085 Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4086 else
4087 Builder.SetInsertPoint(
4088 &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
4089
4090 // We will construct a vector for the recurrence by combining the values for
4091 // the current and previous iterations. This is the required shuffle mask.
4092 SmallVector<Constant *, 8> ShuffleMask(VF);
4093 ShuffleMask[0] = Builder.getInt32(VF - 1);
4094 for (unsigned I = 1; I < VF; ++I)
4095 ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4096
4097 // The vector from which to take the initial value for the current iteration
4098 // (actual or unrolled). Initially, this is the vector phi node.
4099 Value *Incoming = VecPhi;
4100
4101 // Shuffle the current and previous vector and update the vector parts.
4102 for (unsigned Part = 0; Part < UF; ++Part) {
4103 Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
4104 Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
4105 auto *Shuffle =
4106 VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
4107 ConstantVector::get(ShuffleMask))
4108 : Incoming;
4109 PhiPart->replaceAllUsesWith(Shuffle);
4110 cast<Instruction>(PhiPart)->eraseFromParent();
4111 VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
4112 Incoming = PreviousPart;
4113 }
4114
4115 // Fix the latch value of the new recurrence in the vector loop.
4116 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4117
4118 // Extract the last vector element in the middle block. This will be the
4119 // initial value for the recurrence when jumping to the scalar loop.
4120 auto *ExtractForScalar = Incoming;
4121 if (VF > 1) {
4122 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4123 ExtractForScalar = Builder.CreateExtractElement(
4124 ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
4125 }
4126 // Extract the second last element in the middle block if the
4127 // Phi is used outside the loop. We need to extract the phi itself
4128 // and not the last element (the phi update in the current iteration). This
4129 // will be the value when jumping to the exit block from the LoopMiddleBlock,
4130 // when the scalar loop is not run at all.
4131 Value *ExtractForPhiUsedOutsideLoop = nullptr;
4132 if (VF > 1)
4133 ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4134 Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
4135 // When loop is unrolled without vectorizing, initialize
4136 // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4137 // `Incoming`. This is analogous to the vectorized case above: extracting the
4138 // second last element when VF > 1.
4139 else if (UF > 1)
4140 ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
4141
4142 // Fix the initial value of the original recurrence in the scalar loop.
4143 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4144 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4145 for (auto *BB : predecessors(LoopScalarPreHeader)) {
4146 auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4147 Start->addIncoming(Incoming, BB);
4148 }
4149
4150 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4151 Phi->setName("scalar.recur");
4152
4153 // Finally, fix users of the recurrence outside the loop. The users will need
4154 // either the last value of the scalar recurrence or the last value of the
4155 // vector recurrence we extracted in the middle block. Since the loop is in
4156 // LCSSA form, we just need to find the phi node for the original scalar
4157 // recurrence in the exit block, and then add an edge for the middle block.
4158 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4159 if (LCSSAPhi.getIncomingValue(0) == Phi) {
4160 LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4161 break;
4162 }
4163 }
4164}
4165
4166void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
4167 Constant *Zero = Builder.getInt32(0);
4168
4169 // Get it's reduction variable descriptor.
4170 assert(Legal->isReductionVariable(Phi) &&(static_cast <bool> (Legal->isReductionVariable(Phi)
&& "Unable to find the reduction variable") ? void (
0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4171, __extension__ __PRETTY_FUNCTION__))
4171 "Unable to find the reduction variable")(static_cast <bool> (Legal->isReductionVariable(Phi)
&& "Unable to find the reduction variable") ? void (
0) : __assert_fail ("Legal->isReductionVariable(Phi) && \"Unable to find the reduction variable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4171, __extension__ __PRETTY_FUNCTION__))
;
4172 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
4173
4174 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
4175 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4176 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4177 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
4178 RdxDesc.getMinMaxRecurrenceKind();
4179 setDebugLocFromInst(Builder, ReductionStartValue);
4180
4181 // We need to generate a reduction vector from the incoming scalar.
4182 // To do so, we need to generate the 'identity' vector and override
4183 // one of the elements with the incoming scalar reduction. We need
4184 // to do it in the vector-loop preheader.
4185 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4186
4187 // This is the vector-clone of the value that leaves the loop.
4188 Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
4189
4190 // Find the reduction identity variable. Zero for addition, or, xor,
4191 // one for multiplication, -1 for And.
4192 Value *Identity;
4193 Value *VectorStart;
4194 if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
4195 RK == RecurrenceDescriptor::RK_FloatMinMax) {
4196 // MinMax reduction have the start value as their identify.
4197 if (VF == 1) {
4198 VectorStart = Identity = ReductionStartValue;
4199 } else {
4200 VectorStart = Identity =
4201 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
4202 }
4203 } else {
4204 // Handle other reduction kinds:
4205 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
4206 RK, VecTy->getScalarType());
4207 if (VF == 1) {
4208 Identity = Iden;
4209 // This vector is the Identity vector where the first element is the
4210 // incoming scalar reduction.
4211 VectorStart = ReductionStartValue;
4212 } else {
4213 Identity = ConstantVector::getSplat(VF, Iden);
4214
4215 // This vector is the Identity vector where the first element is the
4216 // incoming scalar reduction.
4217 VectorStart =
4218 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4219 }
4220 }
4221
4222 // Fix the vector-loop phi.
4223
4224 // Reductions do not have to start at zero. They can start with
4225 // any loop invariant values.
4226 BasicBlock *Latch = OrigLoop->getLoopLatch();
4227 Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4228 for (unsigned Part = 0; Part < UF; ++Part) {
4229 Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
4230 Value *Val = getOrCreateVectorValue(LoopVal, Part);
4231 // Make sure to add the reduction stat value only to the
4232 // first unroll part.
4233 Value *StartVal = (Part == 0) ? VectorStart : Identity;
4234 cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
4235 cast<PHINode>(VecRdxPhi)
4236 ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4237 }
4238
4239 // Before each round, move the insertion point right between
4240 // the PHIs and the values we are going to write.
4241 // This allows us to write both PHINodes and the extractelement
4242 // instructions.
4243 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4244
4245 setDebugLocFromInst(Builder, LoopExitInst);
4246
4247 // If the vector reduction can be performed in a smaller type, we truncate
4248 // then extend the loop exit value to enable InstCombine to evaluate the
4249 // entire expression in the smaller type.
4250 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
4251 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4252 Builder.SetInsertPoint(
4253 LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4254 VectorParts RdxParts(UF);
4255 for (unsigned Part = 0; Part < UF; ++Part) {
4256 RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4257 Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4258 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4259 : Builder.CreateZExt(Trunc, VecTy);
4260 for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4261 UI != RdxParts[Part]->user_end();)
4262 if (*UI != Trunc) {
4263 (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4264 RdxParts[Part] = Extnd;
4265 } else {
4266 ++UI;
4267 }
4268 }
4269 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4270 for (unsigned Part = 0; Part < UF; ++Part) {
4271 RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4272 VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
4273 }
4274 }
4275
4276 // Reduce all of the unrolled parts into a single vector.
4277 Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
4278 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
4279 setDebugLocFromInst(Builder, ReducedPartRdx);
4280 for (unsigned Part = 1; Part < UF; ++Part) {
4281 Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4282 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4283 // Floating point operations had to be 'fast' to enable the reduction.
4284 ReducedPartRdx = addFastMathFlag(
4285 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
4286 ReducedPartRdx, "bin.rdx"));
4287 else
4288 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
4289 Builder, MinMaxKind, ReducedPartRdx, RdxPart);
4290 }
4291
4292 if (VF > 1) {
4293 bool NoNaN = Legal->hasFunNoNaNAttr();
4294 ReducedPartRdx =
4295 createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
4296 // If the reduction can be performed in a smaller type, we need to extend
4297 // the reduction to the wider type before we branch to the original loop.
4298 if (Phi->getType() != RdxDesc.getRecurrenceType())
4299 ReducedPartRdx =
4300 RdxDesc.isSigned()
4301 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4302 : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4303 }
4304
4305 // Create a phi node that merges control-flow from the backedge-taken check
4306 // block and the middle block.
4307 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4308 LoopScalarPreHeader->getTerminator());
4309 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4310 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4311 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4312
4313 // Now, we need to fix the users of the reduction variable
4314 // inside and outside of the scalar remainder loop.
4315 // We know that the loop is in LCSSA form. We need to update the
4316 // PHI nodes in the exit blocks.
4317 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4318 // All PHINodes need to have a single entry edge, or two if
4319 // we already fixed them.
4320 assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI")(static_cast <bool> (LCSSAPhi.getNumIncomingValues() <
3 && "Invalid LCSSA PHI") ? void (0) : __assert_fail
("LCSSAPhi.getNumIncomingValues() < 3 && \"Invalid LCSSA PHI\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4320, __extension__ __PRETTY_FUNCTION__))
;
4321
4322 // We found a reduction value exit-PHI. Update it with the
4323 // incoming bypass edge.
4324 if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
4325 LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4326 } // end of the LCSSA phi scan.
4327
4328 // Fix the scalar loop reduction variable with the incoming reduction sum
4329 // from the vector body and from the backedge value.
4330 int IncomingEdgeBlockIdx =
4331 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4332 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index")(static_cast <bool> (IncomingEdgeBlockIdx >= 0 &&
"Invalid block index") ? void (0) : __assert_fail ("IncomingEdgeBlockIdx >= 0 && \"Invalid block index\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4332, __extension__ __PRETTY_FUNCTION__))
;
4333 // Pick the other block.
4334 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4335 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4336 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4337}
4338
4339void InnerLoopVectorizer::fixLCSSAPHIs() {
4340 for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4341 if (LCSSAPhi.getNumIncomingValues() == 1) {
4342 assert(OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) &&(static_cast <bool> (OrigLoop->isLoopInvariant(LCSSAPhi
.getIncomingValue(0)) && "Incoming value isn't loop invariant"
) ? void (0) : __assert_fail ("OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) && \"Incoming value isn't loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4343, __extension__ __PRETTY_FUNCTION__))
4343 "Incoming value isn't loop invariant")(static_cast <bool> (OrigLoop->isLoopInvariant(LCSSAPhi
.getIncomingValue(0)) && "Incoming value isn't loop invariant"
) ? void (0) : __assert_fail ("OrigLoop->isLoopInvariant(LCSSAPhi.getIncomingValue(0)) && \"Incoming value isn't loop invariant\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4343, __extension__ __PRETTY_FUNCTION__))
;
4344 LCSSAPhi.addIncoming(LCSSAPhi.getIncomingValue(0), LoopMiddleBlock);
4345 }
4346 }
4347}
4348
4349void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4350 // The basic block and loop containing the predicated instruction.
4351 auto *PredBB = PredInst->getParent();
4352 auto *VectorLoop = LI->getLoopFor(PredBB);
4353
4354 // Initialize a worklist with the operands of the predicated instruction.
4355 SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4356
4357 // Holds instructions that we need to analyze again. An instruction may be
4358 // reanalyzed if we don't yet know if we can sink it or not.
4359 SmallVector<Instruction *, 8> InstsToReanalyze;
4360
4361 // Returns true if a given use occurs in the predicated block. Phi nodes use
4362 // their operands in their corresponding predecessor blocks.
4363 auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4364 auto *I = cast<Instruction>(U.getUser());
4365 BasicBlock *BB = I->getParent();
4366 if (auto *Phi = dyn_cast<PHINode>(I))
4367 BB = Phi->getIncomingBlock(
4368 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4369 return BB == PredBB;
4370 };
4371
4372 // Iteratively sink the scalarized operands of the predicated instruction
4373 // into the block we created for it. When an instruction is sunk, it's
4374 // operands are then added to the worklist. The algorithm ends after one pass
4375 // through the worklist doesn't sink a single instruction.
4376 bool Changed;
4377 do {
4378 // Add the instructions that need to be reanalyzed to the worklist, and
4379 // reset the changed indicator.
4380 Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4381 InstsToReanalyze.clear();
4382 Changed = false;
4383
4384 while (!Worklist.empty()) {
4385 auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4386
4387 // We can't sink an instruction if it is a phi node, is already in the
4388 // predicated block, is not in the loop, or may have side effects.
4389 if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4390 !VectorLoop->contains(I) || I->mayHaveSideEffects())
4391 continue;
4392
4393 // It's legal to sink the instruction if all its uses occur in the
4394 // predicated block. Otherwise, there's nothing to do yet, and we may
4395 // need to reanalyze the instruction.
4396 if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4397 InstsToReanalyze.push_back(I);
4398 continue;
4399 }
4400
4401 // Move the instruction to the beginning of the predicated block, and add
4402 // it's operands to the worklist.
4403 I->moveBefore(&*PredBB->getFirstInsertionPt());
4404 Worklist.insert(I->op_begin(), I->op_end());
4405
4406 // The sinking may have enabled other instructions to be sunk, so we will
4407 // need to iterate.
4408 Changed = true;
4409 }
4410 } while (Changed);
4411}
4412
4413void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4414 unsigned VF) {
4415 assert(PN->getParent() == OrigLoop->getHeader() &&(static_cast <bool> (PN->getParent() == OrigLoop->
getHeader() && "Non-header phis should have been handled elsewhere"
) ? void (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4416, __extension__ __PRETTY_FUNCTION__))
4416 "Non-header phis should have been handled elsewhere")(static_cast <bool> (PN->getParent() == OrigLoop->
getHeader() && "Non-header phis should have been handled elsewhere"
) ? void (0) : __assert_fail ("PN->getParent() == OrigLoop->getHeader() && \"Non-header phis should have been handled elsewhere\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4416, __extension__ __PRETTY_FUNCTION__))
;
4417
4418 PHINode *P = cast<PHINode>(PN);
4419 // In order to support recurrences we need to be able to vectorize Phi nodes.
4420 // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4421 // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4422 // this value when we vectorize all of the instructions that use the PHI.
4423 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4424 for (unsigned Part = 0; Part < UF; ++Part) {
4425 // This is phase one of vectorizing PHIs.
4426 Type *VecTy =
4427 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4428 Value *EntryPart = PHINode::Create(
4429 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4430 VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4431 }
4432 return;
4433 }
4434
4435 setDebugLocFromInst(Builder, P);
4436
4437 // This PHINode must be an induction variable.
4438 // Make sure that we know about it.
4439 assert(Legal->getInductionVars()->count(P) && "Not an induction variable")(static_cast <bool> (Legal->getInductionVars()->count
(P) && "Not an induction variable") ? void (0) : __assert_fail
("Legal->getInductionVars()->count(P) && \"Not an induction variable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4439, __extension__ __PRETTY_FUNCTION__))
;
4440
4441 InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4442 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4443
4444 // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4445 // which can be found from the original scalar operations.
4446 switch (II.getKind()) {
4447 case InductionDescriptor::IK_NoInduction:
4448 llvm_unreachable("Unknown induction")::llvm::llvm_unreachable_internal("Unknown induction", "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4448)
;
4449 case InductionDescriptor::IK_IntInduction:
4450 case InductionDescriptor::IK_FpInduction:
4451 llvm_unreachable("Integer/fp induction is handled elsewhere.")::llvm::llvm_unreachable_internal("Integer/fp induction is handled elsewhere."
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4451)
;
4452 case InductionDescriptor::IK_PtrInduction: {
4453 // Handle the pointer induction variable case.
4454 assert(P->getType()->isPointerTy() && "Unexpected type.")(static_cast <bool> (P->getType()->isPointerTy() &&
"Unexpected type.") ? void (0) : __assert_fail ("P->getType()->isPointerTy() && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4454, __extension__ __PRETTY_FUNCTION__))
;
4455 // This is the normalized GEP that starts counting at zero.
4456 Value *PtrInd = Induction;
4457 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4458 // Determine the number of scalars we need to generate for each unroll
4459 // iteration. If the instruction is uniform, we only need to generate the
4460 // first lane. Otherwise, we generate all VF values.
4461 unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4462 // These are the scalar results. Notice that we don't generate vector GEPs
4463 // because scalar GEPs result in better code.
4464 for (unsigned Part = 0; Part < UF; ++Part) {
4465 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4466 Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4467 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4468 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4469 SclrGep->setName("next.gep");
4470 VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
4471 }
4472 }
4473 return;
4474 }
4475 }
4476}
4477
4478/// A helper function for checking whether an integer division-related
4479/// instruction may divide by zero (in which case it must be predicated if
4480/// executed conditionally in the scalar code).
4481/// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4482/// Non-zero divisors that are non compile-time constants will not be
4483/// converted into multiplication, so we will still end up scalarizing
4484/// the division, but can do so w/o predication.
4485static bool mayDivideByZero(Instruction &I) {
4486 assert((I.getOpcode() == Instruction::UDiv ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4487 I.getOpcode() == Instruction::SDiv ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4488 I.getOpcode() == Instruction::URem ||(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4489 I.getOpcode() == Instruction::SRem) &&(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
4490 "Unexpected instruction")(static_cast <bool> ((I.getOpcode() == Instruction::UDiv
|| I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction
::URem || I.getOpcode() == Instruction::SRem) && "Unexpected instruction"
) ? void (0) : __assert_fail ("(I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::URem || I.getOpcode() == Instruction::SRem) && \"Unexpected instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4490, __extension__ __PRETTY_FUNCTION__))
;
4491 Value *Divisor = I.getOperand(1);
4492 auto *CInt = dyn_cast<ConstantInt>(Divisor);
4493 return !CInt || CInt->isZero();
4494}
4495
4496void InnerLoopVectorizer::widenInstruction(Instruction &I) {
4497 switch (I.getOpcode()) {
4498 case Instruction::Br:
4499 case Instruction::PHI:
4500 llvm_unreachable("This instruction is handled by a different recipe.")::llvm::llvm_unreachable_internal("This instruction is handled by a different recipe."
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4500)
;
4501 case Instruction::GetElementPtr: {
4502 // Construct a vector GEP by widening the operands of the scalar GEP as
4503 // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4504 // results in a vector of pointers when at least one operand of the GEP
4505 // is vector-typed. Thus, to keep the representation compact, we only use
4506 // vector-typed operands for loop-varying values.
4507 auto *GEP = cast<GetElementPtrInst>(&I);
4508
4509 if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
4510 // If we are vectorizing, but the GEP has only loop-invariant operands,
4511 // the GEP we build (by only using vector-typed operands for
4512 // loop-varying values) would be a scalar pointer. Thus, to ensure we
4513 // produce a vector of pointers, we need to either arbitrarily pick an
4514 // operand to broadcast, or broadcast a clone of the original GEP.
4515 // Here, we broadcast a clone of the original.
4516 //
4517 // TODO: If at some point we decide to scalarize instructions having
4518 // loop-invariant operands, this special case will no longer be
4519 // required. We would add the scalarization decision to
4520 // collectLoopScalars() and teach getVectorValue() to broadcast
4521 // the lane-zero scalar value.
4522 auto *Clone = Builder.Insert(GEP->clone());
4523 for (unsigned Part = 0; Part < UF; ++Part) {
4524 Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4525 VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
4526 addMetadata(EntryPart, GEP);
4527 }
4528 } else {
4529 // If the GEP has at least one loop-varying operand, we are sure to
4530 // produce a vector of pointers. But if we are only unrolling, we want
4531 // to produce a scalar GEP for each unroll part. Thus, the GEP we
4532 // produce with the code below will be scalar (if VF == 1) or vector
4533 // (otherwise). Note that for the unroll-only case, we still maintain
4534 // values in the vector mapping with initVector, as we do for other
4535 // instructions.
4536 for (unsigned Part = 0; Part < UF; ++Part) {
4537 // The pointer operand of the new GEP. If it's loop-invariant, we
4538 // won't broadcast it.
4539 auto *Ptr =
4540 OrigLoop->isLoopInvariant(GEP->getPointerOperand())
4541 ? GEP->getPointerOperand()
4542 : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
4543
4544 // Collect all the indices for the new GEP. If any index is
4545 // loop-invariant, we won't broadcast it.
4546 SmallVector<Value *, 4> Indices;
4547 for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
4548 if (OrigLoop->isLoopInvariant(U.get()))
4549 Indices.push_back(U.get());
4550 else
4551 Indices.push_back(getOrCreateVectorValue(U.get(), Part));
4552 }
4553
4554 // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4555 // but it should be a vector, otherwise.
4556 auto *NewGEP = GEP->isInBounds()
4557 ? Builder.CreateInBoundsGEP(Ptr, Indices)
4558 : Builder.CreateGEP(Ptr, Indices);
4559 assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&(static_cast <bool> ((VF == 1 || NewGEP->getType()->
isVectorTy()) && "NewGEP is not a pointer vector") ? void
(0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4560, __extension__ __PRETTY_FUNCTION__))
4560 "NewGEP is not a pointer vector")(static_cast <bool> ((VF == 1 || NewGEP->getType()->
isVectorTy()) && "NewGEP is not a pointer vector") ? void
(0) : __assert_fail ("(VF == 1 || NewGEP->getType()->isVectorTy()) && \"NewGEP is not a pointer vector\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4560, __extension__ __PRETTY_FUNCTION__))
;
4561 VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
4562 addMetadata(NewGEP, GEP);
4563 }
4564 }
4565
4566 break;
4567 }
4568 case Instruction::UDiv:
4569 case Instruction::SDiv:
4570 case Instruction::SRem:
4571 case Instruction::URem:
4572 case Instruction::Add:
4573 case Instruction::FAdd:
4574 case Instruction::Sub:
4575 case Instruction::FSub:
4576 case Instruction::Mul:
4577 case Instruction::FMul:
4578 case Instruction::FDiv:
4579 case Instruction::FRem:
4580 case Instruction::Shl:
4581 case Instruction::LShr:
4582 case Instruction::AShr:
4583 case Instruction::And:
4584 case Instruction::Or:
4585 case Instruction::Xor: {
4586 // Just widen binops.
4587 auto *BinOp = cast<BinaryOperator>(&I);
4588 setDebugLocFromInst(Builder, BinOp);
4589
4590 for (unsigned Part = 0; Part < UF; ++Part) {
4591 Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
4592 Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
4593 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
4594
4595 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4596 VecOp->copyIRFlags(BinOp);
4597
4598 // Use this vector value for all users of the original instruction.
4599 VectorLoopValueMap.setVectorValue(&I, Part, V);
4600 addMetadata(V, BinOp);
4601 }
4602
4603 break;
4604 }
4605 case Instruction::Select: {
4606 // Widen selects.
4607 // If the selector is loop invariant we can create a select
4608 // instruction with a scalar condition. Otherwise, use vector-select.
4609 auto *SE = PSE.getSE();
4610 bool InvariantCond =
4611 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4612 setDebugLocFromInst(Builder, &I);
4613
4614 // The condition can be loop invariant but still defined inside the
4615 // loop. This means that we can't just use the original 'cond' value.
4616 // We have to take the 'vectorized' value and pick the first lane.
4617 // Instcombine will make this a no-op.
4618
4619 auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
4620
4621 for (unsigned Part = 0; Part < UF; ++Part) {
4622 Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
4623 Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
4624 Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
4625 Value *Sel =
4626 Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
4627 VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4628 addMetadata(Sel, &I);
4629 }
4630
4631 break;
4632 }
4633
4634 case Instruction::ICmp:
4635 case Instruction::FCmp: {
4636 // Widen compares. Generate vector compares.
4637 bool FCmp = (I.getOpcode() == Instruction::FCmp);
4638 auto *Cmp = dyn_cast<CmpInst>(&I);
4639 setDebugLocFromInst(Builder, Cmp);
4640 for (unsigned Part = 0; Part < UF; ++Part) {
4641 Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
4642 Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
4643 Value *C = nullptr;
4644 if (FCmp) {
4645 // Propagate fast math flags.
4646 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4647 Builder.setFastMathFlags(Cmp->getFastMathFlags());
4648 C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4649 } else {
4650 C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4651 }
4652 VectorLoopValueMap.setVectorValue(&I, Part, C);
4653 addMetadata(C, &I);
4654 }
4655
4656 break;
4657 }
4658
4659 case Instruction::ZExt:
4660 case Instruction::SExt:
4661 case Instruction::FPToUI:
4662 case Instruction::FPToSI:
4663 case Instruction::FPExt:
4664 case Instruction::PtrToInt:
4665 case Instruction::IntToPtr:
4666 case Instruction::SIToFP:
4667 case Instruction::UIToFP:
4668 case Instruction::Trunc:
4669 case Instruction::FPTrunc:
4670 case Instruction::BitCast: {
4671 auto *CI = dyn_cast<CastInst>(&I);
4672 setDebugLocFromInst(Builder, CI);
4673
4674 /// Vectorize casts.
4675 Type *DestTy =
4676 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4677
4678 for (unsigned Part = 0; Part < UF; ++Part) {
4679 Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
4680 Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4681 VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4682 addMetadata(Cast, &I);
4683 }
4684 break;
4685 }
4686
4687 case Instruction::Call: {
4688 // Ignore dbg intrinsics.
4689 if (isa<DbgInfoIntrinsic>(I))
4690 break;
4691 setDebugLocFromInst(Builder, &I);
4692
4693 Module *M = I.getParent()->getParent()->getParent();
4694 auto *CI = cast<CallInst>(&I);
4695
4696 StringRef FnName = CI->getCalledFunction()->getName();
4697 Function *F = CI->getCalledFunction();
4698 Type *RetTy = ToVectorTy(CI->getType(), VF);
4699 SmallVector<Type *, 4> Tys;
4700 for (Value *ArgOperand : CI->arg_operands())
4701 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4702
4703 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4704
4705 // The flag shows whether we use Intrinsic or a usual Call for vectorized
4706 // version of the instruction.
4707 // Is it beneficial to perform intrinsic call compared to lib call?
4708 bool NeedToScalarize;
4709 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4710 bool UseVectorIntrinsic =
4711 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4712 assert((UseVectorIntrinsic || !NeedToScalarize) &&(static_cast <bool> ((UseVectorIntrinsic || !NeedToScalarize
) && "Instruction should be scalarized elsewhere.") ?
void (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4713, __extension__ __PRETTY_FUNCTION__))
4713 "Instruction should be scalarized elsewhere.")(static_cast <bool> ((UseVectorIntrinsic || !NeedToScalarize
) && "Instruction should be scalarized elsewhere.") ?
void (0) : __assert_fail ("(UseVectorIntrinsic || !NeedToScalarize) && \"Instruction should be scalarized elsewhere.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4713, __extension__ __PRETTY_FUNCTION__))
;
4714
4715 for (unsigned Part = 0; Part < UF; ++Part) {
4716 SmallVector<Value *, 4> Args;
4717 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4718 Value *Arg = CI->getArgOperand(i);
4719 // Some intrinsics have a scalar argument - don't replace it with a
4720 // vector.
4721 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
4722 Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
4723 Args.push_back(Arg);
4724 }
4725
4726 Function *VectorF;
4727 if (UseVectorIntrinsic) {
4728 // Use vector version of the intrinsic.
4729 Type *TysForDecl[] = {CI->getType()};
4730 if (VF > 1)
4731 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4732 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4733 } else {
4734 // Use vector version of the library call.
4735 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4736 assert(!VFnName.empty() && "Vector function name is empty.")(static_cast <bool> (!VFnName.empty() && "Vector function name is empty."
) ? void (0) : __assert_fail ("!VFnName.empty() && \"Vector function name is empty.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4736, __extension__ __PRETTY_FUNCTION__))
;
4737 VectorF = M->getFunction(VFnName);
4738 if (!VectorF) {
4739 // Generate a declaration
4740 FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4741 VectorF =
4742 Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4743 VectorF->copyAttributesFrom(F);
4744 }
4745 }
4746 assert(VectorF && "Can't create vector function.")(static_cast <bool> (VectorF && "Can't create vector function."
) ? void (0) : __assert_fail ("VectorF && \"Can't create vector function.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4746, __extension__ __PRETTY_FUNCTION__))
;
4747
4748 SmallVector<OperandBundleDef, 1> OpBundles;
4749 CI->getOperandBundlesAsDefs(OpBundles);
4750 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4751
4752 if (isa<FPMathOperator>(V))
4753 V->copyFastMathFlags(CI);
4754
4755 VectorLoopValueMap.setVectorValue(&I, Part, V);
4756 addMetadata(V, &I);
4757 }
4758
4759 break;
4760 }
4761
4762 default:
4763 // This instruction is not vectorized by simple widening.
4764 DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an unhandled instruction: "
<< I; } } while (false)
;
4765 llvm_unreachable("Unhandled instruction!")::llvm::llvm_unreachable_internal("Unhandled instruction!", "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4765)
;
4766 } // end of switch.
4767}
4768
4769void InnerLoopVectorizer::updateAnalysis() {
4770 // Forget the original basic block.
4771 PSE.getSE()->forgetLoop(OrigLoop);
4772
4773 // Update the dominator tree information.
4774 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&(static_cast <bool> (DT->properlyDominates(LoopBypassBlocks
.front(), LoopExitBlock) && "Entry does not dominate exit."
) ? void (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4775, __extension__ __PRETTY_FUNCTION__))
4775 "Entry does not dominate exit.")(static_cast <bool> (DT->properlyDominates(LoopBypassBlocks
.front(), LoopExitBlock) && "Entry does not dominate exit."
) ? void (0) : __assert_fail ("DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && \"Entry does not dominate exit.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4775, __extension__ __PRETTY_FUNCTION__))
;
4776
4777 DT->addNewBlock(LoopMiddleBlock,
4778 LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4779 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
4780 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
4781 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
4782 assert(DT->verify(DominatorTree::VerificationLevel::Fast))(static_cast <bool> (DT->verify(DominatorTree::VerificationLevel
::Fast)) ? void (0) : __assert_fail ("DT->verify(DominatorTree::VerificationLevel::Fast)"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4782, __extension__ __PRETTY_FUNCTION__))
;
4783}
4784
4785/// \brief Check whether it is safe to if-convert this phi node.
4786///
4787/// Phi nodes with constant expressions that can trap are not safe to if
4788/// convert.
4789static bool canIfConvertPHINodes(BasicBlock *BB) {
4790 for (PHINode &Phi : BB->phis()) {
4791 for (Value *V : Phi.incoming_values())
4792 if (auto *C = dyn_cast<Constant>(V))
4793 if (C->canTrap())
4794 return false;
4795 }
4796 return true;
4797}
4798
4799bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
4800 if (!EnableIfConversion) {
4801 ORE->emit(createMissedAnalysis("IfConversionDisabled")
4802 << "if-conversion is disabled");
4803 return false;
4804 }
4805
4806 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable")(static_cast <bool> (TheLoop->getNumBlocks() > 1 &&
"Single block loops are vectorizable") ? void (0) : __assert_fail
("TheLoop->getNumBlocks() > 1 && \"Single block loops are vectorizable\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 4806, __extension__ __PRETTY_FUNCTION__))
;
4807
4808 // A list of pointers that we can safely read and write to.
4809 SmallPtrSet<Value *, 8> SafePointes;
4810
4811 // Collect safe addresses.
4812 for (BasicBlock *BB : TheLoop->blocks()) {
4813 if (blockNeedsPredication(BB))
4814 continue;
4815
4816 for (Instruction &I : *BB)
4817 if (auto *Ptr = getPointerOperand(&I))
4818 SafePointes.insert(Ptr);
4819 }
4820
4821 // Collect the blocks that need predication.
4822 BasicBlock *Header = TheLoop->getHeader();
4823 for (BasicBlock *BB : TheLoop->blocks()) {
4824 // We don't support switch statements inside loops.
4825 if (!isa<BranchInst>(BB->getTerminator())) {
4826 ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
4827 << "loop contains a switch statement");
4828 return false;
4829 }
4830
4831 // We must be able to predicate all blocks that need to be predicated.
4832 if (blockNeedsPredication(BB)) {
4833 if (!blockCanBePredicated(BB, SafePointes)) {
4834 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4835 << "control flow cannot be substituted for a select");
4836 return false;
4837 }
4838 } else if (BB != Header && !canIfConvertPHINodes(BB)) {
4839 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
4840 << "control flow cannot be substituted for a select");
4841 return false;
4842 }
4843 }
4844
4845 // We can if-convert this loop.
4846 return true;
4847}
4848
4849bool LoopVectorizationLegality::canVectorize() {
4850 // Store the result and return it at the end instead of exiting early, in case
4851 // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
4852 bool Result = true;
4853
4854 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE"loop-vectorize");
4855 // We must have a loop in canonical form. Loops with indirectbr in them cannot
4856 // be canonicalized.
4857 if (!TheLoop->getLoopPreheader()) {
4858 DEBUG(dbgs() << "LV: Loop doesn't have a legal pre-header.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Loop doesn't have a legal pre-header.\n"
; } } while (false)
;
4859 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4860 << "loop control flow is not understood by vectorizer");
4861 if (DoExtraAnalysis)
4862 Result = false;
4863 else
4864 return false;
4865 }
4866
4867 // FIXME: The code is currently dead, since the loop gets sent to
4868 // LoopVectorizationLegality is already an innermost loop.
4869 //
4870 // We can only vectorize innermost loops.
4871 if (!TheLoop->empty()) {
4872 ORE->emit(createMissedAnalysis("NotInnermostLoop")
4873 << "loop is not the innermost loop");
4874 if (DoExtraAnalysis)
4875 Result = false;
4876 else
4877 return false;
4878 }
4879
4880 // We must have a single backedge.
4881 if (TheLoop->getNumBackEdges() != 1) {
4882 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4883 << "loop control flow is not understood by vectorizer");
4884 if (DoExtraAnalysis)
4885 Result = false;
4886 else
4887 return false;
4888 }
4889
4890 // We must have a single exiting block.
4891 if (!TheLoop->getExitingBlock()) {
4892 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4893 << "loop control flow is not understood by vectorizer");
4894 if (DoExtraAnalysis)
4895 Result = false;
4896 else
4897 return false;
4898 }
4899
4900 // We only handle bottom-tested loops, i.e. loop in which the condition is
4901 // checked at the end of each iteration. With that we can assume that all
4902 // instructions in the loop are executed the same number of times.
4903 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
4904 ORE->emit(createMissedAnalysis("CFGNotUnderstood")
4905 << "loop control flow is not understood by vectorizer");
4906 if (DoExtraAnalysis)
4907 Result = false;
4908 else
4909 return false;
4910 }
4911
4912 // We need to have a loop header.
4913 DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop: " <<
TheLoop->getHeader()->getName() << '\n'; } } while
(false)
4914 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a loop: " <<
TheLoop->getHeader()->getName() << '\n'; } } while
(false)
;
4915
4916 // Check if we can if-convert non-single-bb loops.
4917 unsigned NumBlocks = TheLoop->getNumBlocks();
4918 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
4919 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't if-convert the loop.\n"
; } } while (false)
;
4920 if (DoExtraAnalysis)
4921 Result = false;
4922 else
4923 return false;
4924 }
4925
4926 // Check if we can vectorize the instructions and CFG in this loop.
4927 if (!canVectorizeInstrs()) {
4928 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't vectorize the instructions or CFG\n"
; } } while (false)
;
4929 if (DoExtraAnalysis)
4930 Result = false;
4931 else
4932 return false;
4933 }
4934
4935 // Go over each instruction and look at memory deps.
4936 if (!canVectorizeMemory()) {
4937 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Can't vectorize due to memory conflicts\n"
; } } while (false)
;
4938 if (DoExtraAnalysis)
4939 Result = false;
4940 else
4941 return false;
4942 }
4943
4944 DEBUG(dbgs() << "LV: We can vectorize this loop"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4945 << (LAI->getRuntimePointerChecking()->Needdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4946 ? " (with a runtime bound check)"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4947 : "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
4948 << "!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We can vectorize this loop"
<< (LAI->getRuntimePointerChecking()->Need ? " (with a runtime bound check)"
: "") << "!\n"; } } while (false)
;
4949
4950 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
4951
4952 // If an override option has been passed in for interleaved accesses, use it.
4953 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
4954 UseInterleaved = EnableInterleavedMemAccesses;
4955
4956 // Analyze interleaved memory accesses.
4957 if (UseInterleaved)
4958 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
4959
4960 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
4961 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
4962 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
4963
4964 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
4965 ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
4966 << "Too many SCEV assumptions need to be made and checked "
4967 << "at runtime");
4968 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Too many SCEV checks needed.\n"
; } } while (false)
;
4969 if (DoExtraAnalysis)
4970 Result = false;
4971 else
4972 return false;
4973 }
4974
4975 // Okay! We've done all the tests. If any have failed, return false. Otherwise
4976 // we can vectorize, and at this point we don't have any other mem analysis
4977 // which may limit our maximum vectorization factor, so just return true with
4978 // no restrictions.
4979 return Result;
4980}
4981
4982static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
4983 if (Ty->isPointerTy())
4984 return DL.getIntPtrType(Ty);
4985
4986 // It is possible that char's or short's overflow when we ask for the loop's
4987 // trip count, work around this by changing the type size.
4988 if (Ty->getScalarSizeInBits() < 32)
4989 return Type::getInt32Ty(Ty->getContext());
4990
4991 return Ty;
4992}
4993
4994static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
4995 Ty0 = convertPointerToIntegerType(DL, Ty0);
4996 Ty1 = convertPointerToIntegerType(DL, Ty1);
4997 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
4998 return Ty0;
4999 return Ty1;
5000}
5001
5002/// \brief Check that the instruction has outside loop users and is not an
5003/// identified reduction variable.
5004static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5005 SmallPtrSetImpl<Value *> &AllowedExit) {
5006 // Reduction and Induction instructions are allowed to have exit users. All
5007 // other instructions must not have external users.
5008 if (!AllowedExit.count(Inst))
5009 // Check that all of the users of the loop are inside the BB.
5010 for (User *U : Inst->users()) {
5011 Instruction *UI = cast<Instruction>(U);
5012 // This user may be a reduction exit value.
5013 if (!TheLoop->contains(UI)) {
5014 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an outside user for : "
<< *UI << '\n'; } } while (false)
;
5015 return true;
5016 }
5017 }
5018 return false;
5019}
5020
5021void LoopVectorizationLegality::addInductionPhi(
5022 PHINode *Phi, const InductionDescriptor &ID,
5023 SmallPtrSetImpl<Value *> &AllowedExit) {
5024 Inductions[Phi] = ID;
5025
5026 // In case this induction also comes with casts that we know we can ignore
5027 // in the vectorized loop body, record them here. All casts could be recorded
5028 // here for ignoring, but suffices to record only the first (as it is the
5029 // only one that may bw used outside the cast sequence).
5030 const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
5031 if (!Casts.empty())
5032 InductionCastsToIgnore.insert(*Casts.begin());
5033
5034 Type *PhiTy = Phi->getType();
5035 const DataLayout &DL = Phi->getModule()->getDataLayout();
5036
5037 // Get the widest type.
5038 if (!PhiTy->isFloatingPointTy()) {
5039 if (!WidestIndTy)
5040 WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5041 else
5042 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5043 }
5044
5045 // Int inductions are special because we only allow one IV.
5046 if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
5047 ID.getConstIntStepValue() &&
5048 ID.getConstIntStepValue()->isOne() &&
5049 isa<Constant>(ID.getStartValue()) &&
5050 cast<Constant>(ID.getStartValue())->isNullValue()) {
5051
5052 // Use the phi node with the widest type as induction. Use the last
5053 // one if there are multiple (no good reason for doing this other
5054 // than it is expedient). We've checked that it begins at zero and
5055 // steps by one, so this is a canonical induction variable.
5056 if (!PrimaryInduction || PhiTy == WidestIndTy)
5057 PrimaryInduction = Phi;
5058 }
5059
5060 // Both the PHI node itself, and the "post-increment" value feeding
5061 // back into the PHI node may have external users.
5062 // We can allow those uses, except if the SCEVs we have for them rely
5063 // on predicates that only hold within the loop, since allowing the exit
5064 // currently means re-using this SCEV outside the loop.
5065 if (PSE.getUnionPredicate().isAlwaysTrue()) {
5066 AllowedExit.insert(Phi);
5067 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5068 }
5069
5070 DEBUG(dbgs() << "LV: Found an induction variable.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an induction variable.\n"
; } } while (false)
;
5071}
5072
5073bool LoopVectorizationLegality::canVectorizeInstrs() {
5074 BasicBlock *Header = TheLoop->getHeader();
5075
5076 // Look for the attribute signaling the absence of NaNs.
5077 Function &F = *Header->getParent();
5078 HasFunNoNaNAttr =
5079 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5080
5081 // For each block in the loop.
5082 for (BasicBlock *BB : TheLoop->blocks()) {
5083 // Scan the instructions in the block and look for hazards.
5084 for (Instruction &I : *BB) {
5085 if (auto *Phi = dyn_cast<PHINode>(&I)) {
5086 Type *PhiTy = Phi->getType();
5087 // Check that this PHI type is allowed.
5088 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5089 !PhiTy->isPointerTy()) {
5090 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5091 << "loop control flow is not understood by vectorizer");
5092 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an non-int non-pointer PHI.\n"
; } } while (false)
;
5093 return false;
5094 }
5095
5096 // If this PHINode is not in the header block, then we know that we
5097 // can convert it to select during if-conversion. No need to check if
5098 // the PHIs in this block are induction or reduction variables.
5099 if (BB != Header) {
5100 // Check that this instruction has no outside users or is an
5101 // identified reduction value with an outside user.
5102 if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5103 continue;
5104 ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5105 << "value could not be identified as "
5106 "an induction or reduction variable");
5107 return false;
5108 }
5109
5110 // We only allow if-converted PHIs with exactly two incoming values.
5111 if (Phi->getNumIncomingValues() != 2) {
5112 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5113 << "control flow not understood by vectorizer");
5114 DEBUG(dbgs() << "LV: Found an invalid PHI.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an invalid PHI.\n"
; } } while (false)
;
5115 return false;
5116 }
5117
5118 RecurrenceDescriptor RedDes;
5119 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC,
5120 DT)) {
5121 if (RedDes.hasUnsafeAlgebra())
5122 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5123 AllowedExit.insert(RedDes.getLoopExitInstr());
5124 Reductions[Phi] = RedDes;
5125 continue;
5126 }
5127
5128 InductionDescriptor ID;
5129 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5130 addInductionPhi(Phi, ID, AllowedExit);
5131 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5132 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5133 continue;
5134 }
5135
5136 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop,
5137 SinkAfter, DT)) {
5138 FirstOrderRecurrences.insert(Phi);
5139 continue;
5140 }
5141
5142 // As a last resort, coerce the PHI to a AddRec expression
5143 // and re-try classifying it a an induction PHI.
5144 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5145 addInductionPhi(Phi, ID, AllowedExit);
5146 continue;
5147 }
5148
5149 ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5150 << "value that could not be identified as "
5151 "reduction is used outside the loop");
5152 DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found an unidentified PHI."
<< *Phi << "\n"; } } while (false)
;
5153 return false;
5154 } // end of PHI handling
5155
5156 // We handle calls that:
5157 // * Are debug info intrinsics.
5158 // * Have a mapping to an IR intrinsic.
5159 // * Have a vector version available.
5160 auto *CI = dyn_cast<CallInst>(&I);
5161 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5162 !isa<DbgInfoIntrinsic>(CI) &&
5163 !(CI->getCalledFunction() && TLI &&
5164 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5165 ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5166 << "call instruction cannot be vectorized");
5167 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n"
; } } while (false)
;
5168 return false;
5169 }
5170
5171 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5172 // second argument is the same (i.e. loop invariant)
5173 if (CI && hasVectorInstrinsicScalarOpd(
5174 getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5175 auto *SE = PSE.getSE();
5176 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5177 ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5178 << "intrinsic instruction cannot be vectorized");
5179 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found unvectorizable intrinsic "
<< *CI << "\n"; } } while (false)
;
5180 return false;
5181 }
5182 }
5183
5184 // Check that the instruction return type is vectorizable.
5185 // Also, we can't vectorize extractelement instructions.
5186 if ((!VectorType::isValidElementType(I.getType()) &&
5187 !I.getType()->isVoidTy()) ||
5188 isa<ExtractElementInst>(I)) {
5189 ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5190 << "instruction return type cannot be vectorized");
5191 DEBUG(dbgs() << "LV: Found unvectorizable type.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found unvectorizable type.\n"
; } } while (false)
;
5192 return false;
5193 }
5194
5195 // Check that the stored type is vectorizable.
5196 if (auto *ST = dyn_cast<StoreInst>(&I)) {
5197 Type *T = ST->getValueOperand()->getType();
5198 if (!VectorType::isValidElementType(T)) {
5199 ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5200 << "store instruction cannot be vectorized");
5201 return false;
5202 }
5203
5204 // FP instructions can allow unsafe algebra, thus vectorizable by
5205 // non-IEEE-754 compliant SIMD units.
5206 // This applies to floating-point math operations and calls, not memory
5207 // operations, shuffles, or casts, as they don't change precision or
5208 // semantics.
5209 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5210 !I.isFast()) {
5211 DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found FP op with unsafe algebra.\n"
; } } while (false)
;
5212 Hints->setPotentiallyUnsafe();
5213 }
5214
5215 // Reduction instructions are allowed to have exit users.
5216 // All other instructions must not have external users.
5217 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5218 ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5219 << "value cannot be used outside the loop");
5220 return false;
5221 }
5222 } // next instr.
5223 }
5224
5225 if (!PrimaryInduction) {
5226 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Did not find one integer induction var.\n"
; } } while (false)
;
5227 if (Inductions.empty()) {
5228 ORE->emit(createMissedAnalysis("NoInductionVariable")
5229 << "loop induction variable could not be identified");
5230 return false;
5231 }
5232 }
5233
5234 // Now we know the widest induction type, check if our found induction
5235 // is the same size. If it's not, unset it here and InnerLoopVectorizer
5236 // will create another.
5237 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5238 PrimaryInduction = nullptr;
5239
5240 return true;
5241}
5242
5243void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5244 // We should not collect Scalars more than once per VF. Right now, this
5245 // function is called from collectUniformsAndScalars(), which already does
5246 // this check. Collecting Scalars for VF=1 does not make any sense.
5247 assert(VF >= 2 && !Scalars.count(VF) &&(static_cast <bool> (VF >= 2 && !Scalars.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Scalars.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5248, __extension__ __PRETTY_FUNCTION__))
5248 "This function should not be visited twice for the same VF")(static_cast <bool> (VF >= 2 && !Scalars.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Scalars.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5248, __extension__ __PRETTY_FUNCTION__))
;
5249
5250 SmallSetVector<Instruction *, 8> Worklist;
5251
5252 // These sets are used to seed the analysis with pointers used by memory
5253 // accesses that will remain scalar.
5254 SmallSetVector<Instruction *, 8> ScalarPtrs;
5255 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5256
5257 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5258 // The pointer operands of loads and stores will be scalar as long as the
5259 // memory access is not a gather or scatter operation. The value operand of a
5260 // store will remain scalar if the store is scalarized.
5261 auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5262 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5263 assert(WideningDecision != CM_Unknown &&(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5264, __extension__ __PRETTY_FUNCTION__))
5264 "Widening decision should be ready at this moment")(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5264, __extension__ __PRETTY_FUNCTION__))
;
5265 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5266 if (Ptr == Store->getValueOperand())
5267 return WideningDecision == CM_Scalarize;
5268 assert(Ptr == getPointerOperand(MemAccess) &&(static_cast <bool> (Ptr == getPointerOperand(MemAccess
) && "Ptr is neither a value or pointer operand") ? void
(0) : __assert_fail ("Ptr == getPointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5269, __extension__ __PRETTY_FUNCTION__))
5269 "Ptr is neither a value or pointer operand")(static_cast <bool> (Ptr == getPointerOperand(MemAccess
) && "Ptr is neither a value or pointer operand") ? void
(0) : __assert_fail ("Ptr == getPointerOperand(MemAccess) && \"Ptr is neither a value or pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5269, __extension__ __PRETTY_FUNCTION__))
;
5270 return WideningDecision != CM_GatherScatter;
5271 };
5272
5273 // A helper that returns true if the given value is a bitcast or
5274 // getelementptr instruction contained in the loop.
5275 auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5276 return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5277 isa<GetElementPtrInst>(V)) &&
5278 !TheLoop->isLoopInvariant(V);
5279 };
5280
5281 // A helper that evaluates a memory access's use of a pointer. If the use
5282 // will be a scalar use, and the pointer is only used by memory accesses, we
5283 // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
5284 // PossibleNonScalarPtrs.
5285 auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5286 // We only care about bitcast and getelementptr instructions contained in
5287 // the loop.
5288 if (!isLoopVaryingBitCastOrGEP(Ptr))
5289 return;
5290
5291 // If the pointer has already been identified as scalar (e.g., if it was
5292 // also identified as uniform), there's nothing to do.
5293 auto *I = cast<Instruction>(Ptr);
5294 if (Worklist.count(I))
5295 return;
5296
5297 // If the use of the pointer will be a scalar use, and all users of the
5298 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5299 // place the pointer in PossibleNonScalarPtrs.
5300 if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5301 return isa<LoadInst>(U) || isa<StoreInst>(U);
5302 }))
5303 ScalarPtrs.insert(I);
5304 else
5305 PossibleNonScalarPtrs.insert(I);
5306 };
5307
5308 // We seed the scalars analysis with three classes of instructions: (1)
5309 // instructions marked uniform-after-vectorization, (2) bitcast and
5310 // getelementptr instructions used by memory accesses requiring a scalar use,
5311 // and (3) pointer induction variables and their update instructions (we
5312 // currently only scalarize these).
5313 //
5314 // (1) Add to the worklist all instructions that have been identified as
5315 // uniform-after-vectorization.
5316 Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5317
5318 // (2) Add to the worklist all bitcast and getelementptr instructions used by
5319 // memory accesses requiring a scalar use. The pointer operands of loads and
5320 // stores will be scalar as long as the memory accesses is not a gather or
5321 // scatter operation. The value operand of a store will remain scalar if the
5322 // store is scalarized.
5323 for (auto *BB : TheLoop->blocks())
5324 for (auto &I : *BB) {
5325 if (auto *Load = dyn_cast<LoadInst>(&I)) {
5326 evaluatePtrUse(Load, Load->getPointerOperand());
5327 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5328 evaluatePtrUse(Store, Store->getPointerOperand());
5329 evaluatePtrUse(Store, Store->getValueOperand());
5330 }
5331 }
5332 for (auto *I : ScalarPtrs)
5333 if (!PossibleNonScalarPtrs.count(I)) {
5334 DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *I << "\n"; } } while (false)
;
5335 Worklist.insert(I);
5336 }
5337
5338 // (3) Add to the worklist all pointer induction variables and their update
5339 // instructions.
5340 //
5341 // TODO: Once we are able to vectorize pointer induction variables we should
5342 // no longer insert them into the worklist here.
5343 auto *Latch = TheLoop->getLoopLatch();
5344 for (auto &Induction : *Legal->getInductionVars()) {
5345 auto *Ind = Induction.first;
5346 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5347 if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
5348 continue;
5349 Worklist.insert(Ind);
5350 Worklist.insert(IndUpdate);
5351 DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *Ind << "\n"; } } while (false)
;
5352 DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
5353 }
5354
5355 // Insert the forced scalars.
5356 // FIXME: Currently widenPHIInstruction() often creates a dead vector
5357 // induction variable when the PHI user is scalarized.
5358 if (ForcedScalars.count(VF))
5359 for (auto *I : ForcedScalars.find(VF)->second)
5360 Worklist.insert(I);
5361
5362 // Expand the worklist by looking through any bitcasts and getelementptr
5363 // instructions we've already identified as scalar. This is similar to the
5364 // expansion step in collectLoopUniforms(); however, here we're only
5365 // expanding to include additional bitcasts and getelementptr instructions.
5366 unsigned Idx = 0;
5367 while (Idx != Worklist.size()) {
5368 Instruction *Dst = Worklist[Idx++];
5369 if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5370 continue;
5371 auto *Src = cast<Instruction>(Dst->getOperand(0));
5372 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5373 auto *J = cast<Instruction>(U);
5374 return !TheLoop->contains(J) || Worklist.count(J) ||
5375 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5376 isScalarUse(J, Src));
5377 })) {
5378 Worklist.insert(Src);
5379 DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *Src << "\n"; } } while (false)
;
5380 }
5381 }
5382
5383 // An induction variable will remain scalar if all users of the induction
5384 // variable and induction variable update remain scalar.
5385 for (auto &Induction : *Legal->getInductionVars()) {
5386 auto *Ind = Induction.first;
5387 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5388
5389 // We already considered pointer induction variables, so there's no reason
5390 // to look at their users again.
5391 //
5392 // TODO: Once we are able to vectorize pointer induction variables we
5393 // should no longer skip over them here.
5394 if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
5395 continue;
5396
5397 // Determine if all users of the induction variable are scalar after
5398 // vectorization.
5399 auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5400 auto *I = cast<Instruction>(U);
5401 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5402 });
5403 if (!ScalarInd)
5404 continue;
5405
5406 // Determine if all users of the induction variable update instruction are
5407 // scalar after vectorization.
5408 auto ScalarIndUpdate =
5409 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5410 auto *I = cast<Instruction>(U);
5411 return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5412 });
5413 if (!ScalarIndUpdate)
5414 continue;
5415
5416 // The induction variable and its update instruction will remain scalar.
5417 Worklist.insert(Ind);
5418 Worklist.insert(IndUpdate);
5419 DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *Ind << "\n"; } } while (false)
;
5420 DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found scalar instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
5421 }
5422
5423 Scalars[VF].insert(Worklist.begin(), Worklist.end());
5424}
5425
5426bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) {
5427 if (!Legal->blockNeedsPredication(I->getParent()))
5428 return false;
5429 switch(I->getOpcode()) {
5430 default:
5431 break;
5432 case Instruction::Load:
5433 case Instruction::Store: {
5434 if (!Legal->isMaskRequired(I))
5435 return false;
5436 auto *Ptr = getPointerOperand(I);
5437 auto *Ty = getMemInstValueType(I);
5438 return isa<LoadInst>(I) ?
5439 !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
5440 : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
5441 }
5442 case Instruction::UDiv:
5443 case Instruction::SDiv:
5444 case Instruction::SRem:
5445 case Instruction::URem:
5446 return mayDivideByZero(*I);
5447 }
5448 return false;
5449}
5450
5451bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
5452 unsigned VF) {
5453 // Get and ensure we have a valid memory instruction.
5454 LoadInst *LI = dyn_cast<LoadInst>(I);
5455 StoreInst *SI = dyn_cast<StoreInst>(I);
5456 assert((LI || SI) && "Invalid memory instruction")(static_cast <bool> ((LI || SI) && "Invalid memory instruction"
) ? void (0) : __assert_fail ("(LI || SI) && \"Invalid memory instruction\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5456, __extension__ __PRETTY_FUNCTION__))
;
5457
5458 auto *Ptr = getPointerOperand(I);
5459
5460 // In order to be widened, the pointer should be consecutive, first of all.
5461 if (!Legal->isConsecutivePtr(Ptr))
5462 return false;
5463
5464 // If the instruction is a store located in a predicated block, it will be
5465 // scalarized.
5466 if (isScalarWithPredication(I))
5467 return false;
5468
5469 // If the instruction's allocated size doesn't equal it's type size, it
5470 // requires padding and will be scalarized.
5471 auto &DL = I->getModule()->getDataLayout();
5472 auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5473 if (hasIrregularType(ScalarTy, DL, VF))
5474 return false;
5475
5476 return true;
5477}
5478
5479void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5480 // We should not collect Uniforms more than once per VF. Right now,
5481 // this function is called from collectUniformsAndScalars(), which
5482 // already does this check. Collecting Uniforms for VF=1 does not make any
5483 // sense.
5484
5485 assert(VF >= 2 && !Uniforms.count(VF) &&(static_cast <bool> (VF >= 2 && !Uniforms.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Uniforms.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
5486 "This function should not be visited twice for the same VF")(static_cast <bool> (VF >= 2 && !Uniforms.count
(VF) && "This function should not be visited twice for the same VF"
) ? void (0) : __assert_fail ("VF >= 2 && !Uniforms.count(VF) && \"This function should not be visited twice for the same VF\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5486, __extension__ __PRETTY_FUNCTION__))
;
5487
5488 // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5489 // not analyze again. Uniforms.count(VF) will return 1.
5490 Uniforms[VF].clear();
5491
5492 // We now know that the loop is vectorizable!
5493 // Collect instructions inside the loop that will remain uniform after
5494 // vectorization.
5495
5496 // Global values, params and instructions outside of current loop are out of
5497 // scope.
5498 auto isOutOfScope = [&](Value *V) -> bool {
5499 Instruction *I = dyn_cast<Instruction>(V);
5500 return (!I || !TheLoop->contains(I));
5501 };
5502
5503 SetVector<Instruction *> Worklist;
5504 BasicBlock *Latch = TheLoop->getLoopLatch();
5505
5506 // Start with the conditional branch. If the branch condition is an
5507 // instruction contained in the loop that is only used by the branch, it is
5508 // uniform.
5509 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5510 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5511 Worklist.insert(Cmp);
5512 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *Cmp << "\n"; } } while (false)
;
5513 }
5514
5515 // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5516 // are pointers that are treated like consecutive pointers during
5517 // vectorization. The pointer operands of interleaved accesses are an
5518 // example.
5519 SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5520
5521 // Holds pointer operands of instructions that are possibly non-uniform.
5522 SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5523
5524 auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5525 InstWidening WideningDecision = getWideningDecision(I, VF);
5526 assert(WideningDecision != CM_Unknown &&(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5527, __extension__ __PRETTY_FUNCTION__))
5527 "Widening decision should be ready at this moment")(static_cast <bool> (WideningDecision != CM_Unknown &&
"Widening decision should be ready at this moment") ? void (
0) : __assert_fail ("WideningDecision != CM_Unknown && \"Widening decision should be ready at this moment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/Transforms/Vectorize/LoopVectorize.cpp"
, 5527, __extension__ __PRETTY_FUNCTION__))
;
5528
5529 return (WideningDecision == CM_Widen ||
5530 WideningDecision == CM_Widen_Reverse ||
5531 WideningDecision == CM_Interleave);
5532 };
5533 // Iterate over the instructions in the loop, and collect all
5534 // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5535 // that a consecutive-like pointer operand will be scalarized, we collect it
5536 // in PossibleNonUniformPtrs instead. We use two sets here because a single
5537 // getelementptr instruction can be used by both vectorized and scalarized
5538 // memory instructions. For example, if a loop loads and stores from the same
5539 // location, but the store is conditional, the store will be scalarized, and
5540 // the getelementptr won't remain uniform.
5541 for (auto *BB : TheLoop->blocks())
5542 for (auto &I : *BB) {
5543 // If there's no pointer operand, there's nothing to do.
5544 auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5545 if (!Ptr)
5546 continue;
5547
5548 // True if all users of Ptr are memory accesses that have Ptr as their
5549 // pointer operand.
5550 auto UsersAreMemAccesses =
5551 llvm::all_of(Ptr->users(), [&](User *U) -> bool {
5552 return getPointerOperand(U) == Ptr;
5553 });
5554
5555 // Ensure the memory instruction will not be scalarized or used by
5556 // gather/scatter, making its pointer operand non-uniform. If the pointer
5557 // operand is used by any instruction other than a memory access, we
5558 // conservatively assume the pointer operand may be non-uniform.
5559 if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5560 PossibleNonUniformPtrs.insert(Ptr);
5561
5562 // If the memory instruction will be vectorized and its pointer operand
5563 // is consecutive-like, or interleaving - the pointer operand should
5564 // remain uniform.
5565 else
5566 ConsecutiveLikePtrs.insert(Ptr);
5567 }
5568
5569 // Add to the Worklist all consecutive and consecutive-like pointers that
5570 // aren't also identified as possibly non-uniform.
5571 for (auto *V : ConsecutiveLikePtrs)
5572 if (!PossibleNonUniformPtrs.count(V)) {
5573 DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *V << "\n"; } } while (false)
;
5574 Worklist.insert(V);
5575 }
5576
5577 // Expand Worklist in topological order: whenever a new instruction
5578 // is added , its users should be either already inside Worklist, or
5579 // out of scope. It ensures a uniform instruction will only be used
5580 // by uniform instructions or out of scope instructions.
5581 unsigned idx = 0;
5582 while (idx != Worklist.size()) {
5583 Instruction *I = Worklist[idx++];
5584
5585 for (auto OV : I->operand_values()) {
5586 if (isOutOfScope(OV))
5587 continue;
5588 auto *OI = cast<Instruction>(OV);
5589 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5590 auto *J = cast<Instruction>(U);
5591 return !TheLoop->contains(J) || Worklist.count(J) ||
5592 (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5593 })) {
5594 Worklist.insert(OI);
5595 DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *OI << "\n"; } } while (false)
;
5596 }
5597 }
5598 }
5599
5600 // Returns true if Ptr is the pointer operand of a memory access instruction
5601 // I, and I is known to not require scalarization.
5602 auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5603 return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5604 };
5605
5606 // For an instruction to be added into Worklist above, all its users inside
5607 // the loop should also be in Worklist. However, this condition cannot be
5608 // true for phi nodes that form a cyclic dependence. We must process phi
5609 // nodes separately. An induction variable will remain uniform if all users
5610 // of the induction variable and induction variable update remain uniform.
5611 // The code below handles both pointer and non-pointer induction variables.
5612 for (auto &Induction : *Legal->getInductionVars()) {
5613 auto *Ind = Induction.first;
5614 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5615
5616 // Determine if all users of the induction variable are uniform after
5617 // vectorization.
5618 auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5619 auto *I = cast<Instruction>(U);
5620 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5621 isVectorizedMemAccessUse(I, Ind);
5622 });
5623 if (!UniformInd)
5624 continue;
5625
5626 // Determine if all users of the induction variable update instruction are
5627 // uniform after vectorization.
5628 auto UniformIndUpdate =
5629 llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5630 auto *I = cast<Instruction>(U);
5631 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5632 isVectorizedMemAccessUse(I, IndUpdate);
5633 });
5634 if (!UniformIndUpdate)
5635 continue;
5636
5637 // The induction variable and its update instruction will remain uniform.
5638 Worklist.insert(Ind);
5639 Worklist.insert(IndUpdate);
5640 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *Ind << "\n"; } } while (false)
;
5641 DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: Found uniform instruction: "
<< *IndUpdate << "\n"; } } while (false)
;
5642 }
5643
5644 Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5645}
5646
5647bool LoopVectorizationLegality::canVectorizeMemory() {
5648 LAI = &(*GetLAA)(*TheLoop);
5649 InterleaveInfo.setLAI(LAI);
5650 const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5651 if (LAR) {
5652 ORE->emit([&]() {
5653 return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(),
5654 "loop not vectorized: ", *LAR);
5655 });
5656 }
5657 if (!LAI->canVectorizeMemory())
5658 return false;
5659
5660 if (LAI->hasStoreToLoopInvariantAddress()) {
5661 ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
5662 << "write to a loop invariant address could not be vectorized");
5663 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-vectorize")) { dbgs() << "LV: We don't allow storing to uniform addresses\n"
; } } while (false)
;
5664 return false;
5665 }
5666
5667 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5668 PSE.addPredicate(LAI->getPSE().getUnionPredicate());
5669
5670 return true;
5671}
5672
5673bool LoopVectorizationLegality::isInductionPhi(const Value *V) {
5674 Value *In0 = const_cast<Value *>(V);