1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
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.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/EquivalenceClasses.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/Analysis/AliasAnalysis.h"
59 #include "llvm/Analysis/BlockFrequencyInfo.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Analysis/LoopIterator.h"
62 #include "llvm/Analysis/LoopPass.h"
63 #include "llvm/Analysis/ScalarEvolution.h"
64 #include "llvm/Analysis/ScalarEvolutionExpander.h"
65 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
66 #include "llvm/Analysis/TargetTransformInfo.h"
67 #include "llvm/Analysis/ValueTracking.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/IRBuilder.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/LLVMContext.h"
77 #include "llvm/IR/Module.h"
78 #include "llvm/IR/Type.h"
79 #include "llvm/IR/Value.h"
80 #include "llvm/IR/Verifier.h"
81 #include "llvm/Pass.h"
82 #include "llvm/Support/BranchProbability.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/PatternMatch.h"
86 #include "llvm/Support/ValueHandle.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetLibraryInfo.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
91 #include "llvm/Transforms/Utils/Local.h"
96 using namespace llvm::PatternMatch;
98 static cl::opt<unsigned>
99 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
100 cl::desc("Sets the SIMD width. Zero is autoselect."));
102 static cl::opt<unsigned>
103 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
104 cl::desc("Sets the vectorization unroll count. "
105 "Zero is autoselect."));
108 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
109 cl::desc("Enable if-conversion during vectorization."));
111 /// We don't vectorize loops with a known constant trip count below this number.
112 static cl::opt<unsigned>
113 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
115 cl::desc("Don't vectorize loops with a constant "
116 "trip count that is smaller than this "
119 /// This enables versioning on the strides of symbolically striding memory
120 /// accesses in code like the following.
121 /// for (i = 0; i < N; ++i)
122 /// A[i * Stride1] += B[i * Stride2] ...
124 /// Will be roughly translated to
125 /// if (Stride1 == 1 && Stride2 == 1) {
126 /// for (i = 0; i < N; i+=4)
130 static cl::opt<bool> EnableMemAccessVersioning(
131 "enable-mem-access-versioning", cl::init(true), cl::Hidden,
132 cl::desc("Enable symblic stride memory access versioning"));
134 /// We don't unroll loops with a known constant trip count below this number.
135 static const unsigned TinyTripCountUnrollThreshold = 128;
137 /// When performing memory disambiguation checks at runtime do not make more
138 /// than this number of comparisons.
139 static const unsigned RuntimeMemoryCheckThreshold = 8;
141 /// Maximum simd width.
142 static const unsigned MaxVectorWidth = 64;
144 static cl::opt<unsigned> ForceTargetNumScalarRegs(
145 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
146 cl::desc("A flag that overrides the target's number of scalar registers."));
148 static cl::opt<unsigned> ForceTargetNumVectorRegs(
149 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
150 cl::desc("A flag that overrides the target's number of vector registers."));
152 /// Maximum vectorization unroll count.
153 static const unsigned MaxUnrollFactor = 16;
155 static cl::opt<unsigned> ForceTargetMaxScalarUnrollFactor(
156 "force-target-max-scalar-unroll", cl::init(0), cl::Hidden,
157 cl::desc("A flag that overrides the target's max unroll factor for scalar "
160 static cl::opt<unsigned> ForceTargetMaxVectorUnrollFactor(
161 "force-target-max-vector-unroll", cl::init(0), cl::Hidden,
162 cl::desc("A flag that overrides the target's max unroll factor for "
163 "vectorized loops."));
165 static cl::opt<unsigned> ForceTargetInstructionCost(
166 "force-target-instruction-cost", cl::init(0), cl::Hidden,
167 cl::desc("A flag that overrides the target's expected cost for "
168 "an instruction to a single constant value. Mostly "
169 "useful for getting consistent testing."));
171 static cl::opt<unsigned> SmallLoopCost(
172 "small-loop-cost", cl::init(20), cl::Hidden,
173 cl::desc("The cost of a loop that is considered 'small' by the unroller."));
177 // Forward declarations.
178 class LoopVectorizationLegality;
179 class LoopVectorizationCostModel;
181 /// InnerLoopVectorizer vectorizes loops which contain only one basic
182 /// block to a specified vectorization factor (VF).
183 /// This class performs the widening of scalars into vectors, or multiple
184 /// scalars. This class also implements the following features:
185 /// * It inserts an epilogue loop for handling loops that don't have iteration
186 /// counts that are known to be a multiple of the vectorization factor.
187 /// * It handles the code generation for reduction variables.
188 /// * Scalarization (implementation using scalars) of un-vectorizable
190 /// InnerLoopVectorizer does not perform any vectorization-legality
191 /// checks, and relies on the caller to check for the different legality
192 /// aspects. The InnerLoopVectorizer relies on the
193 /// LoopVectorizationLegality class to provide information about the induction
194 /// and reduction variables that were found to a given vectorization factor.
195 class InnerLoopVectorizer {
197 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
198 DominatorTree *DT, DataLayout *DL,
199 const TargetLibraryInfo *TLI, unsigned VecWidth,
200 unsigned UnrollFactor)
201 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
202 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
203 OldInduction(0), WidenMap(UnrollFactor), Legal(0) {}
205 // Perform the actual loop widening (vectorization).
206 void vectorize(LoopVectorizationLegality *L) {
208 // Create a new empty loop. Unlink the old loop and connect the new one.
210 // Widen each instruction in the old loop to a new one in the new loop.
211 // Use the Legality module to find the induction and reduction variables.
213 // Register the new loop and update the analysis passes.
217 virtual ~InnerLoopVectorizer() {}
220 /// A small list of PHINodes.
221 typedef SmallVector<PHINode*, 4> PhiVector;
222 /// When we unroll loops we have multiple vector values for each scalar.
223 /// This data structure holds the unrolled and vectorized values that
224 /// originated from one scalar instruction.
225 typedef SmallVector<Value*, 2> VectorParts;
227 // When we if-convert we need create edge masks. We have to cache values so
228 // that we don't end up with exponential recursion/IR.
229 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
230 VectorParts> EdgeMaskCache;
232 /// \brief Add code that checks at runtime if the accessed arrays overlap.
234 /// Returns a pair of instructions where the first element is the first
235 /// instruction generated in possibly a sequence of instructions and the
236 /// second value is the final comparator value or NULL if no check is needed.
237 std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
239 /// \brief Add checks for strides that where assumed to be 1.
241 /// Returns the last check instruction and the first check instruction in the
242 /// pair as (first, last).
243 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
245 /// Create an empty loop, based on the loop ranges of the old loop.
246 void createEmptyLoop();
247 /// Copy and widen the instructions from the old loop.
248 virtual void vectorizeLoop();
250 /// \brief The Loop exit block may have single value PHI nodes where the
251 /// incoming value is 'Undef'. While vectorizing we only handled real values
252 /// that were defined inside the loop. Here we fix the 'undef case'.
256 /// A helper function that computes the predicate of the block BB, assuming
257 /// that the header block of the loop is set to True. It returns the *entry*
258 /// mask for the block BB.
259 VectorParts createBlockInMask(BasicBlock *BB);
260 /// A helper function that computes the predicate of the edge between SRC
262 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
264 /// A helper function to vectorize a single BB within the innermost loop.
265 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
267 /// Vectorize a single PHINode in a block. This method handles the induction
268 /// variable canonicalization. It supports both VF = 1 for unrolled loops and
269 /// arbitrary length vectors.
270 void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
271 unsigned UF, unsigned VF, PhiVector *PV);
273 /// Insert the new loop to the loop hierarchy and pass manager
274 /// and update the analysis passes.
275 void updateAnalysis();
277 /// This instruction is un-vectorizable. Implement it as a sequence
279 virtual void scalarizeInstruction(Instruction *Instr);
281 /// Vectorize Load and Store instructions,
282 virtual void vectorizeMemoryInstruction(Instruction *Instr);
284 /// Create a broadcast instruction. This method generates a broadcast
285 /// instruction (shuffle) for loop invariant values and for the induction
286 /// value. If this is the induction variable then we extend it to N, N+1, ...
287 /// this is needed because each iteration in the loop corresponds to a SIMD
289 virtual Value *getBroadcastInstrs(Value *V);
291 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
292 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
293 /// The sequence starts at StartIndex.
294 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
296 /// When we go over instructions in the basic block we rely on previous
297 /// values within the current basic block or on loop invariant values.
298 /// When we widen (vectorize) values we place them in the map. If the values
299 /// are not within the map, they have to be loop invariant, so we simply
300 /// broadcast them into a vector.
301 VectorParts &getVectorValue(Value *V);
303 /// Generate a shuffle sequence that will reverse the vector Vec.
304 virtual Value *reverseVector(Value *Vec);
306 /// This is a helper class that holds the vectorizer state. It maps scalar
307 /// instructions to vector instructions. When the code is 'unrolled' then
308 /// then a single scalar value is mapped to multiple vector parts. The parts
309 /// are stored in the VectorPart type.
311 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
313 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
315 /// \return True if 'Key' is saved in the Value Map.
316 bool has(Value *Key) const { return MapStorage.count(Key); }
318 /// Initializes a new entry in the map. Sets all of the vector parts to the
319 /// save value in 'Val'.
320 /// \return A reference to a vector with splat values.
321 VectorParts &splat(Value *Key, Value *Val) {
322 VectorParts &Entry = MapStorage[Key];
323 Entry.assign(UF, Val);
327 ///\return A reference to the value that is stored at 'Key'.
328 VectorParts &get(Value *Key) {
329 VectorParts &Entry = MapStorage[Key];
332 assert(Entry.size() == UF);
337 /// The unroll factor. Each entry in the map stores this number of vector
341 /// Map storage. We use std::map and not DenseMap because insertions to a
342 /// dense map invalidates its iterators.
343 std::map<Value *, VectorParts> MapStorage;
346 /// The original loop.
348 /// Scev analysis to use.
356 /// Target Library Info.
357 const TargetLibraryInfo *TLI;
359 /// The vectorization SIMD factor to use. Each vector will have this many
364 /// The vectorization unroll factor to use. Each scalar is vectorized to this
365 /// many different vector instructions.
368 /// The builder that we use
371 // --- Vectorization state ---
373 /// The vector-loop preheader.
374 BasicBlock *LoopVectorPreHeader;
375 /// The scalar-loop preheader.
376 BasicBlock *LoopScalarPreHeader;
377 /// Middle Block between the vector and the scalar.
378 BasicBlock *LoopMiddleBlock;
379 ///The ExitBlock of the scalar loop.
380 BasicBlock *LoopExitBlock;
381 ///The vector loop body.
382 BasicBlock *LoopVectorBody;
383 ///The scalar loop body.
384 BasicBlock *LoopScalarBody;
385 /// A list of all bypass blocks. The first block is the entry of the loop.
386 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
388 /// The new Induction variable which was added to the new block.
390 /// The induction variable of the old basic block.
391 PHINode *OldInduction;
392 /// Holds the extended (to the widest induction type) start index.
394 /// Maps scalars to widened vectors.
396 EdgeMaskCache MaskCache;
398 LoopVectorizationLegality *Legal;
401 class InnerLoopUnroller : public InnerLoopVectorizer {
403 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
404 DominatorTree *DT, DataLayout *DL,
405 const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
406 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
409 virtual void scalarizeInstruction(Instruction *Instr);
410 virtual void vectorizeMemoryInstruction(Instruction *Instr);
411 virtual Value *getBroadcastInstrs(Value *V);
412 virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
413 virtual Value *reverseVector(Value *Vec);
416 /// \brief Look for a meaningful debug location on the instruction or it's
418 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
423 if (I->getDebugLoc() != Empty)
426 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
427 if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
428 if (OpInst->getDebugLoc() != Empty)
435 /// \brief Set the debug location in the builder using the debug location in the
437 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
438 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
439 B.SetCurrentDebugLocation(Inst->getDebugLoc());
441 B.SetCurrentDebugLocation(DebugLoc());
444 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
445 /// to what vectorization factor.
446 /// This class does not look at the profitability of vectorization, only the
447 /// legality. This class has two main kinds of checks:
448 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
449 /// will change the order of memory accesses in a way that will change the
450 /// correctness of the program.
451 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
452 /// checks for a number of different conditions, such as the availability of a
453 /// single induction variable, that all types are supported and vectorize-able,
454 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
455 /// This class is also used by InnerLoopVectorizer for identifying
456 /// induction variable and the different reduction variables.
457 class LoopVectorizationLegality {
459 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
460 DominatorTree *DT, TargetLibraryInfo *TLI)
461 : TheLoop(L), SE(SE), DL(DL), DT(DT), TLI(TLI),
462 Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
463 MaxSafeDepDistBytes(-1U) {}
465 /// This enum represents the kinds of reductions that we support.
467 RK_NoReduction, ///< Not a reduction.
468 RK_IntegerAdd, ///< Sum of integers.
469 RK_IntegerMult, ///< Product of integers.
470 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
471 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
472 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
473 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
474 RK_FloatAdd, ///< Sum of floats.
475 RK_FloatMult, ///< Product of floats.
476 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
479 /// This enum represents the kinds of inductions that we support.
481 IK_NoInduction, ///< Not an induction variable.
482 IK_IntInduction, ///< Integer induction variable. Step = 1.
483 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
484 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
485 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
488 // This enum represents the kind of minmax reduction.
489 enum MinMaxReductionKind {
499 /// This struct holds information about reduction variables.
500 struct ReductionDescriptor {
501 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
502 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
504 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
505 MinMaxReductionKind MK)
506 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
508 // The starting value of the reduction.
509 // It does not have to be zero!
510 TrackingVH<Value> StartValue;
511 // The instruction who's value is used outside the loop.
512 Instruction *LoopExitInstr;
513 // The kind of the reduction.
515 // If this a min/max reduction the kind of reduction.
516 MinMaxReductionKind MinMaxKind;
519 /// This POD struct holds information about a potential reduction operation.
520 struct ReductionInstDesc {
521 ReductionInstDesc(bool IsRedux, Instruction *I) :
522 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
524 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
525 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
527 // Is this instruction a reduction candidate.
529 // The last instruction in a min/max pattern (select of the select(icmp())
530 // pattern), or the current reduction instruction otherwise.
531 Instruction *PatternLastInst;
532 // If this is a min/max pattern the comparison predicate.
533 MinMaxReductionKind MinMaxKind;
536 /// This struct holds information about the memory runtime legality
537 /// check that a group of pointers do not overlap.
538 struct RuntimePointerCheck {
539 RuntimePointerCheck() : Need(false) {}
541 /// Reset the state of the pointer runtime information.
548 DependencySetId.clear();
551 /// Insert a pointer and calculate the start and end SCEVs.
552 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
553 unsigned DepSetId, ValueToValueMap &Strides);
555 /// This flag indicates if we need to add the runtime check.
557 /// Holds the pointers that we need to check.
558 SmallVector<TrackingVH<Value>, 2> Pointers;
559 /// Holds the pointer value at the beginning of the loop.
560 SmallVector<const SCEV*, 2> Starts;
561 /// Holds the pointer value at the end of the loop.
562 SmallVector<const SCEV*, 2> Ends;
563 /// Holds the information if this pointer is used for writing to memory.
564 SmallVector<bool, 2> IsWritePtr;
565 /// Holds the id of the set of pointers that could be dependent because of a
566 /// shared underlying object.
567 SmallVector<unsigned, 2> DependencySetId;
570 /// A struct for saving information about induction variables.
571 struct InductionInfo {
572 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
573 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
575 TrackingVH<Value> StartValue;
580 /// ReductionList contains the reduction descriptors for all
581 /// of the reductions that were found in the loop.
582 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
584 /// InductionList saves induction variables and maps them to the
585 /// induction descriptor.
586 typedef MapVector<PHINode*, InductionInfo> InductionList;
588 /// Returns true if it is legal to vectorize this loop.
589 /// This does not mean that it is profitable to vectorize this
590 /// loop, only that it is legal to do so.
593 /// Returns the Induction variable.
594 PHINode *getInduction() { return Induction; }
596 /// Returns the reduction variables found in the loop.
597 ReductionList *getReductionVars() { return &Reductions; }
599 /// Returns the induction variables found in the loop.
600 InductionList *getInductionVars() { return &Inductions; }
602 /// Returns the widest induction type.
603 Type *getWidestInductionType() { return WidestIndTy; }
605 /// Returns True if V is an induction variable in this loop.
606 bool isInductionVariable(const Value *V);
608 /// Return true if the block BB needs to be predicated in order for the loop
609 /// to be vectorized.
610 bool blockNeedsPredication(BasicBlock *BB);
612 /// Check if this pointer is consecutive when vectorizing. This happens
613 /// when the last index of the GEP is the induction variable, or that the
614 /// pointer itself is an induction variable.
615 /// This check allows us to vectorize A[idx] into a wide load/store.
617 /// 0 - Stride is unknown or non-consecutive.
618 /// 1 - Address is consecutive.
619 /// -1 - Address is consecutive, and decreasing.
620 int isConsecutivePtr(Value *Ptr);
622 /// Returns true if the value V is uniform within the loop.
623 bool isUniform(Value *V);
625 /// Returns true if this instruction will remain scalar after vectorization.
626 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
628 /// Returns the information that we collected about runtime memory check.
629 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
631 /// This function returns the identity element (or neutral element) for
633 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
635 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
637 bool hasStride(Value *V) { return StrideSet.count(V); }
638 bool mustCheckStrides() { return !StrideSet.empty(); }
639 SmallPtrSet<Value *, 8>::iterator strides_begin() {
640 return StrideSet.begin();
642 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
645 /// Check if a single basic block loop is vectorizable.
646 /// At this point we know that this is a loop with a constant trip count
647 /// and we only need to check individual instructions.
648 bool canVectorizeInstrs();
650 /// When we vectorize loops we may change the order in which
651 /// we read and write from memory. This method checks if it is
652 /// legal to vectorize the code, considering only memory constrains.
653 /// Returns true if the loop is vectorizable
654 bool canVectorizeMemory();
656 /// Return true if we can vectorize this loop using the IF-conversion
658 bool canVectorizeWithIfConvert();
660 /// Collect the variables that need to stay uniform after vectorization.
661 void collectLoopUniforms();
663 /// Return true if all of the instructions in the block can be speculatively
664 /// executed. \p SafePtrs is a list of addresses that are known to be legal
665 /// and we know that we can read from them without segfault.
666 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
668 /// Returns True, if 'Phi' is the kind of reduction variable for type
669 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
670 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
671 /// Returns a struct describing if the instruction 'I' can be a reduction
672 /// variable of type 'Kind'. If the reduction is a min/max pattern of
673 /// select(icmp()) this function advances the instruction pointer 'I' from the
674 /// compare instruction to the select instruction and stores this pointer in
675 /// 'PatternLastInst' member of the returned struct.
676 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
677 ReductionInstDesc &Desc);
678 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
679 /// pattern corresponding to a min(X, Y) or max(X, Y).
680 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
681 ReductionInstDesc &Prev);
682 /// Returns the induction kind of Phi. This function may return NoInduction
683 /// if the PHI is not an induction variable.
684 InductionKind isInductionVariable(PHINode *Phi);
686 /// \brief Collect memory access with loop invariant strides.
688 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
690 void collectStridedAcccess(Value *LoadOrStoreInst);
692 /// The loop that we evaluate.
696 /// DataLayout analysis.
700 /// Target Library Info.
701 TargetLibraryInfo *TLI;
703 // --- vectorization state --- //
705 /// Holds the integer induction variable. This is the counter of the
708 /// Holds the reduction variables.
709 ReductionList Reductions;
710 /// Holds all of the induction variables that we found in the loop.
711 /// Notice that inductions don't need to start at zero and that induction
712 /// variables can be pointers.
713 InductionList Inductions;
714 /// Holds the widest induction type encountered.
717 /// Allowed outside users. This holds the reduction
718 /// vars which can be accessed from outside the loop.
719 SmallPtrSet<Value*, 4> AllowedExit;
720 /// This set holds the variables which are known to be uniform after
722 SmallPtrSet<Instruction*, 4> Uniforms;
723 /// We need to check that all of the pointers in this list are disjoint
725 RuntimePointerCheck PtrRtCheck;
726 /// Can we assume the absence of NaNs.
727 bool HasFunNoNaNAttr;
729 unsigned MaxSafeDepDistBytes;
731 ValueToValueMap Strides;
732 SmallPtrSet<Value *, 8> StrideSet;
735 /// LoopVectorizationCostModel - estimates the expected speedups due to
737 /// In many cases vectorization is not profitable. This can happen because of
738 /// a number of reasons. In this class we mainly attempt to predict the
739 /// expected speedup/slowdowns due to the supported instruction set. We use the
740 /// TargetTransformInfo to query the different backends for the cost of
741 /// different operations.
742 class LoopVectorizationCostModel {
744 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
745 LoopVectorizationLegality *Legal,
746 const TargetTransformInfo &TTI,
747 DataLayout *DL, const TargetLibraryInfo *TLI)
748 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
750 /// Information about vectorization costs
751 struct VectorizationFactor {
752 unsigned Width; // Vector width with best cost
753 unsigned Cost; // Cost of the loop with that width
755 /// \return The most profitable vectorization factor and the cost of that VF.
756 /// This method checks every power of two up to VF. If UserVF is not ZERO
757 /// then this vectorization factor will be selected if vectorization is
759 VectorizationFactor selectVectorizationFactor(bool OptForSize,
762 /// \return The size (in bits) of the widest type in the code that
763 /// needs to be vectorized. We ignore values that remain scalar such as
764 /// 64 bit loop indices.
765 unsigned getWidestType();
767 /// \return The most profitable unroll factor.
768 /// If UserUF is non-zero then this method finds the best unroll-factor
769 /// based on register pressure and other parameters.
770 /// VF and LoopCost are the selected vectorization factor and the cost of the
772 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
775 /// \brief A struct that represents some properties of the register usage
777 struct RegisterUsage {
778 /// Holds the number of loop invariant values that are used in the loop.
779 unsigned LoopInvariantRegs;
780 /// Holds the maximum number of concurrent live intervals in the loop.
781 unsigned MaxLocalUsers;
782 /// Holds the number of instructions in the loop.
783 unsigned NumInstructions;
786 /// \return information about the register usage of the loop.
787 RegisterUsage calculateRegisterUsage();
790 /// Returns the expected execution cost. The unit of the cost does
791 /// not matter because we use the 'cost' units to compare different
792 /// vector widths. The cost that is returned is *not* normalized by
793 /// the factor width.
794 unsigned expectedCost(unsigned VF);
796 /// Returns the execution time cost of an instruction for a given vector
797 /// width. Vector width of one means scalar.
798 unsigned getInstructionCost(Instruction *I, unsigned VF);
800 /// A helper function for converting Scalar types to vector types.
801 /// If the incoming type is void, we return void. If the VF is 1, we return
803 static Type* ToVectorTy(Type *Scalar, unsigned VF);
805 /// Returns whether the instruction is a load or store and will be a emitted
806 /// as a vector operation.
807 bool isConsecutiveLoadOrStore(Instruction *I);
809 /// The loop that we evaluate.
813 /// Loop Info analysis.
815 /// Vectorization legality.
816 LoopVectorizationLegality *Legal;
817 /// Vector target information.
818 const TargetTransformInfo &TTI;
819 /// Target data layout information.
821 /// Target Library Info.
822 const TargetLibraryInfo *TLI;
825 /// Utility class for getting and setting loop vectorizer hints in the form
826 /// of loop metadata.
827 struct LoopVectorizeHints {
828 /// Vectorization width.
830 /// Vectorization unroll factor.
832 /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
835 LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
836 : Width(VectorizationFactor)
837 , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
839 , LoopID(L->getLoopID()) {
841 // The command line options override any loop metadata except for when
842 // width == 1 which is used to indicate the loop is already vectorized.
843 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
844 Width = VectorizationFactor;
845 if (VectorizationUnroll.getNumOccurrences() > 0)
846 Unroll = VectorizationUnroll;
848 DEBUG(if (DisableUnrolling && Unroll == 1)
849 dbgs() << "LV: Unrolling disabled by the pass manager\n");
852 /// Return the loop vectorizer metadata prefix.
853 static StringRef Prefix() { return "llvm.vectorizer."; }
855 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
856 SmallVector<Value*, 2> Vals;
857 Vals.push_back(MDString::get(Context, Name));
858 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
859 return MDNode::get(Context, Vals);
862 /// Mark the loop L as already vectorized by setting the width to 1.
863 void setAlreadyVectorized(Loop *L) {
864 LLVMContext &Context = L->getHeader()->getContext();
868 // Create a new loop id with one more operand for the already_vectorized
869 // hint. If the loop already has a loop id then copy the existing operands.
870 SmallVector<Value*, 4> Vals(1);
872 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
873 Vals.push_back(LoopID->getOperand(i));
875 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
876 Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
878 MDNode *NewLoopID = MDNode::get(Context, Vals);
879 // Set operand 0 to refer to the loop id itself.
880 NewLoopID->replaceOperandWith(0, NewLoopID);
882 L->setLoopID(NewLoopID);
884 LoopID->replaceAllUsesWith(NewLoopID);
892 /// Find hints specified in the loop metadata.
893 void getHints(const Loop *L) {
897 // First operand should refer to the loop id itself.
898 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
899 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
901 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
902 const MDString *S = 0;
903 SmallVector<Value*, 4> Args;
905 // The expected hint is either a MDString or a MDNode with the first
906 // operand a MDString.
907 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
908 if (!MD || MD->getNumOperands() == 0)
910 S = dyn_cast<MDString>(MD->getOperand(0));
911 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
912 Args.push_back(MD->getOperand(i));
914 S = dyn_cast<MDString>(LoopID->getOperand(i));
915 assert(Args.size() == 0 && "too many arguments for MDString");
921 // Check if the hint starts with the vectorizer prefix.
922 StringRef Hint = S->getString();
923 if (!Hint.startswith(Prefix()))
925 // Remove the prefix.
926 Hint = Hint.substr(Prefix().size(), StringRef::npos);
928 if (Args.size() == 1)
929 getHint(Hint, Args[0]);
933 // Check string hint with one operand.
934 void getHint(StringRef Hint, Value *Arg) {
935 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
937 unsigned Val = C->getZExtValue();
939 if (Hint == "width") {
940 if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
943 DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
944 } else if (Hint == "unroll") {
945 if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
948 DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
949 } else if (Hint == "enable") {
950 if (C->getBitWidth() == 1)
953 DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
955 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
960 static void addInnerLoop(Loop *L, SmallVectorImpl<Loop *> &V) {
962 return V.push_back(L);
964 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
968 /// The LoopVectorize Pass.
969 struct LoopVectorize : public FunctionPass {
970 /// Pass identification, replacement for typeid
973 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
975 DisableUnrolling(NoUnrolling),
976 AlwaysVectorize(AlwaysVectorize) {
977 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
983 TargetTransformInfo *TTI;
985 BlockFrequencyInfo *BFI;
986 TargetLibraryInfo *TLI;
987 bool DisableUnrolling;
988 bool AlwaysVectorize;
990 BlockFrequency ColdEntryFreq;
992 virtual bool runOnFunction(Function &F) {
993 SE = &getAnalysis<ScalarEvolution>();
994 DL = getAnalysisIfAvailable<DataLayout>();
995 LI = &getAnalysis<LoopInfo>();
996 TTI = &getAnalysis<TargetTransformInfo>();
997 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
998 BFI = &getAnalysis<BlockFrequencyInfo>();
999 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
1001 // Compute some weights outside of the loop over the loops. Compute this
1002 // using a BranchProbability to re-use its scaling math.
1003 const BranchProbability ColdProb(1, 5); // 20%
1004 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
1006 // If the target claims to have no vector registers don't attempt
1008 if (!TTI->getNumberOfRegisters(true))
1012 DEBUG(dbgs() << "LV: Not vectorizing: Missing data layout\n");
1016 // Build up a worklist of inner-loops to vectorize. This is necessary as
1017 // the act of vectorizing or partially unrolling a loop creates new loops
1018 // and can invalidate iterators across the loops.
1019 SmallVector<Loop *, 8> Worklist;
1021 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
1022 addInnerLoop(*I, Worklist);
1024 // Now walk the identified inner loops.
1025 bool Changed = false;
1026 while (!Worklist.empty())
1027 Changed |= processLoop(Worklist.pop_back_val());
1029 // Process each loop nest in the function.
1033 bool processLoop(Loop *L) {
1034 // We only handle inner loops, so if there are children just recurse.
1036 bool Changed = false;
1037 for (Loop::iterator I = L->begin(), E = L->begin(); I != E; ++I)
1038 Changed |= processLoop(*I);
1042 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
1043 L->getHeader()->getParent()->getName() << "\"\n");
1045 LoopVectorizeHints Hints(L, DisableUnrolling);
1047 if (Hints.Force == 0) {
1048 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1052 if (!AlwaysVectorize && Hints.Force != 1) {
1053 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1057 if (Hints.Width == 1 && Hints.Unroll == 1) {
1058 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1062 // Check if it is legal to vectorize the loop.
1063 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
1064 if (!LVL.canVectorize()) {
1065 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
1069 // Use the cost model.
1070 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
1072 // Check the function attributes to find out if this function should be
1073 // optimized for size.
1074 Function *F = L->getHeader()->getParent();
1076 Hints.Force != 1 && F->hasFnAttribute(Attribute::OptimizeForSize);
1078 // Compute the weighted frequency of this loop being executed and see if it
1079 // is less than 20% of the function entry baseline frequency. Note that we
1080 // always have a canonical loop here because we think we *can* vectoriez.
1081 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
1082 if (Hints.Force != 1 && LoopEntryFreq < ColdEntryFreq)
1085 // Check the function attributes to see if implicit floats are allowed.a
1086 // FIXME: This check doesn't seem possibly correct -- what if the loop is
1087 // an integer loop and the vector instructions selected are purely integer
1088 // vector instructions?
1089 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1090 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
1091 "attribute is used.\n");
1095 // Select the optimal vectorization factor.
1096 LoopVectorizationCostModel::VectorizationFactor VF;
1097 VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
1098 // Select the unroll factor.
1099 unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
1102 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
1103 F->getParent()->getModuleIdentifier() << '\n');
1104 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
1106 if (VF.Width == 1) {
1107 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
1110 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
1111 // We decided not to vectorize, but we may want to unroll.
1112 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
1113 Unroller.vectorize(&LVL);
1115 // If we decided that it is *legal* to vectorize the loop then do it.
1116 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
1120 // Mark the loop as already vectorized to avoid vectorizing again.
1121 Hints.setAlreadyVectorized(L);
1123 DEBUG(verifyFunction(*L->getHeader()->getParent()));
1127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1128 AU.addRequiredID(LoopSimplifyID);
1129 AU.addRequiredID(LCSSAID);
1130 AU.addRequired<BlockFrequencyInfo>();
1131 AU.addRequired<DominatorTreeWrapperPass>();
1132 AU.addRequired<LoopInfo>();
1133 AU.addRequired<ScalarEvolution>();
1134 AU.addRequired<TargetTransformInfo>();
1135 AU.addPreserved<LoopInfo>();
1136 AU.addPreserved<DominatorTreeWrapperPass>();
1141 } // end anonymous namespace
1143 //===----------------------------------------------------------------------===//
1144 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1145 // LoopVectorizationCostModel.
1146 //===----------------------------------------------------------------------===//
1148 static Value *stripIntegerCast(Value *V) {
1149 if (CastInst *CI = dyn_cast<CastInst>(V))
1150 if (CI->getOperand(0)->getType()->isIntegerTy())
1151 return CI->getOperand(0);
1155 ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
1157 /// If \p OrigPtr is not null, use it to look up the stride value instead of
1159 static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
1160 ValueToValueMap &PtrToStride,
1161 Value *Ptr, Value *OrigPtr = 0) {
1163 const SCEV *OrigSCEV = SE->getSCEV(Ptr);
1165 // If there is an entry in the map return the SCEV of the pointer with the
1166 // symbolic stride replaced by one.
1167 ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
1168 if (SI != PtrToStride.end()) {
1169 Value *StrideVal = SI->second;
1172 StrideVal = stripIntegerCast(StrideVal);
1174 // Replace symbolic stride by one.
1175 Value *One = ConstantInt::get(StrideVal->getType(), 1);
1176 ValueToValueMap RewriteMap;
1177 RewriteMap[StrideVal] = One;
1180 SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
1181 DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
1186 // Otherwise, just return the SCEV of the original pointer.
1187 return SE->getSCEV(Ptr);
1190 void LoopVectorizationLegality::RuntimePointerCheck::insert(
1191 ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
1192 ValueToValueMap &Strides) {
1193 // Get the stride replaced scev.
1194 const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
1195 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1196 assert(AR && "Invalid addrec expression");
1197 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1198 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1199 Pointers.push_back(Ptr);
1200 Starts.push_back(AR->getStart());
1201 Ends.push_back(ScEnd);
1202 IsWritePtr.push_back(WritePtr);
1203 DependencySetId.push_back(DepSetId);
1206 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1207 // We need to place the broadcast of invariant variables outside the loop.
1208 Instruction *Instr = dyn_cast<Instruction>(V);
1209 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
1210 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1212 // Place the code for broadcasting invariant variables in the new preheader.
1213 IRBuilder<>::InsertPointGuard Guard(Builder);
1215 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1217 // Broadcast the scalar into all locations in the vector.
1218 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1223 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1225 assert(Val->getType()->isVectorTy() && "Must be a vector");
1226 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1227 "Elem must be an integer");
1228 // Create the types.
1229 Type *ITy = Val->getType()->getScalarType();
1230 VectorType *Ty = cast<VectorType>(Val->getType());
1231 int VLen = Ty->getNumElements();
1232 SmallVector<Constant*, 8> Indices;
1234 // Create a vector of consecutive numbers from zero to VF.
1235 for (int i = 0; i < VLen; ++i) {
1236 int64_t Idx = Negate ? (-i) : i;
1237 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1240 // Add the consecutive indices to the vector value.
1241 Constant *Cv = ConstantVector::get(Indices);
1242 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1243 return Builder.CreateAdd(Val, Cv, "induction");
1246 /// \brief Find the operand of the GEP that should be checked for consecutive
1247 /// stores. This ignores trailing indices that have no effect on the final
1249 static unsigned getGEPInductionOperand(DataLayout *DL,
1250 const GetElementPtrInst *Gep) {
1251 unsigned LastOperand = Gep->getNumOperands() - 1;
1252 unsigned GEPAllocSize = DL->getTypeAllocSize(
1253 cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
1255 // Walk backwards and try to peel off zeros.
1256 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1257 // Find the type we're currently indexing into.
1258 gep_type_iterator GEPTI = gep_type_begin(Gep);
1259 std::advance(GEPTI, LastOperand - 1);
1261 // If it's a type with the same allocation size as the result of the GEP we
1262 // can peel off the zero index.
1263 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
1271 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1272 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
1273 // Make sure that the pointer does not point to structs.
1274 if (Ptr->getType()->getPointerElementType()->isAggregateType())
1277 // If this value is a pointer induction variable we know it is consecutive.
1278 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1279 if (Phi && Inductions.count(Phi)) {
1280 InductionInfo II = Inductions[Phi];
1281 if (IK_PtrInduction == II.IK)
1283 else if (IK_ReversePtrInduction == II.IK)
1287 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1291 unsigned NumOperands = Gep->getNumOperands();
1292 Value *GpPtr = Gep->getPointerOperand();
1293 // If this GEP value is a consecutive pointer induction variable and all of
1294 // the indices are constant then we know it is consecutive. We can
1295 Phi = dyn_cast<PHINode>(GpPtr);
1296 if (Phi && Inductions.count(Phi)) {
1298 // Make sure that the pointer does not point to structs.
1299 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1300 if (GepPtrType->getElementType()->isAggregateType())
1303 // Make sure that all of the index operands are loop invariant.
1304 for (unsigned i = 1; i < NumOperands; ++i)
1305 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1308 InductionInfo II = Inductions[Phi];
1309 if (IK_PtrInduction == II.IK)
1311 else if (IK_ReversePtrInduction == II.IK)
1315 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1317 // Check that all of the gep indices are uniform except for our induction
1319 for (unsigned i = 0; i != NumOperands; ++i)
1320 if (i != InductionOperand &&
1321 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1324 // We can emit wide load/stores only if the last non-zero index is the
1325 // induction variable.
1326 const SCEV *Last = 0;
1327 if (!Strides.count(Gep))
1328 Last = SE->getSCEV(Gep->getOperand(InductionOperand));
1330 // Because of the multiplication by a stride we can have a s/zext cast.
1331 // We are going to replace this stride by 1 so the cast is safe to ignore.
1333 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
1334 // %0 = trunc i64 %indvars.iv to i32
1335 // %mul = mul i32 %0, %Stride1
1336 // %idxprom = zext i32 %mul to i64 << Safe cast.
1337 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
1339 Last = replaceSymbolicStrideSCEV(SE, Strides,
1340 Gep->getOperand(InductionOperand), Gep);
1341 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
1343 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
1347 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1348 const SCEV *Step = AR->getStepRecurrence(*SE);
1350 // The memory is consecutive because the last index is consecutive
1351 // and all other indices are loop invariant.
1354 if (Step->isAllOnesValue())
1361 bool LoopVectorizationLegality::isUniform(Value *V) {
1362 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1365 InnerLoopVectorizer::VectorParts&
1366 InnerLoopVectorizer::getVectorValue(Value *V) {
1367 assert(V != Induction && "The new induction variable should not be used.");
1368 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1370 // If we have a stride that is replaced by one, do it here.
1371 if (Legal->hasStride(V))
1372 V = ConstantInt::get(V->getType(), 1);
1374 // If we have this scalar in the map, return it.
1375 if (WidenMap.has(V))
1376 return WidenMap.get(V);
1378 // If this scalar is unknown, assume that it is a constant or that it is
1379 // loop invariant. Broadcast V and save the value for future uses.
1380 Value *B = getBroadcastInstrs(V);
1381 return WidenMap.splat(V, B);
1384 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1385 assert(Vec->getType()->isVectorTy() && "Invalid type");
1386 SmallVector<Constant*, 8> ShuffleMask;
1387 for (unsigned i = 0; i < VF; ++i)
1388 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1390 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1391 ConstantVector::get(ShuffleMask),
1395 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
1396 // Attempt to issue a wide load.
1397 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1398 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1400 assert((LI || SI) && "Invalid Load/Store instruction");
1402 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1403 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1404 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1405 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1406 // An alignment of 0 means target abi alignment. We need to use the scalar's
1407 // target abi alignment in such a case.
1409 Alignment = DL->getABITypeAlignment(ScalarDataTy);
1410 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1411 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1412 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1414 if (ScalarAllocatedSize != VectorElementSize)
1415 return scalarizeInstruction(Instr);
1417 // If the pointer is loop invariant or if it is non-consecutive,
1418 // scalarize the load.
1419 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1420 bool Reverse = ConsecutiveStride < 0;
1421 bool UniformLoad = LI && Legal->isUniform(Ptr);
1422 if (!ConsecutiveStride || UniformLoad)
1423 return scalarizeInstruction(Instr);
1425 Constant *Zero = Builder.getInt32(0);
1426 VectorParts &Entry = WidenMap.get(Instr);
1428 // Handle consecutive loads/stores.
1429 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1430 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1431 setDebugLocFromInst(Builder, Gep);
1432 Value *PtrOperand = Gep->getPointerOperand();
1433 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1434 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1436 // Create the new GEP with the new induction variable.
1437 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1438 Gep2->setOperand(0, FirstBasePtr);
1439 Gep2->setName("gep.indvar.base");
1440 Ptr = Builder.Insert(Gep2);
1442 setDebugLocFromInst(Builder, Gep);
1443 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1444 OrigLoop) && "Base ptr must be invariant");
1446 // The last index does not have to be the induction. It can be
1447 // consecutive and be a function of the index. For example A[I+1];
1448 unsigned NumOperands = Gep->getNumOperands();
1449 unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
1450 // Create the new GEP with the new induction variable.
1451 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1453 for (unsigned i = 0; i < NumOperands; ++i) {
1454 Value *GepOperand = Gep->getOperand(i);
1455 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1457 // Update last index or loop invariant instruction anchored in loop.
1458 if (i == InductionOperand ||
1459 (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1460 assert((i == InductionOperand ||
1461 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1462 "Must be last index or loop invariant");
1464 VectorParts &GEPParts = getVectorValue(GepOperand);
1465 Value *Index = GEPParts[0];
1466 Index = Builder.CreateExtractElement(Index, Zero);
1467 Gep2->setOperand(i, Index);
1468 Gep2->setName("gep.indvar.idx");
1471 Ptr = Builder.Insert(Gep2);
1473 // Use the induction element ptr.
1474 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1475 setDebugLocFromInst(Builder, Ptr);
1476 VectorParts &PtrVal = getVectorValue(Ptr);
1477 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1482 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1483 "We do not allow storing to uniform addresses");
1484 setDebugLocFromInst(Builder, SI);
1485 // We don't want to update the value in the map as it might be used in
1486 // another expression. So don't use a reference type for "StoredVal".
1487 VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1489 for (unsigned Part = 0; Part < UF; ++Part) {
1490 // Calculate the pointer for the specific unroll-part.
1491 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1494 // If we store to reverse consecutive memory locations then we need
1495 // to reverse the order of elements in the stored value.
1496 StoredVal[Part] = reverseVector(StoredVal[Part]);
1497 // If the address is consecutive but reversed, then the
1498 // wide store needs to start at the last vector element.
1499 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1500 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1503 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1504 DataTy->getPointerTo(AddressSpace));
1505 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1511 assert(LI && "Must have a load instruction");
1512 setDebugLocFromInst(Builder, LI);
1513 for (unsigned Part = 0; Part < UF; ++Part) {
1514 // Calculate the pointer for the specific unroll-part.
1515 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1518 // If the address is consecutive but reversed, then the
1519 // wide store needs to start at the last vector element.
1520 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1521 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1524 Value *VecPtr = Builder.CreateBitCast(PartPtr,
1525 DataTy->getPointerTo(AddressSpace));
1526 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1527 cast<LoadInst>(LI)->setAlignment(Alignment);
1528 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1532 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1533 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1534 // Holds vector parameters or scalars, in case of uniform vals.
1535 SmallVector<VectorParts, 4> Params;
1537 setDebugLocFromInst(Builder, Instr);
1539 // Find all of the vectorized parameters.
1540 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1541 Value *SrcOp = Instr->getOperand(op);
1543 // If we are accessing the old induction variable, use the new one.
1544 if (SrcOp == OldInduction) {
1545 Params.push_back(getVectorValue(SrcOp));
1549 // Try using previously calculated values.
1550 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1552 // If the src is an instruction that appeared earlier in the basic block
1553 // then it should already be vectorized.
1554 if (SrcInst && OrigLoop->contains(SrcInst)) {
1555 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1556 // The parameter is a vector value from earlier.
1557 Params.push_back(WidenMap.get(SrcInst));
1559 // The parameter is a scalar from outside the loop. Maybe even a constant.
1560 VectorParts Scalars;
1561 Scalars.append(UF, SrcOp);
1562 Params.push_back(Scalars);
1566 assert(Params.size() == Instr->getNumOperands() &&
1567 "Invalid number of operands");
1569 // Does this instruction return a value ?
1570 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1572 Value *UndefVec = IsVoidRetTy ? 0 :
1573 UndefValue::get(VectorType::get(Instr->getType(), VF));
1574 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1575 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1577 // For each vector unroll 'part':
1578 for (unsigned Part = 0; Part < UF; ++Part) {
1579 // For each scalar that we create:
1580 for (unsigned Width = 0; Width < VF; ++Width) {
1581 Instruction *Cloned = Instr->clone();
1583 Cloned->setName(Instr->getName() + ".cloned");
1584 // Replace the operands of the cloned instructions with extracted scalars.
1585 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1586 Value *Op = Params[op][Part];
1587 // Param is a vector. Need to extract the right lane.
1588 if (Op->getType()->isVectorTy())
1589 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1590 Cloned->setOperand(op, Op);
1593 // Place the cloned scalar in the new loop.
1594 Builder.Insert(Cloned);
1596 // If the original scalar returns a value we need to place it in a vector
1597 // so that future users will be able to use it.
1599 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1600 Builder.getInt32(Width));
1605 static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
1609 if (Instruction *I = dyn_cast<Instruction>(V))
1610 return I->getParent() == Loc->getParent() ? I : 0;
1614 std::pair<Instruction *, Instruction *>
1615 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
1616 Instruction *tnullptr = 0;
1617 if (!Legal->mustCheckStrides())
1618 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1620 IRBuilder<> ChkBuilder(Loc);
1624 Instruction *FirstInst = 0;
1625 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1626 SE = Legal->strides_end();
1628 Value *Ptr = stripIntegerCast(*SI);
1629 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1631 // Store the first instruction we create.
1632 FirstInst = getFirstInst(FirstInst, C, Loc);
1634 Check = ChkBuilder.CreateOr(Check, C);
1639 // We have to do this trickery because the IRBuilder might fold the check to a
1640 // constant expression in which case there is no Instruction anchored in a
1642 LLVMContext &Ctx = Loc->getContext();
1643 Instruction *TheCheck =
1644 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1645 ChkBuilder.Insert(TheCheck, "stride.not.one");
1646 FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1648 return std::make_pair(FirstInst, TheCheck);
1651 std::pair<Instruction *, Instruction *>
1652 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1653 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1654 Legal->getRuntimePointerCheck();
1656 Instruction *tnullptr = 0;
1657 if (!PtrRtCheck->Need)
1658 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1660 unsigned NumPointers = PtrRtCheck->Pointers.size();
1661 SmallVector<TrackingVH<Value> , 2> Starts;
1662 SmallVector<TrackingVH<Value> , 2> Ends;
1664 LLVMContext &Ctx = Loc->getContext();
1665 SCEVExpander Exp(*SE, "induction");
1666 Instruction *FirstInst = 0;
1668 for (unsigned i = 0; i < NumPointers; ++i) {
1669 Value *Ptr = PtrRtCheck->Pointers[i];
1670 const SCEV *Sc = SE->getSCEV(Ptr);
1672 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1673 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1675 Starts.push_back(Ptr);
1676 Ends.push_back(Ptr);
1678 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1679 unsigned AS = Ptr->getType()->getPointerAddressSpace();
1681 // Use this type for pointer arithmetic.
1682 Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1684 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1685 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1686 Starts.push_back(Start);
1687 Ends.push_back(End);
1691 IRBuilder<> ChkBuilder(Loc);
1692 // Our instructions might fold to a constant.
1693 Value *MemoryRuntimeCheck = 0;
1694 for (unsigned i = 0; i < NumPointers; ++i) {
1695 for (unsigned j = i+1; j < NumPointers; ++j) {
1696 // No need to check if two readonly pointers intersect.
1697 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1700 // Only need to check pointers between two different dependency sets.
1701 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1704 unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1705 unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1707 assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1708 (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1709 "Trying to bounds check pointers with different address spaces");
1711 Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1712 Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1714 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1715 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1716 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
1717 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
1719 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1720 FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1721 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1722 FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1723 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1724 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1725 if (MemoryRuntimeCheck) {
1726 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1728 FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1730 MemoryRuntimeCheck = IsConflict;
1734 // We have to do this trickery because the IRBuilder might fold the check to a
1735 // constant expression in which case there is no Instruction anchored in a
1737 Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1738 ConstantInt::getTrue(Ctx));
1739 ChkBuilder.Insert(Check, "memcheck.conflict");
1740 FirstInst = getFirstInst(FirstInst, Check, Loc);
1741 return std::make_pair(FirstInst, Check);
1744 void InnerLoopVectorizer::createEmptyLoop() {
1746 In this function we generate a new loop. The new loop will contain
1747 the vectorized instructions while the old loop will continue to run the
1750 [ ] <-- vector loop bypass (may consist of multiple blocks).
1753 | [ ] <-- vector pre header.
1757 | [ ]_| <-- vector loop.
1760 >[ ] <--- middle-block.
1763 | [ ] <--- new preheader.
1767 | [ ]_| <-- old scalar loop to handle remainder.
1770 >[ ] <-- exit block.
1774 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1775 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1776 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1777 assert(ExitBlock && "Must have an exit block");
1779 // Some loops have a single integer induction variable, while other loops
1780 // don't. One example is c++ iterators that often have multiple pointer
1781 // induction variables. In the code below we also support a case where we
1782 // don't have a single induction variable.
1783 OldInduction = Legal->getInduction();
1784 Type *IdxTy = Legal->getWidestInductionType();
1786 // Find the loop boundaries.
1787 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1788 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1790 // The exit count might have the type of i64 while the phi is i32. This can
1791 // happen if we have an induction variable that is sign extended before the
1792 // compare. The only way that we get a backedge taken count is that the
1793 // induction variable was signed and as such will not overflow. In such a case
1794 // truncation is legal.
1795 if (ExitCount->getType()->getPrimitiveSizeInBits() >
1796 IdxTy->getPrimitiveSizeInBits())
1797 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1799 ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1800 // Get the total trip count from the count by adding 1.
1801 ExitCount = SE->getAddExpr(ExitCount,
1802 SE->getConstant(ExitCount->getType(), 1));
1804 // Expand the trip count and place the new instructions in the preheader.
1805 // Notice that the pre-header does not change, only the loop body.
1806 SCEVExpander Exp(*SE, "induction");
1808 // Count holds the overall loop count (N).
1809 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1810 BypassBlock->getTerminator());
1812 // The loop index does not have to start at Zero. Find the original start
1813 // value from the induction PHI node. If we don't have an induction variable
1814 // then we know that it starts at zero.
1815 Builder.SetInsertPoint(BypassBlock->getTerminator());
1816 Value *StartIdx = ExtendedIdx = OldInduction ?
1817 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1819 ConstantInt::get(IdxTy, 0);
1821 assert(BypassBlock && "Invalid loop structure");
1822 LoopBypassBlocks.push_back(BypassBlock);
1824 // Split the single block loop into the two loop structure described above.
1825 BasicBlock *VectorPH =
1826 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1827 BasicBlock *VecBody =
1828 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1829 BasicBlock *MiddleBlock =
1830 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1831 BasicBlock *ScalarPH =
1832 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1834 // Create and register the new vector loop.
1835 Loop* Lp = new Loop();
1836 Loop *ParentLoop = OrigLoop->getParentLoop();
1838 // Insert the new loop into the loop nest and register the new basic blocks
1839 // before calling any utilities such as SCEV that require valid LoopInfo.
1841 ParentLoop->addChildLoop(Lp);
1842 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1843 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1844 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1846 LI->addTopLevelLoop(Lp);
1848 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1850 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1852 Builder.SetInsertPoint(VecBody->getFirstNonPHI());
1854 // Generate the induction variable.
1855 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1856 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1857 // The loop step is equal to the vectorization factor (num of SIMD elements)
1858 // times the unroll factor (num of SIMD instructions).
1859 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1861 // This is the IR builder that we use to add all of the logic for bypassing
1862 // the new vector loop.
1863 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1864 setDebugLocFromInst(BypassBuilder,
1865 getDebugLocFromInstOrOperands(OldInduction));
1867 // We may need to extend the index in case there is a type mismatch.
1868 // We know that the count starts at zero and does not overflow.
1869 if (Count->getType() != IdxTy) {
1870 // The exit count can be of pointer type. Convert it to the correct
1872 if (ExitCount->getType()->isPointerTy())
1873 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1875 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1878 // Add the start index to the loop count to get the new end index.
1879 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1881 // Now we need to generate the expression for N - (N % VF), which is
1882 // the part that the vectorized body will execute.
1883 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1884 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1885 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1886 "end.idx.rnd.down");
1888 // Now, compare the new count to zero. If it is zero skip the vector loop and
1889 // jump to the scalar loop.
1890 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1893 BasicBlock *LastBypassBlock = BypassBlock;
1895 // Generate the code to check that the strides we assumed to be one are really
1896 // one. We want the new basic block to start at the first instruction in a
1897 // sequence of instructions that form a check.
1898 Instruction *StrideCheck;
1899 Instruction *FirstCheckInst;
1900 tie(FirstCheckInst, StrideCheck) =
1901 addStrideCheck(BypassBlock->getTerminator());
1903 // Create a new block containing the stride check.
1904 BasicBlock *CheckBlock =
1905 BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
1907 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1908 LoopBypassBlocks.push_back(CheckBlock);
1910 // Replace the branch into the memory check block with a conditional branch
1911 // for the "few elements case".
1912 Instruction *OldTerm = BypassBlock->getTerminator();
1913 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1914 OldTerm->eraseFromParent();
1917 LastBypassBlock = CheckBlock;
1920 // Generate the code that checks in runtime if arrays overlap. We put the
1921 // checks into a separate block to make the more common case of few elements
1923 Instruction *MemRuntimeCheck;
1924 tie(FirstCheckInst, MemRuntimeCheck) =
1925 addRuntimeCheck(LastBypassBlock->getTerminator());
1926 if (MemRuntimeCheck) {
1927 // Create a new block containing the memory check.
1928 BasicBlock *CheckBlock =
1929 LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
1931 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1932 LoopBypassBlocks.push_back(CheckBlock);
1934 // Replace the branch into the memory check block with a conditional branch
1935 // for the "few elements case".
1936 Instruction *OldTerm = LastBypassBlock->getTerminator();
1937 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1938 OldTerm->eraseFromParent();
1940 Cmp = MemRuntimeCheck;
1941 LastBypassBlock = CheckBlock;
1944 LastBypassBlock->getTerminator()->eraseFromParent();
1945 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1948 // We are going to resume the execution of the scalar loop.
1949 // Go over all of the induction variables that we found and fix the
1950 // PHIs that are left in the scalar version of the loop.
1951 // The starting values of PHI nodes depend on the counter of the last
1952 // iteration in the vectorized loop.
1953 // If we come from a bypass edge then we need to start from the original
1956 // This variable saves the new starting index for the scalar loop.
1957 PHINode *ResumeIndex = 0;
1958 LoopVectorizationLegality::InductionList::iterator I, E;
1959 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1960 // Set builder to point to last bypass block.
1961 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1962 for (I = List->begin(), E = List->end(); I != E; ++I) {
1963 PHINode *OrigPhi = I->first;
1964 LoopVectorizationLegality::InductionInfo II = I->second;
1966 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1967 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1968 MiddleBlock->getTerminator());
1969 // We might have extended the type of the induction variable but we need a
1970 // truncated version for the scalar loop.
1971 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1972 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1973 MiddleBlock->getTerminator()) : 0;
1975 Value *EndValue = 0;
1977 case LoopVectorizationLegality::IK_NoInduction:
1978 llvm_unreachable("Unknown induction");
1979 case LoopVectorizationLegality::IK_IntInduction: {
1980 // Handle the integer induction counter.
1981 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1983 // We have the canonical induction variable.
1984 if (OrigPhi == OldInduction) {
1985 // Create a truncated version of the resume value for the scalar loop,
1986 // we might have promoted the type to a larger width.
1988 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1989 // The new PHI merges the original incoming value, in case of a bypass,
1990 // or the value at the end of the vectorized loop.
1991 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1992 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1993 TruncResumeVal->addIncoming(EndValue, VecBody);
1995 // We know what the end value is.
1996 EndValue = IdxEndRoundDown;
1997 // We also know which PHI node holds it.
1998 ResumeIndex = ResumeVal;
2002 // Not the canonical induction variable - add the vector loop count to the
2004 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2005 II.StartValue->getType(),
2007 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
2010 case LoopVectorizationLegality::IK_ReverseIntInduction: {
2011 // Convert the CountRoundDown variable to the PHI size.
2012 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
2013 II.StartValue->getType(),
2015 // Handle reverse integer induction counter.
2016 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
2019 case LoopVectorizationLegality::IK_PtrInduction: {
2020 // For pointer induction variables, calculate the offset using
2022 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
2026 case LoopVectorizationLegality::IK_ReversePtrInduction: {
2027 // The value at the end of the loop for the reverse pointer is calculated
2028 // by creating a GEP with a negative index starting from the start value.
2029 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
2030 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
2032 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
2038 // The new PHI merges the original incoming value, in case of a bypass,
2039 // or the value at the end of the vectorized loop.
2040 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
2041 if (OrigPhi == OldInduction)
2042 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
2044 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
2046 ResumeVal->addIncoming(EndValue, VecBody);
2048 // Fix the scalar body counter (PHI node).
2049 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
2050 // The old inductions phi node in the scalar body needs the truncated value.
2051 if (OrigPhi == OldInduction)
2052 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
2054 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
2057 // If we are generating a new induction variable then we also need to
2058 // generate the code that calculates the exit value. This value is not
2059 // simply the end of the counter because we may skip the vectorized body
2060 // in case of a runtime check.
2062 assert(!ResumeIndex && "Unexpected resume value found");
2063 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
2064 MiddleBlock->getTerminator());
2065 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2066 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
2067 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
2070 // Make sure that we found the index where scalar loop needs to continue.
2071 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
2072 "Invalid resume Index");
2074 // Add a check in the middle block to see if we have completed
2075 // all of the iterations in the first vector loop.
2076 // If (N - N%VF) == N, then we *don't* need to run the remainder.
2077 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2078 ResumeIndex, "cmp.n",
2079 MiddleBlock->getTerminator());
2081 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2082 // Remove the old terminator.
2083 MiddleBlock->getTerminator()->eraseFromParent();
2085 // Create i+1 and fill the PHINode.
2086 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2087 Induction->addIncoming(StartIdx, VectorPH);
2088 Induction->addIncoming(NextIdx, VecBody);
2089 // Create the compare.
2090 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2091 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2093 // Now we have two terminators. Remove the old one from the block.
2094 VecBody->getTerminator()->eraseFromParent();
2096 // Get ready to start creating new instructions into the vectorized body.
2097 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2100 LoopVectorPreHeader = VectorPH;
2101 LoopScalarPreHeader = ScalarPH;
2102 LoopMiddleBlock = MiddleBlock;
2103 LoopExitBlock = ExitBlock;
2104 LoopVectorBody = VecBody;
2105 LoopScalarBody = OldBasicBlock;
2107 LoopVectorizeHints Hints(Lp, true);
2108 Hints.setAlreadyVectorized(Lp);
2111 /// This function returns the identity element (or neutral element) for
2112 /// the operation K.
2114 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2119 // Adding, Xoring, Oring zero to a number does not change it.
2120 return ConstantInt::get(Tp, 0);
2121 case RK_IntegerMult:
2122 // Multiplying a number by 1 does not change it.
2123 return ConstantInt::get(Tp, 1);
2125 // AND-ing a number with an all-1 value does not change it.
2126 return ConstantInt::get(Tp, -1, true);
2128 // Multiplying a number by 1 does not change it.
2129 return ConstantFP::get(Tp, 1.0L);
2131 // Adding zero to a number does not change it.
2132 return ConstantFP::get(Tp, 0.0L);
2134 llvm_unreachable("Unknown reduction kind");
2138 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2139 Intrinsic::ID ValidIntrinsicID) {
2140 if (I.getNumArgOperands() != 1 ||
2141 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2142 I.getType() != I.getArgOperand(0)->getType() ||
2143 !I.onlyReadsMemory())
2144 return Intrinsic::not_intrinsic;
2146 return ValidIntrinsicID;
2149 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2150 Intrinsic::ID ValidIntrinsicID) {
2151 if (I.getNumArgOperands() != 2 ||
2152 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2153 !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2154 I.getType() != I.getArgOperand(0)->getType() ||
2155 I.getType() != I.getArgOperand(1)->getType() ||
2156 !I.onlyReadsMemory())
2157 return Intrinsic::not_intrinsic;
2159 return ValidIntrinsicID;
2163 static Intrinsic::ID
2164 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2165 // If we have an intrinsic call, check if it is trivially vectorizable.
2166 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2167 switch (II->getIntrinsicID()) {
2168 case Intrinsic::sqrt:
2169 case Intrinsic::sin:
2170 case Intrinsic::cos:
2171 case Intrinsic::exp:
2172 case Intrinsic::exp2:
2173 case Intrinsic::log:
2174 case Intrinsic::log10:
2175 case Intrinsic::log2:
2176 case Intrinsic::fabs:
2177 case Intrinsic::copysign:
2178 case Intrinsic::floor:
2179 case Intrinsic::ceil:
2180 case Intrinsic::trunc:
2181 case Intrinsic::rint:
2182 case Intrinsic::nearbyint:
2183 case Intrinsic::round:
2184 case Intrinsic::pow:
2185 case Intrinsic::fma:
2186 case Intrinsic::fmuladd:
2187 case Intrinsic::lifetime_start:
2188 case Intrinsic::lifetime_end:
2189 return II->getIntrinsicID();
2191 return Intrinsic::not_intrinsic;
2196 return Intrinsic::not_intrinsic;
2199 Function *F = CI->getCalledFunction();
2200 // We're going to make assumptions on the semantics of the functions, check
2201 // that the target knows that it's available in this environment and it does
2202 // not have local linkage.
2203 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2204 return Intrinsic::not_intrinsic;
2206 // Otherwise check if we have a call to a function that can be turned into a
2207 // vector intrinsic.
2214 return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2218 return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2222 return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2224 case LibFunc::exp2f:
2225 case LibFunc::exp2l:
2226 return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2230 return checkUnaryFloatSignature(*CI, Intrinsic::log);
2231 case LibFunc::log10:
2232 case LibFunc::log10f:
2233 case LibFunc::log10l:
2234 return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2236 case LibFunc::log2f:
2237 case LibFunc::log2l:
2238 return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2240 case LibFunc::fabsf:
2241 case LibFunc::fabsl:
2242 return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2243 case LibFunc::copysign:
2244 case LibFunc::copysignf:
2245 case LibFunc::copysignl:
2246 return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2247 case LibFunc::floor:
2248 case LibFunc::floorf:
2249 case LibFunc::floorl:
2250 return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2252 case LibFunc::ceilf:
2253 case LibFunc::ceill:
2254 return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2255 case LibFunc::trunc:
2256 case LibFunc::truncf:
2257 case LibFunc::truncl:
2258 return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2260 case LibFunc::rintf:
2261 case LibFunc::rintl:
2262 return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2263 case LibFunc::nearbyint:
2264 case LibFunc::nearbyintf:
2265 case LibFunc::nearbyintl:
2266 return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2267 case LibFunc::round:
2268 case LibFunc::roundf:
2269 case LibFunc::roundl:
2270 return checkUnaryFloatSignature(*CI, Intrinsic::round);
2274 return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2277 return Intrinsic::not_intrinsic;
2280 /// This function translates the reduction kind to an LLVM binary operator.
2282 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2284 case LoopVectorizationLegality::RK_IntegerAdd:
2285 return Instruction::Add;
2286 case LoopVectorizationLegality::RK_IntegerMult:
2287 return Instruction::Mul;
2288 case LoopVectorizationLegality::RK_IntegerOr:
2289 return Instruction::Or;
2290 case LoopVectorizationLegality::RK_IntegerAnd:
2291 return Instruction::And;
2292 case LoopVectorizationLegality::RK_IntegerXor:
2293 return Instruction::Xor;
2294 case LoopVectorizationLegality::RK_FloatMult:
2295 return Instruction::FMul;
2296 case LoopVectorizationLegality::RK_FloatAdd:
2297 return Instruction::FAdd;
2298 case LoopVectorizationLegality::RK_IntegerMinMax:
2299 return Instruction::ICmp;
2300 case LoopVectorizationLegality::RK_FloatMinMax:
2301 return Instruction::FCmp;
2303 llvm_unreachable("Unknown reduction operation");
2307 Value *createMinMaxOp(IRBuilder<> &Builder,
2308 LoopVectorizationLegality::MinMaxReductionKind RK,
2311 CmpInst::Predicate P = CmpInst::ICMP_NE;
2314 llvm_unreachable("Unknown min/max reduction kind");
2315 case LoopVectorizationLegality::MRK_UIntMin:
2316 P = CmpInst::ICMP_ULT;
2318 case LoopVectorizationLegality::MRK_UIntMax:
2319 P = CmpInst::ICMP_UGT;
2321 case LoopVectorizationLegality::MRK_SIntMin:
2322 P = CmpInst::ICMP_SLT;
2324 case LoopVectorizationLegality::MRK_SIntMax:
2325 P = CmpInst::ICMP_SGT;
2327 case LoopVectorizationLegality::MRK_FloatMin:
2328 P = CmpInst::FCMP_OLT;
2330 case LoopVectorizationLegality::MRK_FloatMax:
2331 P = CmpInst::FCMP_OGT;
2336 if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2337 RK == LoopVectorizationLegality::MRK_FloatMax)
2338 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2340 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2342 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2347 struct CSEDenseMapInfo {
2348 static bool canHandle(Instruction *I) {
2349 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2350 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2352 static inline Instruction *getEmptyKey() {
2353 return DenseMapInfo<Instruction *>::getEmptyKey();
2355 static inline Instruction *getTombstoneKey() {
2356 return DenseMapInfo<Instruction *>::getTombstoneKey();
2358 static unsigned getHashValue(Instruction *I) {
2359 assert(canHandle(I) && "Unknown instruction!");
2360 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2361 I->value_op_end()));
2363 static bool isEqual(Instruction *LHS, Instruction *RHS) {
2364 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2365 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2367 return LHS->isIdenticalTo(RHS);
2372 ///\brief Perform cse of induction variable instructions.
2373 static void cse(BasicBlock *BB) {
2374 // Perform simple cse.
2375 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2376 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2377 Instruction *In = I++;
2379 if (!CSEDenseMapInfo::canHandle(In))
2382 // Check if we can replace this instruction with any of the
2383 // visited instructions.
2384 if (Instruction *V = CSEMap.lookup(In)) {
2385 In->replaceAllUsesWith(V);
2386 In->eraseFromParent();
2394 void InnerLoopVectorizer::vectorizeLoop() {
2395 //===------------------------------------------------===//
2397 // Notice: any optimization or new instruction that go
2398 // into the code below should be also be implemented in
2401 //===------------------------------------------------===//
2402 Constant *Zero = Builder.getInt32(0);
2404 // In order to support reduction variables we need to be able to vectorize
2405 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2406 // stages. First, we create a new vector PHI node with no incoming edges.
2407 // We use this value when we vectorize all of the instructions that use the
2408 // PHI. Next, after all of the instructions in the block are complete we
2409 // add the new incoming edges to the PHI. At this point all of the
2410 // instructions in the basic block are vectorized, so we can use them to
2411 // construct the PHI.
2412 PhiVector RdxPHIsToFix;
2414 // Scan the loop in a topological order to ensure that defs are vectorized
2416 LoopBlocksDFS DFS(OrigLoop);
2419 // Vectorize all of the blocks in the original loop.
2420 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2421 be = DFS.endRPO(); bb != be; ++bb)
2422 vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2424 // At this point every instruction in the original loop is widened to
2425 // a vector form. We are almost done. Now, we need to fix the PHI nodes
2426 // that we vectorized. The PHI nodes are currently empty because we did
2427 // not want to introduce cycles. Notice that the remaining PHI nodes
2428 // that we need to fix are reduction variables.
2430 // Create the 'reduced' values for each of the induction vars.
2431 // The reduced values are the vector values that we scalarize and combine
2432 // after the loop is finished.
2433 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2435 PHINode *RdxPhi = *it;
2436 assert(RdxPhi && "Unable to recover vectorized PHI");
2438 // Find the reduction variable descriptor.
2439 assert(Legal->getReductionVars()->count(RdxPhi) &&
2440 "Unable to find the reduction variable");
2441 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2442 (*Legal->getReductionVars())[RdxPhi];
2444 setDebugLocFromInst(Builder, RdxDesc.StartValue);
2446 // We need to generate a reduction vector from the incoming scalar.
2447 // To do so, we need to generate the 'identity' vector and override
2448 // one of the elements with the incoming scalar reduction. We need
2449 // to do it in the vector-loop preheader.
2450 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2452 // This is the vector-clone of the value that leaves the loop.
2453 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2454 Type *VecTy = VectorExit[0]->getType();
2456 // Find the reduction identity variable. Zero for addition, or, xor,
2457 // one for multiplication, -1 for And.
2460 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2461 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2462 // MinMax reduction have the start value as their identify.
2464 VectorStart = Identity = RdxDesc.StartValue;
2466 VectorStart = Identity = Builder.CreateVectorSplat(VF,
2471 // Handle other reduction kinds:
2473 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2474 VecTy->getScalarType());
2477 // This vector is the Identity vector where the first element is the
2478 // incoming scalar reduction.
2479 VectorStart = RdxDesc.StartValue;
2481 Identity = ConstantVector::getSplat(VF, Iden);
2483 // This vector is the Identity vector where the first element is the
2484 // incoming scalar reduction.
2485 VectorStart = Builder.CreateInsertElement(Identity,
2486 RdxDesc.StartValue, Zero);
2490 // Fix the vector-loop phi.
2491 // We created the induction variable so we know that the
2492 // preheader is the first entry.
2493 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2495 // Reductions do not have to start at zero. They can start with
2496 // any loop invariant values.
2497 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2498 BasicBlock *Latch = OrigLoop->getLoopLatch();
2499 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2500 VectorParts &Val = getVectorValue(LoopVal);
2501 for (unsigned part = 0; part < UF; ++part) {
2502 // Make sure to add the reduction stat value only to the
2503 // first unroll part.
2504 Value *StartVal = (part == 0) ? VectorStart : Identity;
2505 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2506 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2509 // Before each round, move the insertion point right between
2510 // the PHIs and the values we are going to write.
2511 // This allows us to write both PHINodes and the extractelement
2513 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2515 VectorParts RdxParts;
2516 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2517 for (unsigned part = 0; part < UF; ++part) {
2518 // This PHINode contains the vectorized reduction variable, or
2519 // the initial value vector, if we bypass the vector loop.
2520 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2521 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2522 Value *StartVal = (part == 0) ? VectorStart : Identity;
2523 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2524 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2525 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2526 RdxParts.push_back(NewPhi);
2529 // Reduce all of the unrolled parts into a single vector.
2530 Value *ReducedPartRdx = RdxParts[0];
2531 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2532 setDebugLocFromInst(Builder, ReducedPartRdx);
2533 for (unsigned part = 1; part < UF; ++part) {
2534 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2535 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2536 RdxParts[part], ReducedPartRdx,
2539 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2540 ReducedPartRdx, RdxParts[part]);
2544 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2545 // and vector ops, reducing the set of values being computed by half each
2547 assert(isPowerOf2_32(VF) &&
2548 "Reduction emission only supported for pow2 vectors!");
2549 Value *TmpVec = ReducedPartRdx;
2550 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2551 for (unsigned i = VF; i != 1; i >>= 1) {
2552 // Move the upper half of the vector to the lower half.
2553 for (unsigned j = 0; j != i/2; ++j)
2554 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2556 // Fill the rest of the mask with undef.
2557 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2558 UndefValue::get(Builder.getInt32Ty()));
2561 Builder.CreateShuffleVector(TmpVec,
2562 UndefValue::get(TmpVec->getType()),
2563 ConstantVector::get(ShuffleMask),
2566 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2567 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2570 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2573 // The result is in the first element of the vector.
2574 ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2575 Builder.getInt32(0));
2578 // Now, we need to fix the users of the reduction variable
2579 // inside and outside of the scalar remainder loop.
2580 // We know that the loop is in LCSSA form. We need to update the
2581 // PHI nodes in the exit blocks.
2582 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2583 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2584 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2585 if (!LCSSAPhi) break;
2587 // All PHINodes need to have a single entry edge, or two if
2588 // we already fixed them.
2589 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2591 // We found our reduction value exit-PHI. Update it with the
2592 // incoming bypass edge.
2593 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2594 // Add an edge coming from the bypass.
2595 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2598 }// end of the LCSSA phi scan.
2600 // Fix the scalar loop reduction variable with the incoming reduction sum
2601 // from the vector body and from the backedge value.
2602 int IncomingEdgeBlockIdx =
2603 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2604 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2605 // Pick the other block.
2606 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2607 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2608 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2609 }// end of for each redux variable.
2613 // Remove redundant induction instructions.
2614 cse(LoopVectorBody);
2617 void InnerLoopVectorizer::fixLCSSAPHIs() {
2618 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2619 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2620 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2621 if (!LCSSAPhi) break;
2622 if (LCSSAPhi->getNumIncomingValues() == 1)
2623 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2628 InnerLoopVectorizer::VectorParts
2629 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2630 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2633 // Look for cached value.
2634 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2635 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2636 if (ECEntryIt != MaskCache.end())
2637 return ECEntryIt->second;
2639 VectorParts SrcMask = createBlockInMask(Src);
2641 // The terminator has to be a branch inst!
2642 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2643 assert(BI && "Unexpected terminator found");
2645 if (BI->isConditional()) {
2646 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2648 if (BI->getSuccessor(0) != Dst)
2649 for (unsigned part = 0; part < UF; ++part)
2650 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2652 for (unsigned part = 0; part < UF; ++part)
2653 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2655 MaskCache[Edge] = EdgeMask;
2659 MaskCache[Edge] = SrcMask;
2663 InnerLoopVectorizer::VectorParts
2664 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2665 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2667 // Loop incoming mask is all-one.
2668 if (OrigLoop->getHeader() == BB) {
2669 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2670 return getVectorValue(C);
2673 // This is the block mask. We OR all incoming edges, and with zero.
2674 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2675 VectorParts BlockMask = getVectorValue(Zero);
2678 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2679 VectorParts EM = createEdgeMask(*it, BB);
2680 for (unsigned part = 0; part < UF; ++part)
2681 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2687 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2688 InnerLoopVectorizer::VectorParts &Entry,
2689 unsigned UF, unsigned VF, PhiVector *PV) {
2690 PHINode* P = cast<PHINode>(PN);
2691 // Handle reduction variables:
2692 if (Legal->getReductionVars()->count(P)) {
2693 for (unsigned part = 0; part < UF; ++part) {
2694 // This is phase one of vectorizing PHIs.
2695 Type *VecTy = (VF == 1) ? PN->getType() :
2696 VectorType::get(PN->getType(), VF);
2697 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2698 LoopVectorBody-> getFirstInsertionPt());
2704 setDebugLocFromInst(Builder, P);
2705 // Check for PHI nodes that are lowered to vector selects.
2706 if (P->getParent() != OrigLoop->getHeader()) {
2707 // We know that all PHIs in non-header blocks are converted into
2708 // selects, so we don't have to worry about the insertion order and we
2709 // can just use the builder.
2710 // At this point we generate the predication tree. There may be
2711 // duplications since this is a simple recursive scan, but future
2712 // optimizations will clean it up.
2714 unsigned NumIncoming = P->getNumIncomingValues();
2716 // Generate a sequence of selects of the form:
2717 // SELECT(Mask3, In3,
2718 // SELECT(Mask2, In2,
2720 for (unsigned In = 0; In < NumIncoming; In++) {
2721 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2723 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2725 for (unsigned part = 0; part < UF; ++part) {
2726 // We might have single edge PHIs (blocks) - use an identity
2727 // 'select' for the first PHI operand.
2729 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2732 // Select between the current value and the previous incoming edge
2733 // based on the incoming mask.
2734 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2735 Entry[part], "predphi");
2741 // This PHINode must be an induction variable.
2742 // Make sure that we know about it.
2743 assert(Legal->getInductionVars()->count(P) &&
2744 "Not an induction variable");
2746 LoopVectorizationLegality::InductionInfo II =
2747 Legal->getInductionVars()->lookup(P);
2750 case LoopVectorizationLegality::IK_NoInduction:
2751 llvm_unreachable("Unknown induction");
2752 case LoopVectorizationLegality::IK_IntInduction: {
2753 assert(P->getType() == II.StartValue->getType() && "Types must match");
2754 Type *PhiTy = P->getType();
2756 if (P == OldInduction) {
2757 // Handle the canonical induction variable. We might have had to
2759 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2761 // Handle other induction variables that are now based on the
2763 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2765 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2766 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2769 Broadcasted = getBroadcastInstrs(Broadcasted);
2770 // After broadcasting the induction variable we need to make the vector
2771 // consecutive by adding 0, 1, 2, etc.
2772 for (unsigned part = 0; part < UF; ++part)
2773 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2776 case LoopVectorizationLegality::IK_ReverseIntInduction:
2777 case LoopVectorizationLegality::IK_PtrInduction:
2778 case LoopVectorizationLegality::IK_ReversePtrInduction:
2779 // Handle reverse integer and pointer inductions.
2780 Value *StartIdx = ExtendedIdx;
2781 // This is the normalized GEP that starts counting at zero.
2782 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2785 // Handle the reverse integer induction variable case.
2786 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2787 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2788 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2790 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2793 // This is a new value so do not hoist it out.
2794 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2795 // After broadcasting the induction variable we need to make the
2796 // vector consecutive by adding ... -3, -2, -1, 0.
2797 for (unsigned part = 0; part < UF; ++part)
2798 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2803 // Handle the pointer induction variable case.
2804 assert(P->getType()->isPointerTy() && "Unexpected type.");
2806 // Is this a reverse induction ptr or a consecutive induction ptr.
2807 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2810 // This is the vector of results. Notice that we don't generate
2811 // vector geps because scalar geps result in better code.
2812 for (unsigned part = 0; part < UF; ++part) {
2814 int EltIndex = (part) * (Reverse ? -1 : 1);
2815 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2818 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2820 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2822 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2824 Entry[part] = SclrGep;
2828 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2829 for (unsigned int i = 0; i < VF; ++i) {
2830 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2831 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2834 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2836 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2838 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2840 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2841 Builder.getInt32(i),
2844 Entry[part] = VecVal;
2850 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2851 // For each instruction in the old loop.
2852 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2853 VectorParts &Entry = WidenMap.get(it);
2854 switch (it->getOpcode()) {
2855 case Instruction::Br:
2856 // Nothing to do for PHIs and BR, since we already took care of the
2857 // loop control flow instructions.
2859 case Instruction::PHI:{
2860 // Vectorize PHINodes.
2861 widenPHIInstruction(it, Entry, UF, VF, PV);
2865 case Instruction::Add:
2866 case Instruction::FAdd:
2867 case Instruction::Sub:
2868 case Instruction::FSub:
2869 case Instruction::Mul:
2870 case Instruction::FMul:
2871 case Instruction::UDiv:
2872 case Instruction::SDiv:
2873 case Instruction::FDiv:
2874 case Instruction::URem:
2875 case Instruction::SRem:
2876 case Instruction::FRem:
2877 case Instruction::Shl:
2878 case Instruction::LShr:
2879 case Instruction::AShr:
2880 case Instruction::And:
2881 case Instruction::Or:
2882 case Instruction::Xor: {
2883 // Just widen binops.
2884 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2885 setDebugLocFromInst(Builder, BinOp);
2886 VectorParts &A = getVectorValue(it->getOperand(0));
2887 VectorParts &B = getVectorValue(it->getOperand(1));
2889 // Use this vector value for all users of the original instruction.
2890 for (unsigned Part = 0; Part < UF; ++Part) {
2891 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2893 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2894 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2895 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2896 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2897 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2899 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2900 VecOp->setIsExact(BinOp->isExact());
2906 case Instruction::Select: {
2908 // If the selector is loop invariant we can create a select
2909 // instruction with a scalar condition. Otherwise, use vector-select.
2910 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2912 setDebugLocFromInst(Builder, it);
2914 // The condition can be loop invariant but still defined inside the
2915 // loop. This means that we can't just use the original 'cond' value.
2916 // We have to take the 'vectorized' value and pick the first lane.
2917 // Instcombine will make this a no-op.
2918 VectorParts &Cond = getVectorValue(it->getOperand(0));
2919 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2920 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2922 Value *ScalarCond = (VF == 1) ? Cond[0] :
2923 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
2925 for (unsigned Part = 0; Part < UF; ++Part) {
2926 Entry[Part] = Builder.CreateSelect(
2927 InvariantCond ? ScalarCond : Cond[Part],
2934 case Instruction::ICmp:
2935 case Instruction::FCmp: {
2936 // Widen compares. Generate vector compares.
2937 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2938 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2939 setDebugLocFromInst(Builder, it);
2940 VectorParts &A = getVectorValue(it->getOperand(0));
2941 VectorParts &B = getVectorValue(it->getOperand(1));
2942 for (unsigned Part = 0; Part < UF; ++Part) {
2945 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2947 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2953 case Instruction::Store:
2954 case Instruction::Load:
2955 vectorizeMemoryInstruction(it);
2957 case Instruction::ZExt:
2958 case Instruction::SExt:
2959 case Instruction::FPToUI:
2960 case Instruction::FPToSI:
2961 case Instruction::FPExt:
2962 case Instruction::PtrToInt:
2963 case Instruction::IntToPtr:
2964 case Instruction::SIToFP:
2965 case Instruction::UIToFP:
2966 case Instruction::Trunc:
2967 case Instruction::FPTrunc:
2968 case Instruction::BitCast: {
2969 CastInst *CI = dyn_cast<CastInst>(it);
2970 setDebugLocFromInst(Builder, it);
2971 /// Optimize the special case where the source is the induction
2972 /// variable. Notice that we can only optimize the 'trunc' case
2973 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2974 /// c. other casts depend on pointer size.
2975 if (CI->getOperand(0) == OldInduction &&
2976 it->getOpcode() == Instruction::Trunc) {
2977 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2979 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2980 for (unsigned Part = 0; Part < UF; ++Part)
2981 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2984 /// Vectorize casts.
2985 Type *DestTy = (VF == 1) ? CI->getType() :
2986 VectorType::get(CI->getType(), VF);
2988 VectorParts &A = getVectorValue(it->getOperand(0));
2989 for (unsigned Part = 0; Part < UF; ++Part)
2990 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2994 case Instruction::Call: {
2995 // Ignore dbg intrinsics.
2996 if (isa<DbgInfoIntrinsic>(it))
2998 setDebugLocFromInst(Builder, it);
3000 Module *M = BB->getParent()->getParent();
3001 CallInst *CI = cast<CallInst>(it);
3002 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3003 assert(ID && "Not an intrinsic call!");
3005 case Intrinsic::lifetime_end:
3006 case Intrinsic::lifetime_start:
3007 scalarizeInstruction(it);
3010 for (unsigned Part = 0; Part < UF; ++Part) {
3011 SmallVector<Value *, 4> Args;
3012 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
3013 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
3014 Args.push_back(Arg[Part]);
3016 Type *Tys[] = {CI->getType()};
3018 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
3020 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
3021 Entry[Part] = Builder.CreateCall(F, Args);
3029 // All other instructions are unsupported. Scalarize them.
3030 scalarizeInstruction(it);
3033 }// end of for_each instr.
3036 void InnerLoopVectorizer::updateAnalysis() {
3037 // Forget the original basic block.
3038 SE->forgetLoop(OrigLoop);
3040 // Update the dominator tree information.
3041 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
3042 "Entry does not dominate exit.");
3044 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
3045 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
3046 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
3047 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
3048 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
3049 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
3050 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
3051 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3053 DEBUG(DT->verifyDomTree());
3056 /// \brief Check whether it is safe to if-convert this phi node.
3058 /// Phi nodes with constant expressions that can trap are not safe to if
3060 static bool canIfConvertPHINodes(BasicBlock *BB) {
3061 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3062 PHINode *Phi = dyn_cast<PHINode>(I);
3065 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
3066 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
3073 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3074 if (!EnableIfConversion)
3077 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3079 // A list of pointers that we can safely read and write to.
3080 SmallPtrSet<Value *, 8> SafePointes;
3082 // Collect safe addresses.
3083 for (Loop::block_iterator BI = TheLoop->block_begin(),
3084 BE = TheLoop->block_end(); BI != BE; ++BI) {
3085 BasicBlock *BB = *BI;
3087 if (blockNeedsPredication(BB))
3090 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3091 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3092 SafePointes.insert(LI->getPointerOperand());
3093 else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3094 SafePointes.insert(SI->getPointerOperand());
3098 // Collect the blocks that need predication.
3099 BasicBlock *Header = TheLoop->getHeader();
3100 for (Loop::block_iterator BI = TheLoop->block_begin(),
3101 BE = TheLoop->block_end(); BI != BE; ++BI) {
3102 BasicBlock *BB = *BI;
3104 // We don't support switch statements inside loops.
3105 if (!isa<BranchInst>(BB->getTerminator()))
3108 // We must be able to predicate all blocks that need to be predicated.
3109 if (blockNeedsPredication(BB)) {
3110 if (!blockCanBePredicated(BB, SafePointes))
3112 } else if (BB != Header && !canIfConvertPHINodes(BB))
3117 // We can if-convert this loop.
3121 bool LoopVectorizationLegality::canVectorize() {
3122 // We must have a loop in canonical form. Loops with indirectbr in them cannot
3123 // be canonicalized.
3124 if (!TheLoop->getLoopPreheader())
3127 // We can only vectorize innermost loops.
3128 if (TheLoop->getSubLoopsVector().size())
3131 // We must have a single backedge.
3132 if (TheLoop->getNumBackEdges() != 1)
3135 // We must have a single exiting block.
3136 if (!TheLoop->getExitingBlock())
3139 // We need to have a loop header.
3140 DEBUG(dbgs() << "LV: Found a loop: " <<
3141 TheLoop->getHeader()->getName() << '\n');
3143 // Check if we can if-convert non-single-bb loops.
3144 unsigned NumBlocks = TheLoop->getNumBlocks();
3145 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3146 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3150 // ScalarEvolution needs to be able to find the exit count.
3151 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3152 if (ExitCount == SE->getCouldNotCompute()) {
3153 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3157 // Do not loop-vectorize loops with a tiny trip count.
3158 BasicBlock *Latch = TheLoop->getLoopLatch();
3159 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
3160 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
3161 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
3162 "This loop is not worth vectorizing.\n");
3166 // Check if we can vectorize the instructions and CFG in this loop.
3167 if (!canVectorizeInstrs()) {
3168 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3172 // Go over each instruction and look at memory deps.
3173 if (!canVectorizeMemory()) {
3174 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3178 // Collect all of the variables that remain uniform after vectorization.
3179 collectLoopUniforms();
3181 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3182 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3185 // Okay! We can vectorize. At this point we don't have any other mem analysis
3186 // which may limit our maximum vectorization factor, so just return true with
3191 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
3192 if (Ty->isPointerTy())
3193 return DL.getIntPtrType(Ty);
3195 // It is possible that char's or short's overflow when we ask for the loop's
3196 // trip count, work around this by changing the type size.
3197 if (Ty->getScalarSizeInBits() < 32)
3198 return Type::getInt32Ty(Ty->getContext());
3203 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
3204 Ty0 = convertPointerToIntegerType(DL, Ty0);
3205 Ty1 = convertPointerToIntegerType(DL, Ty1);
3206 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3211 /// \brief Check that the instruction has outside loop users and is not an
3212 /// identified reduction variable.
3213 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3214 SmallPtrSet<Value *, 4> &Reductions) {
3215 // Reduction instructions are allowed to have exit users. All other
3216 // instructions must not have external users.
3217 if (!Reductions.count(Inst))
3218 //Check that all of the users of the loop are inside the BB.
3219 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
3221 Instruction *U = cast<Instruction>(*I);
3222 // This user may be a reduction exit value.
3223 if (!TheLoop->contains(U)) {
3224 DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n');
3231 bool LoopVectorizationLegality::canVectorizeInstrs() {
3232 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3233 BasicBlock *Header = TheLoop->getHeader();
3235 // Look for the attribute signaling the absence of NaNs.
3236 Function &F = *Header->getParent();
3237 if (F.hasFnAttribute("no-nans-fp-math"))
3238 HasFunNoNaNAttr = F.getAttributes().getAttribute(
3239 AttributeSet::FunctionIndex,
3240 "no-nans-fp-math").getValueAsString() == "true";
3242 // For each block in the loop.
3243 for (Loop::block_iterator bb = TheLoop->block_begin(),
3244 be = TheLoop->block_end(); bb != be; ++bb) {
3246 // Scan the instructions in the block and look for hazards.
3247 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3250 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3251 Type *PhiTy = Phi->getType();
3252 // Check that this PHI type is allowed.
3253 if (!PhiTy->isIntegerTy() &&
3254 !PhiTy->isFloatingPointTy() &&
3255 !PhiTy->isPointerTy()) {
3256 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3260 // If this PHINode is not in the header block, then we know that we
3261 // can convert it to select during if-conversion. No need to check if
3262 // the PHIs in this block are induction or reduction variables.
3263 if (*bb != Header) {
3264 // Check that this instruction has no outside users or is an
3265 // identified reduction value with an outside user.
3266 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3271 // We only allow if-converted PHIs with more than two incoming values.
3272 if (Phi->getNumIncomingValues() != 2) {
3273 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3277 // This is the value coming from the preheader.
3278 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3279 // Check if this is an induction variable.
3280 InductionKind IK = isInductionVariable(Phi);
3282 if (IK_NoInduction != IK) {
3283 // Get the widest type.
3285 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3287 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3289 // Int inductions are special because we only allow one IV.
3290 if (IK == IK_IntInduction) {
3291 // Use the phi node with the widest type as induction. Use the last
3292 // one if there are multiple (no good reason for doing this other
3293 // than it is expedient).
3294 if (!Induction || PhiTy == WidestIndTy)
3298 DEBUG(dbgs() << "LV: Found an induction variable.\n");
3299 Inductions[Phi] = InductionInfo(StartValue, IK);
3301 // Until we explicitly handle the case of an induction variable with
3302 // an outside loop user we have to give up vectorizing this loop.
3303 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3309 if (AddReductionVar(Phi, RK_IntegerAdd)) {
3310 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3313 if (AddReductionVar(Phi, RK_IntegerMult)) {
3314 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3317 if (AddReductionVar(Phi, RK_IntegerOr)) {
3318 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3321 if (AddReductionVar(Phi, RK_IntegerAnd)) {
3322 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3325 if (AddReductionVar(Phi, RK_IntegerXor)) {
3326 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3329 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3330 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3333 if (AddReductionVar(Phi, RK_FloatMult)) {
3334 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3337 if (AddReductionVar(Phi, RK_FloatAdd)) {
3338 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3341 if (AddReductionVar(Phi, RK_FloatMinMax)) {
3342 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3347 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3349 }// end of PHI handling
3351 // We still don't handle functions. However, we can ignore dbg intrinsic
3352 // calls and we do handle certain intrinsic and libm functions.
3353 CallInst *CI = dyn_cast<CallInst>(it);
3354 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3355 DEBUG(dbgs() << "LV: Found a call site.\n");
3359 // Check that the instruction return type is vectorizable.
3360 // Also, we can't vectorize extractelement instructions.
3361 if ((!VectorType::isValidElementType(it->getType()) &&
3362 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3363 DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3367 // Check that the stored type is vectorizable.
3368 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3369 Type *T = ST->getValueOperand()->getType();
3370 if (!VectorType::isValidElementType(T))
3372 if (EnableMemAccessVersioning)
3373 collectStridedAcccess(ST);
3376 if (EnableMemAccessVersioning)
3377 if (LoadInst *LI = dyn_cast<LoadInst>(it))
3378 collectStridedAcccess(LI);
3380 // Reduction instructions are allowed to have exit users.
3381 // All other instructions must not have external users.
3382 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3390 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3391 if (Inductions.empty())
3398 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3399 /// return the induction operand of the gep pointer.
3400 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3401 DataLayout *DL, Loop *Lp) {
3402 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3406 unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3408 // Check that all of the gep indices are uniform except for our induction
3410 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3411 if (i != InductionOperand &&
3412 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3414 return GEP->getOperand(InductionOperand);
3417 ///\brief Look for a cast use of the passed value.
3418 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3419 Value *UniqueCast = 0;
3420 for (Value::use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); UI != UE;
3422 CastInst *CI = dyn_cast<CastInst>(*UI);
3423 if (CI && CI->getType() == Ty) {
3433 ///\brief Get the stride of a pointer access in a loop.
3434 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3435 /// pointer to the Value, or null otherwise.
3436 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3437 DataLayout *DL, Loop *Lp) {
3438 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3439 if (!PtrTy || PtrTy->isAggregateType())
3442 // Try to remove a gep instruction to make the pointer (actually index at this
3443 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3444 // pointer, otherwise, we are analyzing the index.
3445 Value *OrigPtr = Ptr;
3447 // The size of the pointer access.
3448 int64_t PtrAccessSize = 1;
3450 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3451 const SCEV *V = SE->getSCEV(Ptr);
3455 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3456 V = C->getOperand();
3458 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3462 V = S->getStepRecurrence(*SE);
3466 // Strip off the size of access multiplication if we are still analyzing the
3468 if (OrigPtr == Ptr) {
3469 DL->getTypeAllocSize(PtrTy->getElementType());
3470 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3471 if (M->getOperand(0)->getSCEVType() != scConstant)
3474 const APInt &APStepVal =
3475 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3477 // Huge step value - give up.
3478 if (APStepVal.getBitWidth() > 64)
3481 int64_t StepVal = APStepVal.getSExtValue();
3482 if (PtrAccessSize != StepVal)
3484 V = M->getOperand(1);
3489 Type *StripedOffRecurrenceCast = 0;
3490 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3491 StripedOffRecurrenceCast = C->getType();
3492 V = C->getOperand();
3495 // Look for the loop invariant symbolic value.
3496 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3500 Value *Stride = U->getValue();
3501 if (!Lp->isLoopInvariant(Stride))
3504 // If we have stripped off the recurrence cast we have to make sure that we
3505 // return the value that is used in this loop so that we can replace it later.
3506 if (StripedOffRecurrenceCast)
3507 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3512 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3514 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3515 Ptr = LI->getPointerOperand();
3516 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3517 Ptr = SI->getPointerOperand();
3521 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3525 DEBUG(dbgs() << "LV: Found a strided access that we can version");
3526 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3527 Strides[Ptr] = Stride;
3528 StrideSet.insert(Stride);
3531 void LoopVectorizationLegality::collectLoopUniforms() {
3532 // We now know that the loop is vectorizable!
3533 // Collect variables that will remain uniform after vectorization.
3534 std::vector<Value*> Worklist;
3535 BasicBlock *Latch = TheLoop->getLoopLatch();
3537 // Start with the conditional branch and walk up the block.
3538 Worklist.push_back(Latch->getTerminator()->getOperand(0));
3540 while (Worklist.size()) {
3541 Instruction *I = dyn_cast<Instruction>(Worklist.back());
3542 Worklist.pop_back();
3544 // Look at instructions inside this loop.
3545 // Stop when reaching PHI nodes.
3546 // TODO: we need to follow values all over the loop, not only in this block.
3547 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3550 // This is a known uniform.
3553 // Insert all operands.
3554 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3559 /// \brief Analyses memory accesses in a loop.
3561 /// Checks whether run time pointer checks are needed and builds sets for data
3562 /// dependence checking.
3563 class AccessAnalysis {
3565 /// \brief Read or write access location.
3566 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3567 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3569 /// \brief Set of potential dependent memory accesses.
3570 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3572 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
3573 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3574 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3576 /// \brief Register a load and whether it is only read from.
3577 void addLoad(Value *Ptr, bool IsReadOnly) {
3578 Accesses.insert(MemAccessInfo(Ptr, false));
3580 ReadOnlyPtr.insert(Ptr);
3583 /// \brief Register a store.
3584 void addStore(Value *Ptr) {
3585 Accesses.insert(MemAccessInfo(Ptr, true));
3588 /// \brief Check whether we can check the pointers at runtime for
3589 /// non-intersection.
3590 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3591 unsigned &NumComparisons, ScalarEvolution *SE,
3592 Loop *TheLoop, ValueToValueMap &Strides,
3593 bool ShouldCheckStride = false);
3595 /// \brief Goes over all memory accesses, checks whether a RT check is needed
3596 /// and builds sets of dependent accesses.
3597 void buildDependenceSets() {
3598 // Process read-write pointers first.
3599 processMemAccesses(false);
3600 // Next, process read pointers.
3601 processMemAccesses(true);
3604 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3606 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3607 void resetDepChecks() { CheckDeps.clear(); }
3609 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3612 typedef SetVector<MemAccessInfo> PtrAccessSet;
3613 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3615 /// \brief Go over all memory access or only the deferred ones if
3616 /// \p UseDeferred is true and check whether runtime pointer checks are needed
3617 /// and build sets of dependency check candidates.
3618 void processMemAccesses(bool UseDeferred);
3620 /// Set of all accesses.
3621 PtrAccessSet Accesses;
3623 /// Set of access to check after all writes have been processed.
3624 PtrAccessSet DeferredAccesses;
3626 /// Map of pointers to last access encountered.
3627 UnderlyingObjToAccessMap ObjToLastAccess;
3629 /// Set of accesses that need a further dependence check.
3630 MemAccessInfoSet CheckDeps;
3632 /// Set of pointers that are read only.
3633 SmallPtrSet<Value*, 16> ReadOnlyPtr;
3635 /// Set of underlying objects already written to.
3636 SmallPtrSet<Value*, 16> WriteObjects;
3640 /// Sets of potentially dependent accesses - members of one set share an
3641 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3642 /// dependence check.
3643 DepCandidates &DepCands;
3645 bool AreAllWritesIdentified;
3646 bool AreAllReadsIdentified;
3647 bool IsRTCheckNeeded;
3650 } // end anonymous namespace
3652 /// \brief Check whether a pointer can participate in a runtime bounds check.
3653 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3655 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3656 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3660 return AR->isAffine();
3663 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3664 /// the address space.
3665 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3666 const Loop *Lp, ValueToValueMap &StridesMap);
3668 bool AccessAnalysis::canCheckPtrAtRT(
3669 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3670 unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3671 ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3672 // Find pointers with computable bounds. We are going to use this information
3673 // to place a runtime bound check.
3674 unsigned NumReadPtrChecks = 0;
3675 unsigned NumWritePtrChecks = 0;
3676 bool CanDoRT = true;
3678 bool IsDepCheckNeeded = isDependencyCheckNeeded();
3679 // We assign consecutive id to access from different dependence sets.
3680 // Accesses within the same set don't need a runtime check.
3681 unsigned RunningDepId = 1;
3682 DenseMap<Value *, unsigned> DepSetId;
3684 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3686 const MemAccessInfo &Access = *AI;
3687 Value *Ptr = Access.getPointer();
3688 bool IsWrite = Access.getInt();
3690 // Just add write checks if we have both.
3691 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3695 ++NumWritePtrChecks;
3699 if (hasComputableBounds(SE, StridesMap, Ptr) &&
3700 // When we run after a failing dependency check we have to make sure we
3701 // don't have wrapping pointers.
3702 (!ShouldCheckStride ||
3703 isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3704 // The id of the dependence set.
3707 if (IsDepCheckNeeded) {
3708 Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3709 unsigned &LeaderId = DepSetId[Leader];
3711 LeaderId = RunningDepId++;
3714 // Each access has its own dependence set.
3715 DepId = RunningDepId++;
3717 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3719 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3725 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3726 NumComparisons = 0; // Only one dependence set.
3728 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3729 NumWritePtrChecks - 1));
3732 // If the pointers that we would use for the bounds comparison have different
3733 // address spaces, assume the values aren't directly comparable, so we can't
3734 // use them for the runtime check. We also have to assume they could
3735 // overlap. In the future there should be metadata for whether address spaces
3737 unsigned NumPointers = RtCheck.Pointers.size();
3738 for (unsigned i = 0; i < NumPointers; ++i) {
3739 for (unsigned j = i + 1; j < NumPointers; ++j) {
3740 // Only need to check pointers between two different dependency sets.
3741 if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3744 Value *PtrI = RtCheck.Pointers[i];
3745 Value *PtrJ = RtCheck.Pointers[j];
3747 unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3748 unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3750 DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3751 " different address spaces\n");
3760 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3761 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3764 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3765 // We process the set twice: first we process read-write pointers, last we
3766 // process read-only pointers. This allows us to skip dependence tests for
3767 // read-only pointers.
3769 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3770 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3771 const MemAccessInfo &Access = *AI;
3772 Value *Ptr = Access.getPointer();
3773 bool IsWrite = Access.getInt();
3775 DepCands.insert(Access);
3777 // Memorize read-only pointers for later processing and skip them in the
3778 // first round (they need to be checked after we have seen all write
3779 // pointers). Note: we also mark pointer that are not consecutive as
3780 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3781 // second check for "!IsWrite".
3782 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3783 if (!UseDeferred && IsReadOnlyPtr) {
3784 DeferredAccesses.insert(Access);
3788 bool NeedDepCheck = false;
3789 // Check whether there is the possibility of dependency because of
3790 // underlying objects being the same.
3791 typedef SmallVector<Value*, 16> ValueVector;
3792 ValueVector TempObjects;
3793 GetUnderlyingObjects(Ptr, TempObjects, DL);
3794 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3796 Value *UnderlyingObj = *UI;
3798 // If this is a write then it needs to be an identified object. If this a
3799 // read and all writes (so far) are identified function scope objects we
3800 // don't need an identified underlying object but only an Argument (the
3801 // next write is going to invalidate this assumption if it is
3803 // This is a micro-optimization for the case where all writes are
3804 // identified and we have one argument pointer.
3805 // Otherwise, we do need a runtime check.
3806 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3807 (!IsWrite && (!AreAllWritesIdentified ||
3808 !isa<Argument>(UnderlyingObj)) &&
3809 !isIdentifiedObject(UnderlyingObj))) {
3810 DEBUG(dbgs() << "LV: Found an unidentified " <<
3811 (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3813 IsRTCheckNeeded = (IsRTCheckNeeded ||
3814 !isIdentifiedObject(UnderlyingObj) ||
3815 !AreAllReadsIdentified);
3818 AreAllWritesIdentified = false;
3820 AreAllReadsIdentified = false;
3823 // If this is a write - check other reads and writes for conflicts. If
3824 // this is a read only check other writes for conflicts (but only if there
3825 // is no other write to the ptr - this is an optimization to catch "a[i] =
3826 // a[i] + " without having to do a dependence check).
3827 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3828 NeedDepCheck = true;
3831 WriteObjects.insert(UnderlyingObj);
3833 // Create sets of pointers connected by shared underlying objects.
3834 UnderlyingObjToAccessMap::iterator Prev =
3835 ObjToLastAccess.find(UnderlyingObj);
3836 if (Prev != ObjToLastAccess.end())
3837 DepCands.unionSets(Access, Prev->second);
3839 ObjToLastAccess[UnderlyingObj] = Access;
3843 CheckDeps.insert(Access);
3848 /// \brief Checks memory dependences among accesses to the same underlying
3849 /// object to determine whether there vectorization is legal or not (and at
3850 /// which vectorization factor).
3852 /// This class works under the assumption that we already checked that memory
3853 /// locations with different underlying pointers are "must-not alias".
3854 /// We use the ScalarEvolution framework to symbolically evalutate access
3855 /// functions pairs. Since we currently don't restructure the loop we can rely
3856 /// on the program order of memory accesses to determine their safety.
3857 /// At the moment we will only deem accesses as safe for:
3858 /// * A negative constant distance assuming program order.
3860 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
3861 /// a[i] = tmp; y = a[i];
3863 /// The latter case is safe because later checks guarantuee that there can't
3864 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
3865 /// the same variable: a header phi can only be an induction or a reduction, a
3866 /// reduction can't have a memory sink, an induction can't have a memory
3867 /// source). This is important and must not be violated (or we have to
3868 /// resort to checking for cycles through memory).
3870 /// * A positive constant distance assuming program order that is bigger
3871 /// than the biggest memory access.
3873 /// tmp = a[i] OR b[i] = x
3874 /// a[i+2] = tmp y = b[i+2];
3876 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3878 /// * Zero distances and all accesses have the same size.
3880 class MemoryDepChecker {
3882 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3883 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3885 MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L)
3886 : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
3887 ShouldRetryWithRuntimeCheck(false) {}
3889 /// \brief Register the location (instructions are given increasing numbers)
3890 /// of a write access.
3891 void addAccess(StoreInst *SI) {
3892 Value *Ptr = SI->getPointerOperand();
3893 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3894 InstMap.push_back(SI);
3898 /// \brief Register the location (instructions are given increasing numbers)
3899 /// of a write access.
3900 void addAccess(LoadInst *LI) {
3901 Value *Ptr = LI->getPointerOperand();
3902 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3903 InstMap.push_back(LI);
3907 /// \brief Check whether the dependencies between the accesses are safe.
3909 /// Only checks sets with elements in \p CheckDeps.
3910 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3911 MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
3913 /// \brief The maximum number of bytes of a vector register we can vectorize
3914 /// the accesses safely with.
3915 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3917 /// \brief In same cases when the dependency check fails we can still
3918 /// vectorize the loop with a dynamic array access check.
3919 bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
3922 ScalarEvolution *SE;
3924 const Loop *InnermostLoop;
3926 /// \brief Maps access locations (ptr, read/write) to program order.
3927 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3929 /// \brief Memory access instructions in program order.
3930 SmallVector<Instruction *, 16> InstMap;
3932 /// \brief The program order index to be used for the next instruction.
3935 // We can access this many bytes in parallel safely.
3936 unsigned MaxSafeDepDistBytes;
3938 /// \brief If we see a non-constant dependence distance we can still try to
3939 /// vectorize this loop with runtime checks.
3940 bool ShouldRetryWithRuntimeCheck;
3942 /// \brief Check whether there is a plausible dependence between the two
3945 /// Access \p A must happen before \p B in program order. The two indices
3946 /// identify the index into the program order map.
3948 /// This function checks whether there is a plausible dependence (or the
3949 /// absence of such can't be proved) between the two accesses. If there is a
3950 /// plausible dependence but the dependence distance is bigger than one
3951 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
3952 /// distance is smaller than any other distance encountered so far).
3953 /// Otherwise, this function returns true signaling a possible dependence.
3954 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
3955 const MemAccessInfo &B, unsigned BIdx,
3956 ValueToValueMap &Strides);
3958 /// \brief Check whether the data dependence could prevent store-load
3960 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
3963 } // end anonymous namespace
3965 static bool isInBoundsGep(Value *Ptr) {
3966 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
3967 return GEP->isInBounds();
3971 /// \brief Check whether the access through \p Ptr has a constant stride.
3972 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3973 const Loop *Lp, ValueToValueMap &StridesMap) {
3974 const Type *Ty = Ptr->getType();
3975 assert(Ty->isPointerTy() && "Unexpected non-ptr");
3977 // Make sure that the pointer does not point to aggregate types.
3978 const PointerType *PtrTy = cast<PointerType>(Ty);
3979 if (PtrTy->getElementType()->isAggregateType()) {
3980 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
3985 const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
3987 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3989 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
3990 << *Ptr << " SCEV: " << *PtrScev << "\n");
3994 // The accesss function must stride over the innermost loop.
3995 if (Lp != AR->getLoop()) {
3996 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
3997 *Ptr << " SCEV: " << *PtrScev << "\n");
4000 // The address calculation must not wrap. Otherwise, a dependence could be
4002 // An inbounds getelementptr that is a AddRec with a unit stride
4003 // cannot wrap per definition. The unit stride requirement is checked later.
4004 // An getelementptr without an inbounds attribute and unit stride would have
4005 // to access the pointer value "0" which is undefined behavior in address
4006 // space 0, therefore we can also vectorize this case.
4007 bool IsInBoundsGEP = isInBoundsGep(Ptr);
4008 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
4009 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
4010 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
4011 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
4012 << *Ptr << " SCEV: " << *PtrScev << "\n");
4016 // Check the step is constant.
4017 const SCEV *Step = AR->getStepRecurrence(*SE);
4019 // Calculate the pointer stride and check if it is consecutive.
4020 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4022 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
4023 " SCEV: " << *PtrScev << "\n");
4027 int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
4028 const APInt &APStepVal = C->getValue()->getValue();
4030 // Huge step value - give up.
4031 if (APStepVal.getBitWidth() > 64)
4034 int64_t StepVal = APStepVal.getSExtValue();
4037 int64_t Stride = StepVal / Size;
4038 int64_t Rem = StepVal % Size;
4042 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
4043 // know we can't "wrap around the address space". In case of address space
4044 // zero we know that this won't happen without triggering undefined behavior.
4045 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
4046 Stride != 1 && Stride != -1)
4052 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
4053 unsigned TypeByteSize) {
4054 // If loads occur at a distance that is not a multiple of a feasible vector
4055 // factor store-load forwarding does not take place.
4056 // Positive dependences might cause troubles because vectorizing them might
4057 // prevent store-load forwarding making vectorized code run a lot slower.
4058 // a[i] = a[i-3] ^ a[i-8];
4059 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
4060 // hence on your typical architecture store-load forwarding does not take
4061 // place. Vectorizing in such cases does not make sense.
4062 // Store-load forwarding distance.
4063 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
4064 // Maximum vector factor.
4065 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
4066 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
4067 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
4069 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
4071 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
4072 MaxVFWithoutSLForwardIssues = (vf >>=1);
4077 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4078 DEBUG(dbgs() << "LV: Distance " << Distance <<
4079 " that could cause a store-load forwarding conflict\n");
4083 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4084 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4085 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4089 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4090 const MemAccessInfo &B, unsigned BIdx,
4091 ValueToValueMap &Strides) {
4092 assert (AIdx < BIdx && "Must pass arguments in program order");
4094 Value *APtr = A.getPointer();
4095 Value *BPtr = B.getPointer();
4096 bool AIsWrite = A.getInt();
4097 bool BIsWrite = B.getInt();
4099 // Two reads are independent.
4100 if (!AIsWrite && !BIsWrite)
4103 const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4104 const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4106 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4107 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4109 const SCEV *Src = AScev;
4110 const SCEV *Sink = BScev;
4112 // If the induction step is negative we have to invert source and sink of the
4114 if (StrideAPtr < 0) {
4117 std::swap(APtr, BPtr);
4118 std::swap(Src, Sink);
4119 std::swap(AIsWrite, BIsWrite);
4120 std::swap(AIdx, BIdx);
4121 std::swap(StrideAPtr, StrideBPtr);
4124 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4126 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4127 << "(Induction step: " << StrideAPtr << ")\n");
4128 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4129 << *InstMap[BIdx] << ": " << *Dist << "\n");
4131 // Need consecutive accesses. We don't want to vectorize
4132 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4133 // the address space.
4134 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4135 DEBUG(dbgs() << "Non-consecutive pointer access\n");
4139 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4141 DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4142 ShouldRetryWithRuntimeCheck = true;
4146 Type *ATy = APtr->getType()->getPointerElementType();
4147 Type *BTy = BPtr->getType()->getPointerElementType();
4148 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4150 // Negative distances are not plausible dependencies.
4151 const APInt &Val = C->getValue()->getValue();
4152 if (Val.isNegative()) {
4153 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4154 if (IsTrueDataDependence &&
4155 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4159 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4163 // Write to the same location with the same size.
4164 // Could be improved to assert type sizes are the same (i32 == float, etc).
4168 DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4172 assert(Val.isStrictlyPositive() && "Expect a positive value");
4174 // Positive distance bigger than max vectorization factor.
4177 "LV: ReadWrite-Write positive dependency with different types\n");
4181 unsigned Distance = (unsigned) Val.getZExtValue();
4183 // Bail out early if passed-in parameters make vectorization not feasible.
4184 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4185 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4187 // The distance must be bigger than the size needed for a vectorized version
4188 // of the operation and the size of the vectorized operation must not be
4189 // bigger than the currrent maximum size.
4190 if (Distance < 2*TypeByteSize ||
4191 2*TypeByteSize > MaxSafeDepDistBytes ||
4192 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4193 DEBUG(dbgs() << "LV: Failure because of Positive distance "
4194 << Val.getSExtValue() << '\n');
4198 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4199 Distance : MaxSafeDepDistBytes;
4201 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4202 if (IsTrueDataDependence &&
4203 couldPreventStoreLoadForward(Distance, TypeByteSize))
4206 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4207 " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4212 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4213 MemAccessInfoSet &CheckDeps,
4214 ValueToValueMap &Strides) {
4216 MaxSafeDepDistBytes = -1U;
4217 while (!CheckDeps.empty()) {
4218 MemAccessInfo CurAccess = *CheckDeps.begin();
4220 // Get the relevant memory access set.
4221 EquivalenceClasses<MemAccessInfo>::iterator I =
4222 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4224 // Check accesses within this set.
4225 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4226 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4228 // Check every access pair.
4230 CheckDeps.erase(*AI);
4231 EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
4233 // Check every accessing instruction pair in program order.
4234 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4235 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4236 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4237 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4238 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4240 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4251 bool LoopVectorizationLegality::canVectorizeMemory() {
4253 typedef SmallVector<Value*, 16> ValueVector;
4254 typedef SmallPtrSet<Value*, 16> ValueSet;
4256 // Holds the Load and Store *instructions*.
4260 // Holds all the different accesses in the loop.
4261 unsigned NumReads = 0;
4262 unsigned NumReadWrites = 0;
4264 PtrRtCheck.Pointers.clear();
4265 PtrRtCheck.Need = false;
4267 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4268 MemoryDepChecker DepChecker(SE, DL, TheLoop);
4271 for (Loop::block_iterator bb = TheLoop->block_begin(),
4272 be = TheLoop->block_end(); bb != be; ++bb) {
4274 // Scan the BB and collect legal loads and stores.
4275 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4278 // If this is a load, save it. If this instruction can read from memory
4279 // but is not a load, then we quit. Notice that we don't handle function
4280 // calls that read or write.
4281 if (it->mayReadFromMemory()) {
4282 // Many math library functions read the rounding mode. We will only
4283 // vectorize a loop if it contains known function calls that don't set
4284 // the flag. Therefore, it is safe to ignore this read from memory.
4285 CallInst *Call = dyn_cast<CallInst>(it);
4286 if (Call && getIntrinsicIDForCall(Call, TLI))
4289 LoadInst *Ld = dyn_cast<LoadInst>(it);
4290 if (!Ld) return false;
4291 if (!Ld->isSimple() && !IsAnnotatedParallel) {
4292 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4295 Loads.push_back(Ld);
4296 DepChecker.addAccess(Ld);
4300 // Save 'store' instructions. Abort if other instructions write to memory.
4301 if (it->mayWriteToMemory()) {
4302 StoreInst *St = dyn_cast<StoreInst>(it);
4303 if (!St) return false;
4304 if (!St->isSimple() && !IsAnnotatedParallel) {
4305 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4308 Stores.push_back(St);
4309 DepChecker.addAccess(St);
4314 // Now we have two lists that hold the loads and the stores.
4315 // Next, we find the pointers that they use.
4317 // Check if we see any stores. If there are no stores, then we don't
4318 // care if the pointers are *restrict*.
4319 if (!Stores.size()) {
4320 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4324 AccessAnalysis::DepCandidates DependentAccesses;
4325 AccessAnalysis Accesses(DL, DependentAccesses);
4327 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4328 // multiple times on the same object. If the ptr is accessed twice, once
4329 // for read and once for write, it will only appear once (on the write
4330 // list). This is okay, since we are going to check for conflicts between
4331 // writes and between reads and writes, but not between reads and reads.
4334 ValueVector::iterator I, IE;
4335 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4336 StoreInst *ST = cast<StoreInst>(*I);
4337 Value* Ptr = ST->getPointerOperand();
4339 if (isUniform(Ptr)) {
4340 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4344 // If we did *not* see this pointer before, insert it to the read-write
4345 // list. At this phase it is only a 'write' list.
4346 if (Seen.insert(Ptr)) {
4348 Accesses.addStore(Ptr);
4352 if (IsAnnotatedParallel) {
4354 << "LV: A loop annotated parallel, ignore memory dependency "
4359 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4360 LoadInst *LD = cast<LoadInst>(*I);
4361 Value* Ptr = LD->getPointerOperand();
4362 // If we did *not* see this pointer before, insert it to the
4363 // read list. If we *did* see it before, then it is already in
4364 // the read-write list. This allows us to vectorize expressions
4365 // such as A[i] += x; Because the address of A[i] is a read-write
4366 // pointer. This only works if the index of A[i] is consecutive.
4367 // If the address of i is unknown (for example A[B[i]]) then we may
4368 // read a few words, modify, and write a few words, and some of the
4369 // words may be written to the same address.
4370 bool IsReadOnlyPtr = false;
4371 if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4373 IsReadOnlyPtr = true;
4375 Accesses.addLoad(Ptr, IsReadOnlyPtr);
4378 // If we write (or read-write) to a single destination and there are no
4379 // other reads in this loop then is it safe to vectorize.
4380 if (NumReadWrites == 1 && NumReads == 0) {
4381 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4385 // Build dependence sets and check whether we need a runtime pointer bounds
4387 Accesses.buildDependenceSets();
4388 bool NeedRTCheck = Accesses.isRTCheckNeeded();
4390 // Find pointers with computable bounds. We are going to use this information
4391 // to place a runtime bound check.
4392 unsigned NumComparisons = 0;
4393 bool CanDoRT = false;
4395 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4398 DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4399 " pointer comparisons.\n");
4401 // If we only have one set of dependences to check pointers among we don't
4402 // need a runtime check.
4403 if (NumComparisons == 0 && NeedRTCheck)
4404 NeedRTCheck = false;
4406 // Check that we did not collect too many pointers or found an unsizeable
4408 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4414 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4417 if (NeedRTCheck && !CanDoRT) {
4418 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4419 "the array bounds.\n");
4424 PtrRtCheck.Need = NeedRTCheck;
4426 bool CanVecMem = true;
4427 if (Accesses.isDependencyCheckNeeded()) {
4428 DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4429 CanVecMem = DepChecker.areDepsSafe(
4430 DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4431 MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4433 if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4434 DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4437 // Clear the dependency checks. We assume they are not needed.
4438 Accesses.resetDepChecks();
4441 PtrRtCheck.Need = true;
4443 CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4444 TheLoop, Strides, true);
4445 // Check that we did not collect too many pointers or found an unsizeable
4447 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4448 DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4457 DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4458 " need a runtime memory check.\n");
4463 static bool hasMultipleUsesOf(Instruction *I,
4464 SmallPtrSet<Instruction *, 8> &Insts) {
4465 unsigned NumUses = 0;
4466 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4467 if (Insts.count(dyn_cast<Instruction>(*Use)))
4476 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4477 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4478 if (!Set.count(dyn_cast<Instruction>(*Use)))
4483 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4484 ReductionKind Kind) {
4485 if (Phi->getNumIncomingValues() != 2)
4488 // Reduction variables are only found in the loop header block.
4489 if (Phi->getParent() != TheLoop->getHeader())
4492 // Obtain the reduction start value from the value that comes from the loop
4494 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4496 // ExitInstruction is the single value which is used outside the loop.
4497 // We only allow for a single reduction value to be used outside the loop.
4498 // This includes users of the reduction, variables (which form a cycle
4499 // which ends in the phi node).
4500 Instruction *ExitInstruction = 0;
4501 // Indicates that we found a reduction operation in our scan.
4502 bool FoundReduxOp = false;
4504 // We start with the PHI node and scan for all of the users of this
4505 // instruction. All users must be instructions that can be used as reduction
4506 // variables (such as ADD). We must have a single out-of-block user. The cycle
4507 // must include the original PHI.
4508 bool FoundStartPHI = false;
4510 // To recognize min/max patterns formed by a icmp select sequence, we store
4511 // the number of instruction we saw from the recognized min/max pattern,
4512 // to make sure we only see exactly the two instructions.
4513 unsigned NumCmpSelectPatternInst = 0;
4514 ReductionInstDesc ReduxDesc(false, 0);
4516 SmallPtrSet<Instruction *, 8> VisitedInsts;
4517 SmallVector<Instruction *, 8> Worklist;
4518 Worklist.push_back(Phi);
4519 VisitedInsts.insert(Phi);
4521 // A value in the reduction can be used:
4522 // - By the reduction:
4523 // - Reduction operation:
4524 // - One use of reduction value (safe).
4525 // - Multiple use of reduction value (not safe).
4527 // - All uses of the PHI must be the reduction (safe).
4528 // - Otherwise, not safe.
4529 // - By one instruction outside of the loop (safe).
4530 // - By further instructions outside of the loop (not safe).
4531 // - By an instruction that is not part of the reduction (not safe).
4533 // * An instruction type other than PHI or the reduction operation.
4534 // * A PHI in the header other than the initial PHI.
4535 while (!Worklist.empty()) {
4536 Instruction *Cur = Worklist.back();
4537 Worklist.pop_back();
4540 // If the instruction has no users then this is a broken chain and can't be
4541 // a reduction variable.
4542 if (Cur->use_empty())
4545 bool IsAPhi = isa<PHINode>(Cur);
4547 // A header PHI use other than the original PHI.
4548 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4551 // Reductions of instructions such as Div, and Sub is only possible if the
4552 // LHS is the reduction variable.
4553 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4554 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4555 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4558 // Any reduction instruction must be of one of the allowed kinds.
4559 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4560 if (!ReduxDesc.IsReduction)
4563 // A reduction operation must only have one use of the reduction value.
4564 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4565 hasMultipleUsesOf(Cur, VisitedInsts))
4568 // All inputs to a PHI node must be a reduction value.
4569 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4572 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4573 isa<SelectInst>(Cur)))
4574 ++NumCmpSelectPatternInst;
4575 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4576 isa<SelectInst>(Cur)))
4577 ++NumCmpSelectPatternInst;
4579 // Check whether we found a reduction operator.
4580 FoundReduxOp |= !IsAPhi;
4582 // Process users of current instruction. Push non-PHI nodes after PHI nodes
4583 // onto the stack. This way we are going to have seen all inputs to PHI
4584 // nodes once we get to them.
4585 SmallVector<Instruction *, 8> NonPHIs;
4586 SmallVector<Instruction *, 8> PHIs;
4587 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
4589 Instruction *Usr = cast<Instruction>(*UI);
4591 // Check if we found the exit user.
4592 BasicBlock *Parent = Usr->getParent();
4593 if (!TheLoop->contains(Parent)) {
4594 // Exit if you find multiple outside users or if the header phi node is
4595 // being used. In this case the user uses the value of the previous
4596 // iteration, in which case we would loose "VF-1" iterations of the
4597 // reduction operation if we vectorize.
4598 if (ExitInstruction != 0 || Cur == Phi)
4601 // The instruction used by an outside user must be the last instruction
4602 // before we feed back to the reduction phi. Otherwise, we loose VF-1
4603 // operations on the value.
4604 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4607 ExitInstruction = Cur;
4611 // Process instructions only once (termination). Each reduction cycle
4612 // value must only be used once, except by phi nodes and min/max
4613 // reductions which are represented as a cmp followed by a select.
4614 ReductionInstDesc IgnoredVal(false, 0);
4615 if (VisitedInsts.insert(Usr)) {
4616 if (isa<PHINode>(Usr))
4617 PHIs.push_back(Usr);
4619 NonPHIs.push_back(Usr);
4620 } else if (!isa<PHINode>(Usr) &&
4621 ((!isa<FCmpInst>(Usr) &&
4622 !isa<ICmpInst>(Usr) &&
4623 !isa<SelectInst>(Usr)) ||
4624 !isMinMaxSelectCmpPattern(Usr, IgnoredVal).IsReduction))
4627 // Remember that we completed the cycle.
4629 FoundStartPHI = true;
4631 Worklist.append(PHIs.begin(), PHIs.end());
4632 Worklist.append(NonPHIs.begin(), NonPHIs.end());
4635 // This means we have seen one but not the other instruction of the
4636 // pattern or more than just a select and cmp.
4637 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4638 NumCmpSelectPatternInst != 2)
4641 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4644 // We found a reduction var if we have reached the original phi node and we
4645 // only have a single instruction with out-of-loop users.
4647 // This instruction is allowed to have out-of-loop users.
4648 AllowedExit.insert(ExitInstruction);
4650 // Save the description of this reduction variable.
4651 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4652 ReduxDesc.MinMaxKind);
4653 Reductions[Phi] = RD;
4654 // We've ended the cycle. This is a reduction variable if we have an
4655 // outside user and it has a binary op.
4660 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4661 /// pattern corresponding to a min(X, Y) or max(X, Y).
4662 LoopVectorizationLegality::ReductionInstDesc
4663 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4664 ReductionInstDesc &Prev) {
4666 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4667 "Expect a select instruction");
4668 Instruction *Cmp = 0;
4669 SelectInst *Select = 0;
4671 // We must handle the select(cmp()) as a single instruction. Advance to the
4673 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4674 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
4675 return ReductionInstDesc(false, I);
4676 return ReductionInstDesc(Select, Prev.MinMaxKind);
4679 // Only handle single use cases for now.
4680 if (!(Select = dyn_cast<SelectInst>(I)))
4681 return ReductionInstDesc(false, I);
4682 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4683 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4684 return ReductionInstDesc(false, I);
4685 if (!Cmp->hasOneUse())
4686 return ReductionInstDesc(false, I);
4691 // Look for a min/max pattern.
4692 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4693 return ReductionInstDesc(Select, MRK_UIntMin);
4694 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4695 return ReductionInstDesc(Select, MRK_UIntMax);
4696 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4697 return ReductionInstDesc(Select, MRK_SIntMax);
4698 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4699 return ReductionInstDesc(Select, MRK_SIntMin);
4700 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4701 return ReductionInstDesc(Select, MRK_FloatMin);
4702 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4703 return ReductionInstDesc(Select, MRK_FloatMax);
4704 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4705 return ReductionInstDesc(Select, MRK_FloatMin);
4706 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4707 return ReductionInstDesc(Select, MRK_FloatMax);
4709 return ReductionInstDesc(false, I);
4712 LoopVectorizationLegality::ReductionInstDesc
4713 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4715 ReductionInstDesc &Prev) {
4716 bool FP = I->getType()->isFloatingPointTy();
4717 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4718 switch (I->getOpcode()) {
4720 return ReductionInstDesc(false, I);
4721 case Instruction::PHI:
4722 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4723 Kind != RK_FloatMinMax))
4724 return ReductionInstDesc(false, I);
4725 return ReductionInstDesc(I, Prev.MinMaxKind);
4726 case Instruction::Sub:
4727 case Instruction::Add:
4728 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4729 case Instruction::Mul:
4730 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4731 case Instruction::And:
4732 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4733 case Instruction::Or:
4734 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4735 case Instruction::Xor:
4736 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4737 case Instruction::FMul:
4738 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4739 case Instruction::FAdd:
4740 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4741 case Instruction::FCmp:
4742 case Instruction::ICmp:
4743 case Instruction::Select:
4744 if (Kind != RK_IntegerMinMax &&
4745 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4746 return ReductionInstDesc(false, I);
4747 return isMinMaxSelectCmpPattern(I, Prev);
4751 LoopVectorizationLegality::InductionKind
4752 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4753 Type *PhiTy = Phi->getType();
4754 // We only handle integer and pointer inductions variables.
4755 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4756 return IK_NoInduction;
4758 // Check that the PHI is consecutive.
4759 const SCEV *PhiScev = SE->getSCEV(Phi);
4760 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4762 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4763 return IK_NoInduction;
4765 const SCEV *Step = AR->getStepRecurrence(*SE);
4767 // Integer inductions need to have a stride of one.
4768 if (PhiTy->isIntegerTy()) {
4770 return IK_IntInduction;
4771 if (Step->isAllOnesValue())
4772 return IK_ReverseIntInduction;
4773 return IK_NoInduction;
4776 // Calculate the pointer stride and check if it is consecutive.
4777 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4779 return IK_NoInduction;
4781 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4782 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4783 if (C->getValue()->equalsInt(Size))
4784 return IK_PtrInduction;
4785 else if (C->getValue()->equalsInt(0 - Size))
4786 return IK_ReversePtrInduction;
4788 return IK_NoInduction;
4791 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4792 Value *In0 = const_cast<Value*>(V);
4793 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4797 return Inductions.count(PN);
4800 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4801 assert(TheLoop->contains(BB) && "Unknown block used");
4803 // Blocks that do not dominate the latch need predication.
4804 BasicBlock* Latch = TheLoop->getLoopLatch();
4805 return !DT->dominates(BB, Latch);
4808 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4809 SmallPtrSet<Value *, 8>& SafePtrs) {
4810 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4811 // We might be able to hoist the load.
4812 if (it->mayReadFromMemory()) {
4813 LoadInst *LI = dyn_cast<LoadInst>(it);
4814 if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4818 // We don't predicate stores at the moment.
4819 if (it->mayWriteToMemory() || it->mayThrow())
4822 // Check that we don't have a constant expression that can trap as operand.
4823 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4825 if (Constant *C = dyn_cast<Constant>(*OI))
4830 // The instructions below can trap.
4831 switch (it->getOpcode()) {
4833 case Instruction::UDiv:
4834 case Instruction::SDiv:
4835 case Instruction::URem:
4836 case Instruction::SRem:
4844 LoopVectorizationCostModel::VectorizationFactor
4845 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4847 // Width 1 means no vectorize
4848 VectorizationFactor Factor = { 1U, 0U };
4849 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4850 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4854 // Find the trip count.
4855 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4856 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4858 unsigned WidestType = getWidestType();
4859 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4860 unsigned MaxSafeDepDist = -1U;
4861 if (Legal->getMaxSafeDepDistBytes() != -1U)
4862 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4863 WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4864 WidestRegister : MaxSafeDepDist);
4865 unsigned MaxVectorSize = WidestRegister / WidestType;
4866 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4867 DEBUG(dbgs() << "LV: The Widest register is: "
4868 << WidestRegister << " bits.\n");
4870 if (MaxVectorSize == 0) {
4871 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4875 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4876 " into one vector!");
4878 unsigned VF = MaxVectorSize;
4880 // If we optimize the program for size, avoid creating the tail loop.
4882 // If we are unable to calculate the trip count then don't try to vectorize.
4884 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4888 // Find the maximum SIMD width that can fit within the trip count.
4889 VF = TC % MaxVectorSize;
4894 // If the trip count that we found modulo the vectorization factor is not
4895 // zero then we require a tail.
4897 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4903 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4904 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4906 Factor.Width = UserVF;
4910 float Cost = expectedCost(1);
4912 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
4913 for (unsigned i=2; i <= VF; i*=2) {
4914 // Notice that the vector loop needs to be executed less times, so
4915 // we need to divide the cost of the vector loops by the width of
4916 // the vector elements.
4917 float VectorCost = expectedCost(i) / (float)i;
4918 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4919 (int)VectorCost << ".\n");
4920 if (VectorCost < Cost) {
4926 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
4927 Factor.Width = Width;
4928 Factor.Cost = Width * Cost;
4932 unsigned LoopVectorizationCostModel::getWidestType() {
4933 unsigned MaxWidth = 8;
4936 for (Loop::block_iterator bb = TheLoop->block_begin(),
4937 be = TheLoop->block_end(); bb != be; ++bb) {
4938 BasicBlock *BB = *bb;
4940 // For each instruction in the loop.
4941 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4942 Type *T = it->getType();
4944 // Only examine Loads, Stores and PHINodes.
4945 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4948 // Examine PHI nodes that are reduction variables.
4949 if (PHINode *PN = dyn_cast<PHINode>(it))
4950 if (!Legal->getReductionVars()->count(PN))
4953 // Examine the stored values.
4954 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4955 T = ST->getValueOperand()->getType();
4957 // Ignore loaded pointer types and stored pointer types that are not
4958 // consecutive. However, we do want to take consecutive stores/loads of
4959 // pointer vectors into account.
4960 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4963 MaxWidth = std::max(MaxWidth,
4964 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4972 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4975 unsigned LoopCost) {
4977 // -- The unroll heuristics --
4978 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4979 // There are many micro-architectural considerations that we can't predict
4980 // at this level. For example frontend pressure (on decode or fetch) due to
4981 // code size, or the number and capabilities of the execution ports.
4983 // We use the following heuristics to select the unroll factor:
4984 // 1. If the code has reductions the we unroll in order to break the cross
4985 // iteration dependency.
4986 // 2. If the loop is really small then we unroll in order to reduce the loop
4988 // 3. We don't unroll if we think that we will spill registers to memory due
4989 // to the increased register pressure.
4991 // Use the user preference, unless 'auto' is selected.
4995 // When we optimize for size we don't unroll.
4999 // We used the distance for the unroll factor.
5000 if (Legal->getMaxSafeDepDistBytes() != -1U)
5003 // Do not unroll loops with a relatively small trip count.
5004 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
5005 TheLoop->getLoopLatch());
5006 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
5009 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
5010 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
5014 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5015 TargetNumRegisters = ForceTargetNumScalarRegs;
5017 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5018 TargetNumRegisters = ForceTargetNumVectorRegs;
5021 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
5022 // We divide by these constants so assume that we have at least one
5023 // instruction that uses at least one register.
5024 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
5025 R.NumInstructions = std::max(R.NumInstructions, 1U);
5027 // We calculate the unroll factor using the following formula.
5028 // Subtract the number of loop invariants from the number of available
5029 // registers. These registers are used by all of the unrolled instances.
5030 // Next, divide the remaining registers by the number of registers that is
5031 // required by the loop, in order to estimate how many parallel instances
5032 // fit without causing spills. All of this is rounded down if necessary to be
5033 // a power of two. We want power of two unroll factors to simplify any
5034 // addressing operations or alignment considerations.
5035 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
5038 // Clamp the unroll factor ranges to reasonable factors.
5039 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
5041 // Check if the user has overridden the unroll max.
5043 if (ForceTargetMaxScalarUnrollFactor.getNumOccurrences() > 0)
5044 MaxUnrollSize = ForceTargetMaxScalarUnrollFactor;
5046 if (ForceTargetMaxVectorUnrollFactor.getNumOccurrences() > 0)
5047 MaxUnrollSize = ForceTargetMaxVectorUnrollFactor;
5050 // If we did not calculate the cost for VF (because the user selected the VF)
5051 // then we calculate the cost of VF here.
5053 LoopCost = expectedCost(VF);
5055 // Clamp the calculated UF to be between the 1 and the max unroll factor
5056 // that the target allows.
5057 if (UF > MaxUnrollSize)
5062 // Unroll if we vectorized this loop and there is a reduction that could
5063 // benefit from unrolling.
5064 if (VF > 1 && Legal->getReductionVars()->size()) {
5065 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
5069 // We want to unroll tiny loops in order to reduce the loop overhead.
5070 // We assume that the cost overhead is 1 and we use the cost model
5071 // to estimate the cost of the loop and unroll until the cost of the
5072 // loop overhead is about 5% of the cost of the loop.
5073 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
5074 if (LoopCost < SmallLoopCost) {
5075 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
5076 unsigned NewUF = PowerOf2Floor(SmallLoopCost / LoopCost);
5077 return std::min(NewUF, UF);
5080 DEBUG(dbgs() << "LV: Not Unrolling.\n");
5084 LoopVectorizationCostModel::RegisterUsage
5085 LoopVectorizationCostModel::calculateRegisterUsage() {
5086 // This function calculates the register usage by measuring the highest number
5087 // of values that are alive at a single location. Obviously, this is a very
5088 // rough estimation. We scan the loop in a topological order in order and
5089 // assign a number to each instruction. We use RPO to ensure that defs are
5090 // met before their users. We assume that each instruction that has in-loop
5091 // users starts an interval. We record every time that an in-loop value is
5092 // used, so we have a list of the first and last occurrences of each
5093 // instruction. Next, we transpose this data structure into a multi map that
5094 // holds the list of intervals that *end* at a specific location. This multi
5095 // map allows us to perform a linear search. We scan the instructions linearly
5096 // and record each time that a new interval starts, by placing it in a set.
5097 // If we find this value in the multi-map then we remove it from the set.
5098 // The max register usage is the maximum size of the set.
5099 // We also search for instructions that are defined outside the loop, but are
5100 // used inside the loop. We need this number separately from the max-interval
5101 // usage number because when we unroll, loop-invariant values do not take
5103 LoopBlocksDFS DFS(TheLoop);
5107 R.NumInstructions = 0;
5109 // Each 'key' in the map opens a new interval. The values
5110 // of the map are the index of the 'last seen' usage of the
5111 // instruction that is the key.
5112 typedef DenseMap<Instruction*, unsigned> IntervalMap;
5113 // Maps instruction to its index.
5114 DenseMap<unsigned, Instruction*> IdxToInstr;
5115 // Marks the end of each interval.
5116 IntervalMap EndPoint;
5117 // Saves the list of instruction indices that are used in the loop.
5118 SmallSet<Instruction*, 8> Ends;
5119 // Saves the list of values that are used in the loop but are
5120 // defined outside the loop, such as arguments and constants.
5121 SmallPtrSet<Value*, 8> LoopInvariants;
5124 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5125 be = DFS.endRPO(); bb != be; ++bb) {
5126 R.NumInstructions += (*bb)->size();
5127 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5129 Instruction *I = it;
5130 IdxToInstr[Index++] = I;
5132 // Save the end location of each USE.
5133 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5134 Value *U = I->getOperand(i);
5135 Instruction *Instr = dyn_cast<Instruction>(U);
5137 // Ignore non-instruction values such as arguments, constants, etc.
5138 if (!Instr) continue;
5140 // If this instruction is outside the loop then record it and continue.
5141 if (!TheLoop->contains(Instr)) {
5142 LoopInvariants.insert(Instr);
5146 // Overwrite previous end points.
5147 EndPoint[Instr] = Index;
5153 // Saves the list of intervals that end with the index in 'key'.
5154 typedef SmallVector<Instruction*, 2> InstrList;
5155 DenseMap<unsigned, InstrList> TransposeEnds;
5157 // Transpose the EndPoints to a list of values that end at each index.
5158 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5160 TransposeEnds[it->second].push_back(it->first);
5162 SmallSet<Instruction*, 8> OpenIntervals;
5163 unsigned MaxUsage = 0;
5166 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5167 for (unsigned int i = 0; i < Index; ++i) {
5168 Instruction *I = IdxToInstr[i];
5169 // Ignore instructions that are never used within the loop.
5170 if (!Ends.count(I)) continue;
5172 // Remove all of the instructions that end at this location.
5173 InstrList &List = TransposeEnds[i];
5174 for (unsigned int j=0, e = List.size(); j < e; ++j)
5175 OpenIntervals.erase(List[j]);
5177 // Count the number of live interals.
5178 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5180 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5181 OpenIntervals.size() << '\n');
5183 // Add the current instruction to the list of open intervals.
5184 OpenIntervals.insert(I);
5187 unsigned Invariant = LoopInvariants.size();
5188 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5189 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5190 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5192 R.LoopInvariantRegs = Invariant;
5193 R.MaxLocalUsers = MaxUsage;
5197 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5201 for (Loop::block_iterator bb = TheLoop->block_begin(),
5202 be = TheLoop->block_end(); bb != be; ++bb) {
5203 unsigned BlockCost = 0;
5204 BasicBlock *BB = *bb;
5206 // For each instruction in the old loop.
5207 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5208 // Skip dbg intrinsics.
5209 if (isa<DbgInfoIntrinsic>(it))
5212 unsigned C = getInstructionCost(it, VF);
5214 // Check if we should override the cost.
5215 if (ForceTargetInstructionCost.getNumOccurrences() > 0)
5216 C = ForceTargetInstructionCost;
5219 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5220 VF << " For instruction: " << *it << '\n');
5223 // We assume that if-converted blocks have a 50% chance of being executed.
5224 // When the code is scalar then some of the blocks are avoided due to CF.
5225 // When the code is vectorized we execute all code paths.
5226 if (VF == 1 && Legal->blockNeedsPredication(*bb))
5235 /// \brief Check whether the address computation for a non-consecutive memory
5236 /// access looks like an unlikely candidate for being merged into the indexing
5239 /// We look for a GEP which has one index that is an induction variable and all
5240 /// other indices are loop invariant. If the stride of this access is also
5241 /// within a small bound we decide that this address computation can likely be
5242 /// merged into the addressing mode.
5243 /// In all other cases, we identify the address computation as complex.
5244 static bool isLikelyComplexAddressComputation(Value *Ptr,
5245 LoopVectorizationLegality *Legal,
5246 ScalarEvolution *SE,
5247 const Loop *TheLoop) {
5248 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5252 // We are looking for a gep with all loop invariant indices except for one
5253 // which should be an induction variable.
5254 unsigned NumOperands = Gep->getNumOperands();
5255 for (unsigned i = 1; i < NumOperands; ++i) {
5256 Value *Opd = Gep->getOperand(i);
5257 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5258 !Legal->isInductionVariable(Opd))
5262 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5263 // can likely be merged into the address computation.
5264 unsigned MaxMergeDistance = 64;
5266 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5270 // Check the step is constant.
5271 const SCEV *Step = AddRec->getStepRecurrence(*SE);
5272 // Calculate the pointer stride and check if it is consecutive.
5273 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5277 const APInt &APStepVal = C->getValue()->getValue();
5279 // Huge step value - give up.
5280 if (APStepVal.getBitWidth() > 64)
5283 int64_t StepVal = APStepVal.getSExtValue();
5285 return StepVal > MaxMergeDistance;
5288 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5289 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5295 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5296 // If we know that this instruction will remain uniform, check the cost of
5297 // the scalar version.
5298 if (Legal->isUniformAfterVectorization(I))
5301 Type *RetTy = I->getType();
5302 Type *VectorTy = ToVectorTy(RetTy, VF);
5304 // TODO: We need to estimate the cost of intrinsic calls.
5305 switch (I->getOpcode()) {
5306 case Instruction::GetElementPtr:
5307 // We mark this instruction as zero-cost because the cost of GEPs in
5308 // vectorized code depends on whether the corresponding memory instruction
5309 // is scalarized or not. Therefore, we handle GEPs with the memory
5310 // instruction cost.
5312 case Instruction::Br: {
5313 return TTI.getCFInstrCost(I->getOpcode());
5315 case Instruction::PHI:
5316 //TODO: IF-converted IFs become selects.
5318 case Instruction::Add:
5319 case Instruction::FAdd:
5320 case Instruction::Sub:
5321 case Instruction::FSub:
5322 case Instruction::Mul:
5323 case Instruction::FMul:
5324 case Instruction::UDiv:
5325 case Instruction::SDiv:
5326 case Instruction::FDiv:
5327 case Instruction::URem:
5328 case Instruction::SRem:
5329 case Instruction::FRem:
5330 case Instruction::Shl:
5331 case Instruction::LShr:
5332 case Instruction::AShr:
5333 case Instruction::And:
5334 case Instruction::Or:
5335 case Instruction::Xor: {
5336 // Since we will replace the stride by 1 the multiplication should go away.
5337 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5339 // Certain instructions can be cheaper to vectorize if they have a constant
5340 // second vector operand. One example of this are shifts on x86.
5341 TargetTransformInfo::OperandValueKind Op1VK =
5342 TargetTransformInfo::OK_AnyValue;
5343 TargetTransformInfo::OperandValueKind Op2VK =
5344 TargetTransformInfo::OK_AnyValue;
5346 if (isa<ConstantInt>(I->getOperand(1)))
5347 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5349 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5351 case Instruction::Select: {
5352 SelectInst *SI = cast<SelectInst>(I);
5353 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5354 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5355 Type *CondTy = SI->getCondition()->getType();
5357 CondTy = VectorType::get(CondTy, VF);
5359 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5361 case Instruction::ICmp:
5362 case Instruction::FCmp: {
5363 Type *ValTy = I->getOperand(0)->getType();
5364 VectorTy = ToVectorTy(ValTy, VF);
5365 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5367 case Instruction::Store:
5368 case Instruction::Load: {
5369 StoreInst *SI = dyn_cast<StoreInst>(I);
5370 LoadInst *LI = dyn_cast<LoadInst>(I);
5371 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5373 VectorTy = ToVectorTy(ValTy, VF);
5375 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5376 unsigned AS = SI ? SI->getPointerAddressSpace() :
5377 LI->getPointerAddressSpace();
5378 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5379 // We add the cost of address computation here instead of with the gep
5380 // instruction because only here we know whether the operation is
5383 return TTI.getAddressComputationCost(VectorTy) +
5384 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5386 // Scalarized loads/stores.
5387 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5388 bool Reverse = ConsecutiveStride < 0;
5389 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5390 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5391 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5392 bool IsComplexComputation =
5393 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5395 // The cost of extracting from the value vector and pointer vector.
5396 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5397 for (unsigned i = 0; i < VF; ++i) {
5398 // The cost of extracting the pointer operand.
5399 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5400 // In case of STORE, the cost of ExtractElement from the vector.
5401 // In case of LOAD, the cost of InsertElement into the returned
5403 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5404 Instruction::InsertElement,
5408 // The cost of the scalar loads/stores.
5409 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5410 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5415 // Wide load/stores.
5416 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5417 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5420 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5424 case Instruction::ZExt:
5425 case Instruction::SExt:
5426 case Instruction::FPToUI:
5427 case Instruction::FPToSI:
5428 case Instruction::FPExt:
5429 case Instruction::PtrToInt:
5430 case Instruction::IntToPtr:
5431 case Instruction::SIToFP:
5432 case Instruction::UIToFP:
5433 case Instruction::Trunc:
5434 case Instruction::FPTrunc:
5435 case Instruction::BitCast: {
5436 // We optimize the truncation of induction variable.
5437 // The cost of these is the same as the scalar operation.
5438 if (I->getOpcode() == Instruction::Trunc &&
5439 Legal->isInductionVariable(I->getOperand(0)))
5440 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5441 I->getOperand(0)->getType());
5443 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5444 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5446 case Instruction::Call: {
5447 CallInst *CI = cast<CallInst>(I);
5448 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5449 assert(ID && "Not an intrinsic call!");
5450 Type *RetTy = ToVectorTy(CI->getType(), VF);
5451 SmallVector<Type*, 4> Tys;
5452 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5453 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5454 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5457 // We are scalarizing the instruction. Return the cost of the scalar
5458 // instruction, plus the cost of insert and extract into vector
5459 // elements, times the vector width.
5462 if (!RetTy->isVoidTy() && VF != 1) {
5463 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5465 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5468 // The cost of inserting the results plus extracting each one of the
5470 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5473 // The cost of executing VF copies of the scalar instruction. This opcode
5474 // is unknown. Assume that it is the same as 'mul'.
5475 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5481 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5482 if (Scalar->isVoidTy() || VF == 1)
5484 return VectorType::get(Scalar, VF);
5487 char LoopVectorize::ID = 0;
5488 static const char lv_name[] = "Loop Vectorization";
5489 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5490 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5491 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo)
5492 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5493 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5494 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5495 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5496 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5497 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5500 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5501 return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5505 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5506 // Check for a store.
5507 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5508 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5510 // Check for a load.
5511 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5512 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5518 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr) {
5519 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5520 // Holds vector parameters or scalars, in case of uniform vals.
5521 SmallVector<VectorParts, 4> Params;
5523 setDebugLocFromInst(Builder, Instr);
5525 // Find all of the vectorized parameters.
5526 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5527 Value *SrcOp = Instr->getOperand(op);
5529 // If we are accessing the old induction variable, use the new one.
5530 if (SrcOp == OldInduction) {
5531 Params.push_back(getVectorValue(SrcOp));
5535 // Try using previously calculated values.
5536 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5538 // If the src is an instruction that appeared earlier in the basic block
5539 // then it should already be vectorized.
5540 if (SrcInst && OrigLoop->contains(SrcInst)) {
5541 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5542 // The parameter is a vector value from earlier.
5543 Params.push_back(WidenMap.get(SrcInst));
5545 // The parameter is a scalar from outside the loop. Maybe even a constant.
5546 VectorParts Scalars;
5547 Scalars.append(UF, SrcOp);
5548 Params.push_back(Scalars);
5552 assert(Params.size() == Instr->getNumOperands() &&
5553 "Invalid number of operands");
5555 // Does this instruction return a value ?
5556 bool IsVoidRetTy = Instr->getType()->isVoidTy();
5558 Value *UndefVec = IsVoidRetTy ? 0 :
5559 UndefValue::get(Instr->getType());
5560 // Create a new entry in the WidenMap and initialize it to Undef or Null.
5561 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5563 // For each vector unroll 'part':
5564 for (unsigned Part = 0; Part < UF; ++Part) {
5565 // For each scalar that we create:
5567 Instruction *Cloned = Instr->clone();
5569 Cloned->setName(Instr->getName() + ".cloned");
5570 // Replace the operands of the cloned instructions with extracted scalars.
5571 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5572 Value *Op = Params[op][Part];
5573 Cloned->setOperand(op, Op);
5576 // Place the cloned scalar in the new loop.
5577 Builder.Insert(Cloned);
5579 // If the original scalar returns a value we need to place it in a vector
5580 // so that future users will be able to use it.
5582 VecResults[Part] = Cloned;
5586 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5587 return scalarizeInstruction(Instr);
5590 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5594 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5598 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5600 // When unrolling and the VF is 1, we only need to add a simple scalar.
5601 Type *ITy = Val->getType();
5602 assert(!ITy->isVectorTy() && "Val must be a scalar");
5603 Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5604 return Builder.CreateAdd(Val, C, "induction");