1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10 // and generates target-independent LLVM-IR.
11 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12 // of instructions in order to estimate the profitability of vectorization.
13 //
14 // The loop vectorizer combines consecutive loop iterations into a single
15 // 'wide' iteration. After this transformation the index is incremented
16 // by the SIMD vector width, and not by one.
17 //
18 // This pass has three parts:
19 // 1. The main loop pass that drives the different parts.
20 // 2. LoopVectorizationLegality - A unit that checks for the legality
21 //    of the vectorization.
22 // 3. InnerLoopVectorizer - A unit that performs the actual
23 //    widening of instructions.
24 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
25 //    of vectorization. It decides on the optimal vector width, which
26 //    can be one, if vectorization is not profitable.
27 //
28 // There is a development effort going on to migrate loop vectorizer to the
29 // VPlan infrastructure and to introduce outer loop vectorization support (see
30 // docs/Proposal/VectorizationPlan.rst and
31 // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32 // purpose, we temporarily introduced the VPlan-native vectorization path: an
33 // alternative vectorization path that is natively implemented on top of the
34 // VPlan infrastructure. See EnableVPlanNativePath for enabling.
35 //
36 //===----------------------------------------------------------------------===//
37 //
38 // The reduction-variable vectorization is based on the paper:
39 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40 //
41 // Variable uniformity checks are inspired by:
42 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
43 //
44 // The interleaved access vectorization is based on the paper:
45 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
46 //  Data for SIMD
47 //
48 // Other ideas/concepts are from:
49 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50 //
51 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
52 //  Vectorizing Compilers.
53 //
54 //===----------------------------------------------------------------------===//
55 
56 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
57 #include "LoopVectorizationPlanner.h"
58 #include "VPRecipeBuilder.h"
59 #include "VPlan.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "VPlanPredicator.h"
62 #include "VPlanTransforms.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/ArrayRef.h"
65 #include "llvm/ADT/DenseMap.h"
66 #include "llvm/ADT/DenseMapInfo.h"
67 #include "llvm/ADT/Hashing.h"
68 #include "llvm/ADT/MapVector.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/Statistic.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Twine.h"
78 #include "llvm/ADT/iterator_range.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/BasicAliasAnalysis.h"
81 #include "llvm/Analysis/BlockFrequencyInfo.h"
82 #include "llvm/Analysis/CFG.h"
83 #include "llvm/Analysis/CodeMetrics.h"
84 #include "llvm/Analysis/DemandedBits.h"
85 #include "llvm/Analysis/GlobalsModRef.h"
86 #include "llvm/Analysis/LoopAccessAnalysis.h"
87 #include "llvm/Analysis/LoopAnalysisManager.h"
88 #include "llvm/Analysis/LoopInfo.h"
89 #include "llvm/Analysis/LoopIterator.h"
90 #include "llvm/Analysis/MemorySSA.h"
91 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
92 #include "llvm/Analysis/ProfileSummaryInfo.h"
93 #include "llvm/Analysis/ScalarEvolution.h"
94 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
95 #include "llvm/Analysis/TargetLibraryInfo.h"
96 #include "llvm/Analysis/TargetTransformInfo.h"
97 #include "llvm/Analysis/VectorUtils.h"
98 #include "llvm/IR/Attributes.h"
99 #include "llvm/IR/BasicBlock.h"
100 #include "llvm/IR/CFG.h"
101 #include "llvm/IR/Constant.h"
102 #include "llvm/IR/Constants.h"
103 #include "llvm/IR/DataLayout.h"
104 #include "llvm/IR/DebugInfoMetadata.h"
105 #include "llvm/IR/DebugLoc.h"
106 #include "llvm/IR/DerivedTypes.h"
107 #include "llvm/IR/DiagnosticInfo.h"
108 #include "llvm/IR/Dominators.h"
109 #include "llvm/IR/Function.h"
110 #include "llvm/IR/IRBuilder.h"
111 #include "llvm/IR/InstrTypes.h"
112 #include "llvm/IR/Instruction.h"
113 #include "llvm/IR/Instructions.h"
114 #include "llvm/IR/IntrinsicInst.h"
115 #include "llvm/IR/Intrinsics.h"
116 #include "llvm/IR/LLVMContext.h"
117 #include "llvm/IR/Metadata.h"
118 #include "llvm/IR/Module.h"
119 #include "llvm/IR/Operator.h"
120 #include "llvm/IR/Type.h"
121 #include "llvm/IR/Use.h"
122 #include "llvm/IR/User.h"
123 #include "llvm/IR/Value.h"
124 #include "llvm/IR/ValueHandle.h"
125 #include "llvm/IR/Verifier.h"
126 #include "llvm/InitializePasses.h"
127 #include "llvm/Pass.h"
128 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/CommandLine.h"
130 #include "llvm/Support/Compiler.h"
131 #include "llvm/Support/Debug.h"
132 #include "llvm/Support/ErrorHandling.h"
133 #include "llvm/Support/MathExtras.h"
134 #include "llvm/Support/raw_ostream.h"
135 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
136 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
137 #include "llvm/Transforms/Utils/LoopSimplify.h"
138 #include "llvm/Transforms/Utils/LoopUtils.h"
139 #include "llvm/Transforms/Utils/LoopVersioning.h"
140 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
141 #include "llvm/Transforms/Utils/SizeOpts.h"
142 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
143 #include <algorithm>
144 #include <cassert>
145 #include <cstdint>
146 #include <cstdlib>
147 #include <functional>
148 #include <iterator>
149 #include <limits>
150 #include <memory>
151 #include <string>
152 #include <tuple>
153 #include <utility>
154 
155 using namespace llvm;
156 
157 #define LV_NAME "loop-vectorize"
158 #define DEBUG_TYPE LV_NAME
159 
160 /// @{
161 /// Metadata attribute names
162 static const char *const LLVMLoopVectorizeFollowupAll =
163     "llvm.loop.vectorize.followup_all";
164 static const char *const LLVMLoopVectorizeFollowupVectorized =
165     "llvm.loop.vectorize.followup_vectorized";
166 static const char *const LLVMLoopVectorizeFollowupEpilogue =
167     "llvm.loop.vectorize.followup_epilogue";
168 /// @}
169 
170 STATISTIC(LoopsVectorized, "Number of loops vectorized");
171 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
172 
173 /// Loops with a known constant trip count below this number are vectorized only
174 /// if no scalar iteration overheads are incurred.
175 static cl::opt<unsigned> TinyTripCountVectorThreshold(
176     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
177     cl::desc("Loops with a constant trip count that is smaller than this "
178              "value are vectorized only if no scalar iteration overheads "
179              "are incurred."));
180 
181 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
182 // that predication is preferred, and this lists all options. I.e., the
183 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
184 // and predicate the instructions accordingly. If tail-folding fails, there are
185 // different fallback strategies depending on these values:
186 namespace PreferPredicateTy {
187   enum Option {
188     ScalarEpilogue = 0,
189     PredicateElseScalarEpilogue,
190     PredicateOrDontVectorize
191   };
192 } // namespace PreferPredicateTy
193 
194 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
195     "prefer-predicate-over-epilogue",
196     cl::init(PreferPredicateTy::ScalarEpilogue),
197     cl::Hidden,
198     cl::desc("Tail-folding and predication preferences over creating a scalar "
199              "epilogue loop."),
200     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
201                          "scalar-epilogue",
202                          "Don't tail-predicate loops, create scalar epilogue"),
203               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
204                          "predicate-else-scalar-epilogue",
205                          "prefer tail-folding, create scalar epilogue if tail "
206                          "folding fails."),
207               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
208                          "predicate-dont-vectorize",
209                          "prefers tail-folding, don't attempt vectorization if "
210                          "tail-folding fails.")));
211 
212 static cl::opt<bool> MaximizeBandwidth(
213     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
214     cl::desc("Maximize bandwidth when selecting vectorization factor which "
215              "will be determined by the smallest type in loop."));
216 
217 static cl::opt<bool> EnableInterleavedMemAccesses(
218     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
219     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
220 
221 /// An interleave-group may need masking if it resides in a block that needs
222 /// predication, or in order to mask away gaps.
223 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
224     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
225     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
226 
227 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
228     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
229     cl::desc("We don't interleave loops with a estimated constant trip count "
230              "below this number"));
231 
232 static cl::opt<unsigned> ForceTargetNumScalarRegs(
233     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
234     cl::desc("A flag that overrides the target's number of scalar registers."));
235 
236 static cl::opt<unsigned> ForceTargetNumVectorRegs(
237     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
238     cl::desc("A flag that overrides the target's number of vector registers."));
239 
240 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
241     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
242     cl::desc("A flag that overrides the target's max interleave factor for "
243              "scalar loops."));
244 
245 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
246     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
247     cl::desc("A flag that overrides the target's max interleave factor for "
248              "vectorized loops."));
249 
250 static cl::opt<unsigned> ForceTargetInstructionCost(
251     "force-target-instruction-cost", cl::init(0), cl::Hidden,
252     cl::desc("A flag that overrides the target's expected cost for "
253              "an instruction to a single constant value. Mostly "
254              "useful for getting consistent testing."));
255 
256 static cl::opt<unsigned> SmallLoopCost(
257     "small-loop-cost", cl::init(20), cl::Hidden,
258     cl::desc(
259         "The cost of a loop that is considered 'small' by the interleaver."));
260 
261 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
262     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
263     cl::desc("Enable the use of the block frequency analysis to access PGO "
264              "heuristics minimizing code growth in cold regions and being more "
265              "aggressive in hot regions."));
266 
267 // Runtime interleave loops for load/store throughput.
268 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
269     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
270     cl::desc(
271         "Enable runtime interleaving until load/store ports are saturated"));
272 
273 /// Interleave small loops with scalar reductions.
274 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
275     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
276     cl::desc("Enable interleaving for loops with small iteration counts that "
277              "contain scalar reductions to expose ILP."));
278 
279 /// The number of stores in a loop that are allowed to need predication.
280 static cl::opt<unsigned> NumberOfStoresToPredicate(
281     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
282     cl::desc("Max number of stores to be predicated behind an if."));
283 
284 static cl::opt<bool> EnableIndVarRegisterHeur(
285     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
286     cl::desc("Count the induction variable only once when interleaving"));
287 
288 static cl::opt<bool> EnableCondStoresVectorization(
289     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
290     cl::desc("Enable if predication of stores during vectorization."));
291 
292 static cl::opt<unsigned> MaxNestedScalarReductionIC(
293     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
294     cl::desc("The maximum interleave count to use when interleaving a scalar "
295              "reduction in a nested loop."));
296 
297 static cl::opt<bool>
298     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
299                            cl::Hidden,
300                            cl::desc("Prefer in-loop vector reductions, "
301                                     "overriding the targets preference."));
302 
303 static cl::opt<bool> PreferPredicatedReductionSelect(
304     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
305     cl::desc(
306         "Prefer predicating a reduction operation over an after loop select."));
307 
308 cl::opt<bool> EnableVPlanNativePath(
309     "enable-vplan-native-path", cl::init(false), cl::Hidden,
310     cl::desc("Enable VPlan-native vectorization path with "
311              "support for outer loop vectorization."));
312 
313 // FIXME: Remove this switch once we have divergence analysis. Currently we
314 // assume divergent non-backedge branches when this switch is true.
315 cl::opt<bool> EnableVPlanPredication(
316     "enable-vplan-predication", cl::init(false), cl::Hidden,
317     cl::desc("Enable VPlan-native vectorization path predicator with "
318              "support for outer loop vectorization."));
319 
320 // This flag enables the stress testing of the VPlan H-CFG construction in the
321 // VPlan-native vectorization path. It must be used in conjuction with
322 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
323 // verification of the H-CFGs built.
324 static cl::opt<bool> VPlanBuildStressTest(
325     "vplan-build-stress-test", cl::init(false), cl::Hidden,
326     cl::desc(
327         "Build VPlan for every supported loop nest in the function and bail "
328         "out right after the build (stress test the VPlan H-CFG construction "
329         "in the VPlan-native vectorization path)."));
330 
331 cl::opt<bool> llvm::EnableLoopInterleaving(
332     "interleave-loops", cl::init(true), cl::Hidden,
333     cl::desc("Enable loop interleaving in Loop vectorization passes"));
334 cl::opt<bool> llvm::EnableLoopVectorization(
335     "vectorize-loops", cl::init(true), cl::Hidden,
336     cl::desc("Run the Loop vectorization passes"));
337 
338 /// A helper function that returns the type of loaded or stored value.
339 static Type *getMemInstValueType(Value *I) {
340   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
341          "Expected Load or Store instruction");
342   if (auto *LI = dyn_cast<LoadInst>(I))
343     return LI->getType();
344   return cast<StoreInst>(I)->getValueOperand()->getType();
345 }
346 
347 /// A helper function that returns true if the given type is irregular. The
348 /// type is irregular if its allocated size doesn't equal the store size of an
349 /// element of the corresponding vector type at the given vectorization factor.
350 static bool hasIrregularType(Type *Ty, const DataLayout &DL, ElementCount VF) {
351   assert(!VF.isScalable() && "scalable vectors not yet supported.");
352   // Determine if an array of VF elements of type Ty is "bitcast compatible"
353   // with a <VF x Ty> vector.
354   if (VF.isVector()) {
355     auto *VectorTy = VectorType::get(Ty, VF);
356     return TypeSize::get(VF.getKnownMinValue() *
357                              DL.getTypeAllocSize(Ty).getFixedValue(),
358                          VF.isScalable()) != DL.getTypeStoreSize(VectorTy);
359   }
360 
361   // If the vectorization factor is one, we just check if an array of type Ty
362   // requires padding between elements.
363   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
364 }
365 
366 /// A helper function that returns the reciprocal of the block probability of
367 /// predicated blocks. If we return X, we are assuming the predicated block
368 /// will execute once for every X iterations of the loop header.
369 ///
370 /// TODO: We should use actual block probability here, if available. Currently,
371 ///       we always assume predicated blocks have a 50% chance of executing.
372 static unsigned getReciprocalPredBlockProb() { return 2; }
373 
374 /// A helper function that adds a 'fast' flag to floating-point operations.
375 static Value *addFastMathFlag(Value *V) {
376   if (isa<FPMathOperator>(V))
377     cast<Instruction>(V)->setFastMathFlags(FastMathFlags::getFast());
378   return V;
379 }
380 
381 static Value *addFastMathFlag(Value *V, FastMathFlags FMF) {
382   if (isa<FPMathOperator>(V))
383     cast<Instruction>(V)->setFastMathFlags(FMF);
384   return V;
385 }
386 
387 /// A helper function that returns an integer or floating-point constant with
388 /// value C.
389 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
390   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
391                            : ConstantFP::get(Ty, C);
392 }
393 
394 /// Returns "best known" trip count for the specified loop \p L as defined by
395 /// the following procedure:
396 ///   1) Returns exact trip count if it is known.
397 ///   2) Returns expected trip count according to profile data if any.
398 ///   3) Returns upper bound estimate if it is known.
399 ///   4) Returns None if all of the above failed.
400 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
401   // Check if exact trip count is known.
402   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
403     return ExpectedTC;
404 
405   // Check if there is an expected trip count available from profile data.
406   if (LoopVectorizeWithBlockFrequency)
407     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
408       return EstimatedTC;
409 
410   // Check if upper bound estimate is known.
411   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
412     return ExpectedTC;
413 
414   return None;
415 }
416 
417 namespace llvm {
418 
419 /// InnerLoopVectorizer vectorizes loops which contain only one basic
420 /// block to a specified vectorization factor (VF).
421 /// This class performs the widening of scalars into vectors, or multiple
422 /// scalars. This class also implements the following features:
423 /// * It inserts an epilogue loop for handling loops that don't have iteration
424 ///   counts that are known to be a multiple of the vectorization factor.
425 /// * It handles the code generation for reduction variables.
426 /// * Scalarization (implementation using scalars) of un-vectorizable
427 ///   instructions.
428 /// InnerLoopVectorizer does not perform any vectorization-legality
429 /// checks, and relies on the caller to check for the different legality
430 /// aspects. The InnerLoopVectorizer relies on the
431 /// LoopVectorizationLegality class to provide information about the induction
432 /// and reduction variables that were found to a given vectorization factor.
433 class InnerLoopVectorizer {
434 public:
435   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
436                       LoopInfo *LI, DominatorTree *DT,
437                       const TargetLibraryInfo *TLI,
438                       const TargetTransformInfo *TTI, AssumptionCache *AC,
439                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
440                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
441                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
442                       ProfileSummaryInfo *PSI)
443       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
444         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
445         Builder(PSE.getSE()->getContext()),
446         VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM),
447         BFI(BFI), PSI(PSI) {
448     // Query this against the original loop and save it here because the profile
449     // of the original loop header may change as the transformation happens.
450     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
451         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
452   }
453 
454   virtual ~InnerLoopVectorizer() = default;
455 
456   /// Create a new empty loop that will contain vectorized instructions later
457   /// on, while the old loop will be used as the scalar remainder. Control flow
458   /// is generated around the vectorized (and scalar epilogue) loops consisting
459   /// of various checks and bypasses. Return the pre-header block of the new
460   /// loop.
461   BasicBlock *createVectorizedLoopSkeleton();
462 
463   /// Widen a single instruction within the innermost loop.
464   void widenInstruction(Instruction &I, VPUser &Operands,
465                         VPTransformState &State);
466 
467   /// Widen a single call instruction within the innermost loop.
468   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
469                             VPTransformState &State);
470 
471   /// Widen a single select instruction within the innermost loop.
472   void widenSelectInstruction(SelectInst &I, VPUser &Operands,
473                               bool InvariantCond, VPTransformState &State);
474 
475   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
476   void fixVectorizedLoop();
477 
478   // Return true if any runtime check is added.
479   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
480 
481   /// A type for vectorized values in the new loop. Each value from the
482   /// original loop, when vectorized, is represented by UF vector values in the
483   /// new unrolled loop, where UF is the unroll factor.
484   using VectorParts = SmallVector<Value *, 2>;
485 
486   /// Vectorize a single GetElementPtrInst based on information gathered and
487   /// decisions taken during planning.
488   void widenGEP(GetElementPtrInst *GEP, VPUser &Indices, unsigned UF,
489                 ElementCount VF, bool IsPtrLoopInvariant,
490                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
491 
492   /// Vectorize a single PHINode in a block. This method handles the induction
493   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
494   /// arbitrary length vectors.
495   void widenPHIInstruction(Instruction *PN, unsigned UF, ElementCount VF);
496 
497   /// A helper function to scalarize a single Instruction in the innermost loop.
498   /// Generates a sequence of scalar instances for each lane between \p MinLane
499   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
500   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
501   /// Instr's operands.
502   void scalarizeInstruction(Instruction *Instr, VPUser &Operands,
503                             const VPIteration &Instance, bool IfPredicateInstr,
504                             VPTransformState &State);
505 
506   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
507   /// is provided, the integer induction variable will first be truncated to
508   /// the corresponding type.
509   void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
510 
511   /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
512   /// vector or scalar value on-demand if one is not yet available. When
513   /// vectorizing a loop, we visit the definition of an instruction before its
514   /// uses. When visiting the definition, we either vectorize or scalarize the
515   /// instruction, creating an entry for it in the corresponding map. (In some
516   /// cases, such as induction variables, we will create both vector and scalar
517   /// entries.) Then, as we encounter uses of the definition, we derive values
518   /// for each scalar or vector use unless such a value is already available.
519   /// For example, if we scalarize a definition and one of its uses is vector,
520   /// we build the required vector on-demand with an insertelement sequence
521   /// when visiting the use. Otherwise, if the use is scalar, we can use the
522   /// existing scalar definition.
523   ///
524   /// Return a value in the new loop corresponding to \p V from the original
525   /// loop at unroll index \p Part. If the value has already been vectorized,
526   /// the corresponding vector entry in VectorLoopValueMap is returned. If,
527   /// however, the value has a scalar entry in VectorLoopValueMap, we construct
528   /// a new vector value on-demand by inserting the scalar values into a vector
529   /// with an insertelement sequence. If the value has been neither vectorized
530   /// nor scalarized, it must be loop invariant, so we simply broadcast the
531   /// value into a vector.
532   Value *getOrCreateVectorValue(Value *V, unsigned Part);
533 
534   void setVectorValue(Value *Scalar, unsigned Part, Value *Vector) {
535     VectorLoopValueMap.setVectorValue(Scalar, Part, Vector);
536   }
537 
538   /// Return a value in the new loop corresponding to \p V from the original
539   /// loop at unroll and vector indices \p Instance. If the value has been
540   /// vectorized but not scalarized, the necessary extractelement instruction
541   /// will be generated.
542   Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
543 
544   /// Construct the vector value of a scalarized value \p V one lane at a time.
545   void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
546 
547   /// Try to vectorize interleaved access group \p Group with the base address
548   /// given in \p Addr, optionally masking the vector operations if \p
549   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
550   /// values in the vectorized loop.
551   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
552                                 VPTransformState &State, VPValue *Addr,
553                                 VPValue *BlockInMask = nullptr);
554 
555   /// Vectorize Load and Store instructions with the base address given in \p
556   /// Addr, optionally masking the vector operations if \p BlockInMask is
557   /// non-null. Use \p State to translate given VPValues to IR values in the
558   /// vectorized loop.
559   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
560                                   VPValue *Def, VPValue *Addr,
561                                   VPValue *StoredValue, VPValue *BlockInMask);
562 
563   /// Set the debug location in the builder using the debug location in
564   /// the instruction.
565   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
566 
567   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
568   void fixNonInductionPHIs(void);
569 
570 protected:
571   friend class LoopVectorizationPlanner;
572 
573   /// A small list of PHINodes.
574   using PhiVector = SmallVector<PHINode *, 4>;
575 
576   /// A type for scalarized values in the new loop. Each value from the
577   /// original loop, when scalarized, is represented by UF x VF scalar values
578   /// in the new unrolled loop, where UF is the unroll factor and VF is the
579   /// vectorization factor.
580   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
581 
582   /// Set up the values of the IVs correctly when exiting the vector loop.
583   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
584                     Value *CountRoundDown, Value *EndValue,
585                     BasicBlock *MiddleBlock);
586 
587   /// Create a new induction variable inside L.
588   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
589                                    Value *Step, Instruction *DL);
590 
591   /// Handle all cross-iteration phis in the header.
592   void fixCrossIterationPHIs();
593 
594   /// Fix a first-order recurrence. This is the second phase of vectorizing
595   /// this phi node.
596   void fixFirstOrderRecurrence(PHINode *Phi);
597 
598   /// Fix a reduction cross-iteration phi. This is the second phase of
599   /// vectorizing this phi node.
600   void fixReduction(PHINode *Phi);
601 
602   /// Clear NSW/NUW flags from reduction instructions if necessary.
603   void clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc);
604 
605   /// The Loop exit block may have single value PHI nodes with some
606   /// incoming value. While vectorizing we only handled real values
607   /// that were defined inside the loop and we should have one value for
608   /// each predecessor of its parent basic block. See PR14725.
609   void fixLCSSAPHIs();
610 
611   /// Iteratively sink the scalarized operands of a predicated instruction into
612   /// the block that was created for it.
613   void sinkScalarOperands(Instruction *PredInst);
614 
615   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
616   /// represented as.
617   void truncateToMinimalBitwidths();
618 
619   /// Create a broadcast instruction. This method generates a broadcast
620   /// instruction (shuffle) for loop invariant values and for the induction
621   /// value. If this is the induction variable then we extend it to N, N+1, ...
622   /// this is needed because each iteration in the loop corresponds to a SIMD
623   /// element.
624   virtual Value *getBroadcastInstrs(Value *V);
625 
626   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
627   /// to each vector element of Val. The sequence starts at StartIndex.
628   /// \p Opcode is relevant for FP induction variable.
629   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
630                                Instruction::BinaryOps Opcode =
631                                Instruction::BinaryOpsEnd);
632 
633   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
634   /// variable on which to base the steps, \p Step is the size of the step, and
635   /// \p EntryVal is the value from the original loop that maps to the steps.
636   /// Note that \p EntryVal doesn't have to be an induction variable - it
637   /// can also be a truncate instruction.
638   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
639                         const InductionDescriptor &ID);
640 
641   /// Create a vector induction phi node based on an existing scalar one. \p
642   /// EntryVal is the value from the original loop that maps to the vector phi
643   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
644   /// truncate instruction, instead of widening the original IV, we widen a
645   /// version of the IV truncated to \p EntryVal's type.
646   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
647                                        Value *Step, Instruction *EntryVal);
648 
649   /// Returns true if an instruction \p I should be scalarized instead of
650   /// vectorized for the chosen vectorization factor.
651   bool shouldScalarizeInstruction(Instruction *I) const;
652 
653   /// Returns true if we should generate a scalar version of \p IV.
654   bool needsScalarInduction(Instruction *IV) const;
655 
656   /// If there is a cast involved in the induction variable \p ID, which should
657   /// be ignored in the vectorized loop body, this function records the
658   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
659   /// cast. We had already proved that the casted Phi is equal to the uncasted
660   /// Phi in the vectorized loop (under a runtime guard), and therefore
661   /// there is no need to vectorize the cast - the same value can be used in the
662   /// vector loop for both the Phi and the cast.
663   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
664   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
665   ///
666   /// \p EntryVal is the value from the original loop that maps to the vector
667   /// phi node and is used to distinguish what is the IV currently being
668   /// processed - original one (if \p EntryVal is a phi corresponding to the
669   /// original IV) or the "newly-created" one based on the proof mentioned above
670   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
671   /// latter case \p EntryVal is a TruncInst and we must not record anything for
672   /// that IV, but it's error-prone to expect callers of this routine to care
673   /// about that, hence this explicit parameter.
674   void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
675                                              const Instruction *EntryVal,
676                                              Value *VectorLoopValue,
677                                              unsigned Part,
678                                              unsigned Lane = UINT_MAX);
679 
680   /// Generate a shuffle sequence that will reverse the vector Vec.
681   virtual Value *reverseVector(Value *Vec);
682 
683   /// Returns (and creates if needed) the original loop trip count.
684   Value *getOrCreateTripCount(Loop *NewLoop);
685 
686   /// Returns (and creates if needed) the trip count of the widened loop.
687   Value *getOrCreateVectorTripCount(Loop *NewLoop);
688 
689   /// Returns a bitcasted value to the requested vector type.
690   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
691   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
692                                 const DataLayout &DL);
693 
694   /// Emit a bypass check to see if the vector trip count is zero, including if
695   /// it overflows.
696   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
697 
698   /// Emit a bypass check to see if all of the SCEV assumptions we've
699   /// had to make are correct.
700   void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
701 
702   /// Emit bypass checks to check any memory assumptions we may have made.
703   void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
704 
705   /// Compute the transformed value of Index at offset StartValue using step
706   /// StepValue.
707   /// For integer induction, returns StartValue + Index * StepValue.
708   /// For pointer induction, returns StartValue[Index * StepValue].
709   /// FIXME: The newly created binary instructions should contain nsw/nuw
710   /// flags, which can be found from the original scalar operations.
711   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
712                               const DataLayout &DL,
713                               const InductionDescriptor &ID) const;
714 
715   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
716   /// vector loop preheader, middle block and scalar preheader. Also
717   /// allocate a loop object for the new vector loop and return it.
718   Loop *createVectorLoopSkeleton(StringRef Prefix);
719 
720   /// Create new phi nodes for the induction variables to resume iteration count
721   /// in the scalar epilogue, from where the vectorized loop left off (given by
722   /// \p VectorTripCount).
723   void createInductionResumeValues(Loop *L, Value *VectorTripCount);
724 
725   /// Complete the loop skeleton by adding debug MDs, creating appropriate
726   /// conditional branches in the middle block, preparing the builder and
727   /// running the verifier. Take in the vector loop \p L as argument, and return
728   /// the preheader of the completed vector loop.
729   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
730 
731   /// Add additional metadata to \p To that was not present on \p Orig.
732   ///
733   /// Currently this is used to add the noalias annotations based on the
734   /// inserted memchecks.  Use this for instructions that are *cloned* into the
735   /// vector loop.
736   void addNewMetadata(Instruction *To, const Instruction *Orig);
737 
738   /// Add metadata from one instruction to another.
739   ///
740   /// This includes both the original MDs from \p From and additional ones (\see
741   /// addNewMetadata).  Use this for *newly created* instructions in the vector
742   /// loop.
743   void addMetadata(Instruction *To, Instruction *From);
744 
745   /// Similar to the previous function but it adds the metadata to a
746   /// vector of instructions.
747   void addMetadata(ArrayRef<Value *> To, Instruction *From);
748 
749   /// The original loop.
750   Loop *OrigLoop;
751 
752   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
753   /// dynamic knowledge to simplify SCEV expressions and converts them to a
754   /// more usable form.
755   PredicatedScalarEvolution &PSE;
756 
757   /// Loop Info.
758   LoopInfo *LI;
759 
760   /// Dominator Tree.
761   DominatorTree *DT;
762 
763   /// Alias Analysis.
764   AAResults *AA;
765 
766   /// Target Library Info.
767   const TargetLibraryInfo *TLI;
768 
769   /// Target Transform Info.
770   const TargetTransformInfo *TTI;
771 
772   /// Assumption Cache.
773   AssumptionCache *AC;
774 
775   /// Interface to emit optimization remarks.
776   OptimizationRemarkEmitter *ORE;
777 
778   /// LoopVersioning.  It's only set up (non-null) if memchecks were
779   /// used.
780   ///
781   /// This is currently only used to add no-alias metadata based on the
782   /// memchecks.  The actually versioning is performed manually.
783   std::unique_ptr<LoopVersioning> LVer;
784 
785   /// The vectorization SIMD factor to use. Each vector will have this many
786   /// vector elements.
787   ElementCount VF;
788 
789   /// The vectorization unroll factor to use. Each scalar is vectorized to this
790   /// many different vector instructions.
791   unsigned UF;
792 
793   /// The builder that we use
794   IRBuilder<> Builder;
795 
796   // --- Vectorization state ---
797 
798   /// The vector-loop preheader.
799   BasicBlock *LoopVectorPreHeader;
800 
801   /// The scalar-loop preheader.
802   BasicBlock *LoopScalarPreHeader;
803 
804   /// Middle Block between the vector and the scalar.
805   BasicBlock *LoopMiddleBlock;
806 
807   /// The ExitBlock of the scalar loop.
808   BasicBlock *LoopExitBlock;
809 
810   /// The vector loop body.
811   BasicBlock *LoopVectorBody;
812 
813   /// The scalar loop body.
814   BasicBlock *LoopScalarBody;
815 
816   /// A list of all bypass blocks. The first block is the entry of the loop.
817   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
818 
819   /// The new Induction variable which was added to the new block.
820   PHINode *Induction = nullptr;
821 
822   /// The induction variable of the old basic block.
823   PHINode *OldInduction = nullptr;
824 
825   /// Maps values from the original loop to their corresponding values in the
826   /// vectorized loop. A key value can map to either vector values, scalar
827   /// values or both kinds of values, depending on whether the key was
828   /// vectorized and scalarized.
829   VectorizerValueMap VectorLoopValueMap;
830 
831   /// Store instructions that were predicated.
832   SmallVector<Instruction *, 4> PredicatedInstructions;
833 
834   /// Trip count of the original loop.
835   Value *TripCount = nullptr;
836 
837   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
838   Value *VectorTripCount = nullptr;
839 
840   /// The legality analysis.
841   LoopVectorizationLegality *Legal;
842 
843   /// The profitablity analysis.
844   LoopVectorizationCostModel *Cost;
845 
846   // Record whether runtime checks are added.
847   bool AddedSafetyChecks = false;
848 
849   // Holds the end values for each induction variable. We save the end values
850   // so we can later fix-up the external users of the induction variables.
851   DenseMap<PHINode *, Value *> IVEndValues;
852 
853   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
854   // fixed up at the end of vector code generation.
855   SmallVector<PHINode *, 8> OrigPHIsToFix;
856 
857   /// BFI and PSI are used to check for profile guided size optimizations.
858   BlockFrequencyInfo *BFI;
859   ProfileSummaryInfo *PSI;
860 
861   // Whether this loop should be optimized for size based on profile guided size
862   // optimizatios.
863   bool OptForSizeBasedOnProfile;
864 };
865 
866 class InnerLoopUnroller : public InnerLoopVectorizer {
867 public:
868   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
869                     LoopInfo *LI, DominatorTree *DT,
870                     const TargetLibraryInfo *TLI,
871                     const TargetTransformInfo *TTI, AssumptionCache *AC,
872                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
873                     LoopVectorizationLegality *LVL,
874                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
875                     ProfileSummaryInfo *PSI)
876       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
877                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
878                             BFI, PSI) {}
879 
880 private:
881   Value *getBroadcastInstrs(Value *V) override;
882   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
883                        Instruction::BinaryOps Opcode =
884                        Instruction::BinaryOpsEnd) override;
885   Value *reverseVector(Value *Vec) override;
886 };
887 
888 } // end namespace llvm
889 
890 /// Look for a meaningful debug location on the instruction or it's
891 /// operands.
892 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
893   if (!I)
894     return I;
895 
896   DebugLoc Empty;
897   if (I->getDebugLoc() != Empty)
898     return I;
899 
900   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
901     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
902       if (OpInst->getDebugLoc() != Empty)
903         return OpInst;
904   }
905 
906   return I;
907 }
908 
909 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
910   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
911     const DILocation *DIL = Inst->getDebugLoc();
912     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
913         !isa<DbgInfoIntrinsic>(Inst)) {
914       assert(!VF.isScalable() && "scalable vectors not yet supported.");
915       auto NewDIL =
916           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
917       if (NewDIL)
918         B.SetCurrentDebugLocation(NewDIL.getValue());
919       else
920         LLVM_DEBUG(dbgs()
921                    << "Failed to create new discriminator: "
922                    << DIL->getFilename() << " Line: " << DIL->getLine());
923     }
924     else
925       B.SetCurrentDebugLocation(DIL);
926   } else
927     B.SetCurrentDebugLocation(DebugLoc());
928 }
929 
930 /// Write a record \p DebugMsg about vectorization failure to the debug
931 /// output stream. If \p I is passed, it is an instruction that prevents
932 /// vectorization.
933 #ifndef NDEBUG
934 static void debugVectorizationFailure(const StringRef DebugMsg,
935     Instruction *I) {
936   dbgs() << "LV: Not vectorizing: " << DebugMsg;
937   if (I != nullptr)
938     dbgs() << " " << *I;
939   else
940     dbgs() << '.';
941   dbgs() << '\n';
942 }
943 #endif
944 
945 /// Create an analysis remark that explains why vectorization failed
946 ///
947 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
948 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
949 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
950 /// the location of the remark.  \return the remark object that can be
951 /// streamed to.
952 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
953     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
954   Value *CodeRegion = TheLoop->getHeader();
955   DebugLoc DL = TheLoop->getStartLoc();
956 
957   if (I) {
958     CodeRegion = I->getParent();
959     // If there is no debug location attached to the instruction, revert back to
960     // using the loop's.
961     if (I->getDebugLoc())
962       DL = I->getDebugLoc();
963   }
964 
965   OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
966   R << "loop not vectorized: ";
967   return R;
968 }
969 
970 namespace llvm {
971 
972 void reportVectorizationFailure(const StringRef DebugMsg,
973     const StringRef OREMsg, const StringRef ORETag,
974     OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I) {
975   LLVM_DEBUG(debugVectorizationFailure(DebugMsg, I));
976   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
977   ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(),
978                 ORETag, TheLoop, I) << OREMsg);
979 }
980 
981 } // end namespace llvm
982 
983 #ifndef NDEBUG
984 /// \return string containing a file name and a line # for the given loop.
985 static std::string getDebugLocString(const Loop *L) {
986   std::string Result;
987   if (L) {
988     raw_string_ostream OS(Result);
989     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
990       LoopDbgLoc.print(OS);
991     else
992       // Just print the module name.
993       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
994     OS.flush();
995   }
996   return Result;
997 }
998 #endif
999 
1000 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1001                                          const Instruction *Orig) {
1002   // If the loop was versioned with memchecks, add the corresponding no-alias
1003   // metadata.
1004   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1005     LVer->annotateInstWithNoAlias(To, Orig);
1006 }
1007 
1008 void InnerLoopVectorizer::addMetadata(Instruction *To,
1009                                       Instruction *From) {
1010   propagateMetadata(To, From);
1011   addNewMetadata(To, From);
1012 }
1013 
1014 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1015                                       Instruction *From) {
1016   for (Value *V : To) {
1017     if (Instruction *I = dyn_cast<Instruction>(V))
1018       addMetadata(I, From);
1019   }
1020 }
1021 
1022 namespace llvm {
1023 
1024 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1025 // lowered.
1026 enum ScalarEpilogueLowering {
1027 
1028   // The default: allowing scalar epilogues.
1029   CM_ScalarEpilogueAllowed,
1030 
1031   // Vectorization with OptForSize: don't allow epilogues.
1032   CM_ScalarEpilogueNotAllowedOptSize,
1033 
1034   // A special case of vectorisation with OptForSize: loops with a very small
1035   // trip count are considered for vectorization under OptForSize, thereby
1036   // making sure the cost of their loop body is dominant, free of runtime
1037   // guards and scalar iteration overheads.
1038   CM_ScalarEpilogueNotAllowedLowTripLoop,
1039 
1040   // Loop hint predicate indicating an epilogue is undesired.
1041   CM_ScalarEpilogueNotNeededUsePredicate
1042 };
1043 
1044 /// LoopVectorizationCostModel - estimates the expected speedups due to
1045 /// vectorization.
1046 /// In many cases vectorization is not profitable. This can happen because of
1047 /// a number of reasons. In this class we mainly attempt to predict the
1048 /// expected speedup/slowdowns due to the supported instruction set. We use the
1049 /// TargetTransformInfo to query the different backends for the cost of
1050 /// different operations.
1051 class LoopVectorizationCostModel {
1052 public:
1053   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1054                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1055                              LoopVectorizationLegality *Legal,
1056                              const TargetTransformInfo &TTI,
1057                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1058                              AssumptionCache *AC,
1059                              OptimizationRemarkEmitter *ORE, const Function *F,
1060                              const LoopVectorizeHints *Hints,
1061                              InterleavedAccessInfo &IAI)
1062       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1063         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1064         Hints(Hints), InterleaveInfo(IAI) {}
1065 
1066   /// \return An upper bound for the vectorization factor, or None if
1067   /// vectorization and interleaving should be avoided up front.
1068   Optional<unsigned> computeMaxVF(unsigned UserVF, unsigned UserIC);
1069 
1070   /// \return True if runtime checks are required for vectorization, and false
1071   /// otherwise.
1072   bool runtimeChecksRequired();
1073 
1074   /// \return The most profitable vectorization factor and the cost of that VF.
1075   /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1076   /// then this vectorization factor will be selected if vectorization is
1077   /// possible.
1078   VectorizationFactor selectVectorizationFactor(ElementCount MaxVF);
1079 
1080   /// Setup cost-based decisions for user vectorization factor.
1081   void selectUserVectorizationFactor(ElementCount UserVF) {
1082     collectUniformsAndScalars(UserVF);
1083     collectInstsToScalarize(UserVF);
1084   }
1085 
1086   /// \return The size (in bits) of the smallest and widest types in the code
1087   /// that needs to be vectorized. We ignore values that remain scalar such as
1088   /// 64 bit loop indices.
1089   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1090 
1091   /// \return The desired interleave count.
1092   /// If interleave count has been specified by metadata it will be returned.
1093   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1094   /// are the selected vectorization factor and the cost of the selected VF.
1095   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1096 
1097   /// Memory access instruction may be vectorized in more than one way.
1098   /// Form of instruction after vectorization depends on cost.
1099   /// This function takes cost-based decisions for Load/Store instructions
1100   /// and collects them in a map. This decisions map is used for building
1101   /// the lists of loop-uniform and loop-scalar instructions.
1102   /// The calculated cost is saved with widening decision in order to
1103   /// avoid redundant calculations.
1104   void setCostBasedWideningDecision(ElementCount VF);
1105 
1106   /// A struct that represents some properties of the register usage
1107   /// of a loop.
1108   struct RegisterUsage {
1109     /// Holds the number of loop invariant values that are used in the loop.
1110     /// The key is ClassID of target-provided register class.
1111     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1112     /// Holds the maximum number of concurrent live intervals in the loop.
1113     /// The key is ClassID of target-provided register class.
1114     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1115   };
1116 
1117   /// \return Returns information about the register usages of the loop for the
1118   /// given vectorization factors.
1119   SmallVector<RegisterUsage, 8>
1120   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1121 
1122   /// Collect values we want to ignore in the cost model.
1123   void collectValuesToIgnore();
1124 
1125   /// Split reductions into those that happen in the loop, and those that happen
1126   /// outside. In loop reductions are collected into InLoopReductionChains.
1127   void collectInLoopReductions();
1128 
1129   /// \returns The smallest bitwidth each instruction can be represented with.
1130   /// The vector equivalents of these instructions should be truncated to this
1131   /// type.
1132   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1133     return MinBWs;
1134   }
1135 
1136   /// \returns True if it is more profitable to scalarize instruction \p I for
1137   /// vectorization factor \p VF.
1138   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1139     assert(VF.isVector() &&
1140            "Profitable to scalarize relevant only for VF > 1.");
1141 
1142     // Cost model is not run in the VPlan-native path - return conservative
1143     // result until this changes.
1144     if (EnableVPlanNativePath)
1145       return false;
1146 
1147     auto Scalars = InstsToScalarize.find(VF);
1148     assert(Scalars != InstsToScalarize.end() &&
1149            "VF not yet analyzed for scalarization profitability");
1150     return Scalars->second.find(I) != Scalars->second.end();
1151   }
1152 
1153   /// Returns true if \p I is known to be uniform after vectorization.
1154   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1155     if (VF.isScalar())
1156       return true;
1157 
1158     // Cost model is not run in the VPlan-native path - return conservative
1159     // result until this changes.
1160     if (EnableVPlanNativePath)
1161       return false;
1162 
1163     auto UniformsPerVF = Uniforms.find(VF);
1164     assert(UniformsPerVF != Uniforms.end() &&
1165            "VF not yet analyzed for uniformity");
1166     return UniformsPerVF->second.count(I);
1167   }
1168 
1169   /// Returns true if \p I is known to be scalar after vectorization.
1170   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1171     if (VF.isScalar())
1172       return true;
1173 
1174     // Cost model is not run in the VPlan-native path - return conservative
1175     // result until this changes.
1176     if (EnableVPlanNativePath)
1177       return false;
1178 
1179     auto ScalarsPerVF = Scalars.find(VF);
1180     assert(ScalarsPerVF != Scalars.end() &&
1181            "Scalar values are not calculated for VF");
1182     return ScalarsPerVF->second.count(I);
1183   }
1184 
1185   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1186   /// for vectorization factor \p VF.
1187   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1188     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1189            !isProfitableToScalarize(I, VF) &&
1190            !isScalarAfterVectorization(I, VF);
1191   }
1192 
1193   /// Decision that was taken during cost calculation for memory instruction.
1194   enum InstWidening {
1195     CM_Unknown,
1196     CM_Widen,         // For consecutive accesses with stride +1.
1197     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1198     CM_Interleave,
1199     CM_GatherScatter,
1200     CM_Scalarize
1201   };
1202 
1203   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1204   /// instruction \p I and vector width \p VF.
1205   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1206                            unsigned Cost) {
1207     assert(VF.isVector() && "Expected VF >=2");
1208     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1209   }
1210 
1211   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1212   /// interleaving group \p Grp and vector width \p VF.
1213   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1214                            ElementCount VF, InstWidening W, unsigned Cost) {
1215     assert(VF.isVector() && "Expected VF >=2");
1216     /// Broadcast this decicion to all instructions inside the group.
1217     /// But the cost will be assigned to one instruction only.
1218     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1219       if (auto *I = Grp->getMember(i)) {
1220         if (Grp->getInsertPos() == I)
1221           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1222         else
1223           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1224       }
1225     }
1226   }
1227 
1228   /// Return the cost model decision for the given instruction \p I and vector
1229   /// width \p VF. Return CM_Unknown if this instruction did not pass
1230   /// through the cost modeling.
1231   InstWidening getWideningDecision(Instruction *I, ElementCount VF) {
1232     assert(!VF.isScalable() && "scalable vectors not yet supported.");
1233     assert(VF.isVector() && "Expected VF >=2");
1234 
1235     // Cost model is not run in the VPlan-native path - return conservative
1236     // result until this changes.
1237     if (EnableVPlanNativePath)
1238       return CM_GatherScatter;
1239 
1240     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1241     auto Itr = WideningDecisions.find(InstOnVF);
1242     if (Itr == WideningDecisions.end())
1243       return CM_Unknown;
1244     return Itr->second.first;
1245   }
1246 
1247   /// Return the vectorization cost for the given instruction \p I and vector
1248   /// width \p VF.
1249   unsigned getWideningCost(Instruction *I, ElementCount VF) {
1250     assert(VF.isVector() && "Expected VF >=2");
1251     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1252     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1253            "The cost is not calculated");
1254     return WideningDecisions[InstOnVF].second;
1255   }
1256 
1257   /// Return True if instruction \p I is an optimizable truncate whose operand
1258   /// is an induction variable. Such a truncate will be removed by adding a new
1259   /// induction variable with the destination type.
1260   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1261     // If the instruction is not a truncate, return false.
1262     auto *Trunc = dyn_cast<TruncInst>(I);
1263     if (!Trunc)
1264       return false;
1265 
1266     // Get the source and destination types of the truncate.
1267     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1268     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1269 
1270     // If the truncate is free for the given types, return false. Replacing a
1271     // free truncate with an induction variable would add an induction variable
1272     // update instruction to each iteration of the loop. We exclude from this
1273     // check the primary induction variable since it will need an update
1274     // instruction regardless.
1275     Value *Op = Trunc->getOperand(0);
1276     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1277       return false;
1278 
1279     // If the truncated value is not an induction variable, return false.
1280     return Legal->isInductionPhi(Op);
1281   }
1282 
1283   /// Collects the instructions to scalarize for each predicated instruction in
1284   /// the loop.
1285   void collectInstsToScalarize(ElementCount VF);
1286 
1287   /// Collect Uniform and Scalar values for the given \p VF.
1288   /// The sets depend on CM decision for Load/Store instructions
1289   /// that may be vectorized as interleave, gather-scatter or scalarized.
1290   void collectUniformsAndScalars(ElementCount VF) {
1291     // Do the analysis once.
1292     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1293       return;
1294     setCostBasedWideningDecision(VF);
1295     collectLoopUniforms(VF);
1296     collectLoopScalars(VF);
1297   }
1298 
1299   /// Returns true if the target machine supports masked store operation
1300   /// for the given \p DataType and kind of access to \p Ptr.
1301   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) {
1302     return Legal->isConsecutivePtr(Ptr) &&
1303            TTI.isLegalMaskedStore(DataType, Alignment);
1304   }
1305 
1306   /// Returns true if the target machine supports masked load operation
1307   /// for the given \p DataType and kind of access to \p Ptr.
1308   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) {
1309     return Legal->isConsecutivePtr(Ptr) &&
1310            TTI.isLegalMaskedLoad(DataType, Alignment);
1311   }
1312 
1313   /// Returns true if the target machine supports masked scatter operation
1314   /// for the given \p DataType.
1315   bool isLegalMaskedScatter(Type *DataType, Align Alignment) {
1316     return TTI.isLegalMaskedScatter(DataType, Alignment);
1317   }
1318 
1319   /// Returns true if the target machine supports masked gather operation
1320   /// for the given \p DataType.
1321   bool isLegalMaskedGather(Type *DataType, Align Alignment) {
1322     return TTI.isLegalMaskedGather(DataType, Alignment);
1323   }
1324 
1325   /// Returns true if the target machine can represent \p V as a masked gather
1326   /// or scatter operation.
1327   bool isLegalGatherOrScatter(Value *V) {
1328     bool LI = isa<LoadInst>(V);
1329     bool SI = isa<StoreInst>(V);
1330     if (!LI && !SI)
1331       return false;
1332     auto *Ty = getMemInstValueType(V);
1333     Align Align = getLoadStoreAlignment(V);
1334     return (LI && isLegalMaskedGather(Ty, Align)) ||
1335            (SI && isLegalMaskedScatter(Ty, Align));
1336   }
1337 
1338   /// Returns true if \p I is an instruction that will be scalarized with
1339   /// predication. Such instructions include conditional stores and
1340   /// instructions that may divide by zero.
1341   /// If a non-zero VF has been calculated, we check if I will be scalarized
1342   /// predication for that VF.
1343   bool isScalarWithPredication(Instruction *I,
1344                                ElementCount VF = ElementCount::getFixed(1));
1345 
1346   // Returns true if \p I is an instruction that will be predicated either
1347   // through scalar predication or masked load/store or masked gather/scatter.
1348   // Superset of instructions that return true for isScalarWithPredication.
1349   bool isPredicatedInst(Instruction *I) {
1350     if (!blockNeedsPredication(I->getParent()))
1351       return false;
1352     // Loads and stores that need some form of masked operation are predicated
1353     // instructions.
1354     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1355       return Legal->isMaskRequired(I);
1356     return isScalarWithPredication(I);
1357   }
1358 
1359   /// Returns true if \p I is a memory instruction with consecutive memory
1360   /// access that can be widened.
1361   bool
1362   memoryInstructionCanBeWidened(Instruction *I,
1363                                 ElementCount VF = ElementCount::getFixed(1));
1364 
1365   /// Returns true if \p I is a memory instruction in an interleaved-group
1366   /// of memory accesses that can be vectorized with wide vector loads/stores
1367   /// and shuffles.
1368   bool
1369   interleavedAccessCanBeWidened(Instruction *I,
1370                                 ElementCount VF = ElementCount::getFixed(1));
1371 
1372   /// Check if \p Instr belongs to any interleaved access group.
1373   bool isAccessInterleaved(Instruction *Instr) {
1374     return InterleaveInfo.isInterleaved(Instr);
1375   }
1376 
1377   /// Get the interleaved access group that \p Instr belongs to.
1378   const InterleaveGroup<Instruction> *
1379   getInterleavedAccessGroup(Instruction *Instr) {
1380     return InterleaveInfo.getInterleaveGroup(Instr);
1381   }
1382 
1383   /// Returns true if an interleaved group requires a scalar iteration
1384   /// to handle accesses with gaps, and there is nothing preventing us from
1385   /// creating a scalar epilogue.
1386   bool requiresScalarEpilogue() const {
1387     return isScalarEpilogueAllowed() && InterleaveInfo.requiresScalarEpilogue();
1388   }
1389 
1390   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1391   /// loop hint annotation.
1392   bool isScalarEpilogueAllowed() const {
1393     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1394   }
1395 
1396   /// Returns true if all loop blocks should be masked to fold tail loop.
1397   bool foldTailByMasking() const { return FoldTailByMasking; }
1398 
1399   bool blockNeedsPredication(BasicBlock *BB) {
1400     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1401   }
1402 
1403   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1404   /// nodes to the chain of instructions representing the reductions. Uses a
1405   /// MapVector to ensure deterministic iteration order.
1406   using ReductionChainMap =
1407       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1408 
1409   /// Return the chain of instructions representing an inloop reduction.
1410   const ReductionChainMap &getInLoopReductionChains() const {
1411     return InLoopReductionChains;
1412   }
1413 
1414   /// Returns true if the Phi is part of an inloop reduction.
1415   bool isInLoopReduction(PHINode *Phi) const {
1416     return InLoopReductionChains.count(Phi);
1417   }
1418 
1419   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1420   /// with factor VF.  Return the cost of the instruction, including
1421   /// scalarization overhead if it's needed.
1422   unsigned getVectorIntrinsicCost(CallInst *CI, ElementCount VF);
1423 
1424   /// Estimate cost of a call instruction CI if it were vectorized with factor
1425   /// VF. Return the cost of the instruction, including scalarization overhead
1426   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1427   /// scalarized -
1428   /// i.e. either vector version isn't available, or is too expensive.
1429   unsigned getVectorCallCost(CallInst *CI, ElementCount VF,
1430                              bool &NeedToScalarize);
1431 
1432   /// Invalidates decisions already taken by the cost model.
1433   void invalidateCostModelingDecisions() {
1434     WideningDecisions.clear();
1435     Uniforms.clear();
1436     Scalars.clear();
1437   }
1438 
1439 private:
1440   unsigned NumPredStores = 0;
1441 
1442   /// \return An upper bound for the vectorization factor, a power-of-2 larger
1443   /// than zero. One is returned if vectorization should best be avoided due
1444   /// to cost.
1445   unsigned computeFeasibleMaxVF(unsigned ConstTripCount);
1446 
1447   /// The vectorization cost is a combination of the cost itself and a boolean
1448   /// indicating whether any of the contributing operations will actually
1449   /// operate on
1450   /// vector values after type legalization in the backend. If this latter value
1451   /// is
1452   /// false, then all operations will be scalarized (i.e. no vectorization has
1453   /// actually taken place).
1454   using VectorizationCostTy = std::pair<unsigned, bool>;
1455 
1456   /// Returns the expected execution cost. The unit of the cost does
1457   /// not matter because we use the 'cost' units to compare different
1458   /// vector widths. The cost that is returned is *not* normalized by
1459   /// the factor width.
1460   VectorizationCostTy expectedCost(ElementCount VF);
1461 
1462   /// Returns the execution time cost of an instruction for a given vector
1463   /// width. Vector width of one means scalar.
1464   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1465 
1466   /// The cost-computation logic from getInstructionCost which provides
1467   /// the vector type as an output parameter.
1468   unsigned getInstructionCost(Instruction *I, ElementCount VF, Type *&VectorTy);
1469 
1470   /// Calculate vectorization cost of memory instruction \p I.
1471   unsigned getMemoryInstructionCost(Instruction *I, ElementCount VF);
1472 
1473   /// The cost computation for scalarized memory instruction.
1474   unsigned getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1475 
1476   /// The cost computation for interleaving group of memory instructions.
1477   unsigned getInterleaveGroupCost(Instruction *I, ElementCount VF);
1478 
1479   /// The cost computation for Gather/Scatter instruction.
1480   unsigned getGatherScatterCost(Instruction *I, ElementCount VF);
1481 
1482   /// The cost computation for widening instruction \p I with consecutive
1483   /// memory access.
1484   unsigned getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1485 
1486   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1487   /// Load: scalar load + broadcast.
1488   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1489   /// element)
1490   unsigned getUniformMemOpCost(Instruction *I, ElementCount VF);
1491 
1492   /// Estimate the overhead of scalarizing an instruction. This is a
1493   /// convenience wrapper for the type-based getScalarizationOverhead API.
1494   unsigned getScalarizationOverhead(Instruction *I, ElementCount VF);
1495 
1496   /// Returns whether the instruction is a load or store and will be a emitted
1497   /// as a vector operation.
1498   bool isConsecutiveLoadOrStore(Instruction *I);
1499 
1500   /// Returns true if an artificially high cost for emulated masked memrefs
1501   /// should be used.
1502   bool useEmulatedMaskMemRefHack(Instruction *I);
1503 
1504   /// Map of scalar integer values to the smallest bitwidth they can be legally
1505   /// represented as. The vector equivalents of these values should be truncated
1506   /// to this type.
1507   MapVector<Instruction *, uint64_t> MinBWs;
1508 
1509   /// A type representing the costs for instructions if they were to be
1510   /// scalarized rather than vectorized. The entries are Instruction-Cost
1511   /// pairs.
1512   using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
1513 
1514   /// A set containing all BasicBlocks that are known to present after
1515   /// vectorization as a predicated block.
1516   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1517 
1518   /// Records whether it is allowed to have the original scalar loop execute at
1519   /// least once. This may be needed as a fallback loop in case runtime
1520   /// aliasing/dependence checks fail, or to handle the tail/remainder
1521   /// iterations when the trip count is unknown or doesn't divide by the VF,
1522   /// or as a peel-loop to handle gaps in interleave-groups.
1523   /// Under optsize and when the trip count is very small we don't allow any
1524   /// iterations to execute in the scalar loop.
1525   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1526 
1527   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1528   bool FoldTailByMasking = false;
1529 
1530   /// A map holding scalar costs for different vectorization factors. The
1531   /// presence of a cost for an instruction in the mapping indicates that the
1532   /// instruction will be scalarized when vectorizing with the associated
1533   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1534   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1535 
1536   /// Holds the instructions known to be uniform after vectorization.
1537   /// The data is collected per VF.
1538   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1539 
1540   /// Holds the instructions known to be scalar after vectorization.
1541   /// The data is collected per VF.
1542   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1543 
1544   /// Holds the instructions (address computations) that are forced to be
1545   /// scalarized.
1546   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1547 
1548   /// PHINodes of the reductions that should be expanded in-loop along with
1549   /// their associated chains of reduction operations, in program order from top
1550   /// (PHI) to bottom
1551   ReductionChainMap InLoopReductionChains;
1552 
1553   /// Returns the expected difference in cost from scalarizing the expression
1554   /// feeding a predicated instruction \p PredInst. The instructions to
1555   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1556   /// non-negative return value implies the expression will be scalarized.
1557   /// Currently, only single-use chains are considered for scalarization.
1558   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1559                               ElementCount VF);
1560 
1561   /// Collect the instructions that are uniform after vectorization. An
1562   /// instruction is uniform if we represent it with a single scalar value in
1563   /// the vectorized loop corresponding to each vector iteration. Examples of
1564   /// uniform instructions include pointer operands of consecutive or
1565   /// interleaved memory accesses. Note that although uniformity implies an
1566   /// instruction will be scalar, the reverse is not true. In general, a
1567   /// scalarized instruction will be represented by VF scalar values in the
1568   /// vectorized loop, each corresponding to an iteration of the original
1569   /// scalar loop.
1570   void collectLoopUniforms(ElementCount VF);
1571 
1572   /// Collect the instructions that are scalar after vectorization. An
1573   /// instruction is scalar if it is known to be uniform or will be scalarized
1574   /// during vectorization. Non-uniform scalarized instructions will be
1575   /// represented by VF values in the vectorized loop, each corresponding to an
1576   /// iteration of the original scalar loop.
1577   void collectLoopScalars(ElementCount VF);
1578 
1579   /// Keeps cost model vectorization decision and cost for instructions.
1580   /// Right now it is used for memory instructions only.
1581   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1582                                 std::pair<InstWidening, unsigned>>;
1583 
1584   DecisionList WideningDecisions;
1585 
1586   /// Returns true if \p V is expected to be vectorized and it needs to be
1587   /// extracted.
1588   bool needsExtract(Value *V, ElementCount VF) const {
1589     Instruction *I = dyn_cast<Instruction>(V);
1590     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1591         TheLoop->isLoopInvariant(I))
1592       return false;
1593 
1594     // Assume we can vectorize V (and hence we need extraction) if the
1595     // scalars are not computed yet. This can happen, because it is called
1596     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1597     // the scalars are collected. That should be a safe assumption in most
1598     // cases, because we check if the operands have vectorizable types
1599     // beforehand in LoopVectorizationLegality.
1600     return Scalars.find(VF) == Scalars.end() ||
1601            !isScalarAfterVectorization(I, VF);
1602   };
1603 
1604   /// Returns a range containing only operands needing to be extracted.
1605   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1606                                                    ElementCount VF) {
1607     return SmallVector<Value *, 4>(make_filter_range(
1608         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1609   }
1610 
1611 public:
1612   /// The loop that we evaluate.
1613   Loop *TheLoop;
1614 
1615   /// Predicated scalar evolution analysis.
1616   PredicatedScalarEvolution &PSE;
1617 
1618   /// Loop Info analysis.
1619   LoopInfo *LI;
1620 
1621   /// Vectorization legality.
1622   LoopVectorizationLegality *Legal;
1623 
1624   /// Vector target information.
1625   const TargetTransformInfo &TTI;
1626 
1627   /// Target Library Info.
1628   const TargetLibraryInfo *TLI;
1629 
1630   /// Demanded bits analysis.
1631   DemandedBits *DB;
1632 
1633   /// Assumption cache.
1634   AssumptionCache *AC;
1635 
1636   /// Interface to emit optimization remarks.
1637   OptimizationRemarkEmitter *ORE;
1638 
1639   const Function *TheFunction;
1640 
1641   /// Loop Vectorize Hint.
1642   const LoopVectorizeHints *Hints;
1643 
1644   /// The interleave access information contains groups of interleaved accesses
1645   /// with the same stride and close to each other.
1646   InterleavedAccessInfo &InterleaveInfo;
1647 
1648   /// Values to ignore in the cost model.
1649   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1650 
1651   /// Values to ignore in the cost model when VF > 1.
1652   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1653 };
1654 
1655 } // end namespace llvm
1656 
1657 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
1658 // vectorization. The loop needs to be annotated with #pragma omp simd
1659 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1660 // vector length information is not provided, vectorization is not considered
1661 // explicit. Interleave hints are not allowed either. These limitations will be
1662 // relaxed in the future.
1663 // Please, note that we are currently forced to abuse the pragma 'clang
1664 // vectorize' semantics. This pragma provides *auto-vectorization hints*
1665 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1666 // provides *explicit vectorization hints* (LV can bypass legal checks and
1667 // assume that vectorization is legal). However, both hints are implemented
1668 // using the same metadata (llvm.loop.vectorize, processed by
1669 // LoopVectorizeHints). This will be fixed in the future when the native IR
1670 // representation for pragma 'omp simd' is introduced.
1671 static bool isExplicitVecOuterLoop(Loop *OuterLp,
1672                                    OptimizationRemarkEmitter *ORE) {
1673   assert(!OuterLp->isInnermost() && "This is not an outer loop");
1674   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
1675 
1676   // Only outer loops with an explicit vectorization hint are supported.
1677   // Unannotated outer loops are ignored.
1678   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
1679     return false;
1680 
1681   Function *Fn = OuterLp->getHeader()->getParent();
1682   if (!Hints.allowVectorization(Fn, OuterLp,
1683                                 true /*VectorizeOnlyWhenForced*/)) {
1684     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
1685     return false;
1686   }
1687 
1688   if (Hints.getInterleave() > 1) {
1689     // TODO: Interleave support is future work.
1690     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
1691                          "outer loops.\n");
1692     Hints.emitRemarkWithHints();
1693     return false;
1694   }
1695 
1696   return true;
1697 }
1698 
1699 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
1700                                   OptimizationRemarkEmitter *ORE,
1701                                   SmallVectorImpl<Loop *> &V) {
1702   // Collect inner loops and outer loops without irreducible control flow. For
1703   // now, only collect outer loops that have explicit vectorization hints. If we
1704   // are stress testing the VPlan H-CFG construction, we collect the outermost
1705   // loop of every loop nest.
1706   if (L.isInnermost() || VPlanBuildStressTest ||
1707       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
1708     LoopBlocksRPO RPOT(&L);
1709     RPOT.perform(LI);
1710     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
1711       V.push_back(&L);
1712       // TODO: Collect inner loops inside marked outer loops in case
1713       // vectorization fails for the outer loop. Do not invoke
1714       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1715       // already known to be reducible. We can use an inherited attribute for
1716       // that.
1717       return;
1718     }
1719   }
1720   for (Loop *InnerL : L)
1721     collectSupportedLoops(*InnerL, LI, ORE, V);
1722 }
1723 
1724 namespace {
1725 
1726 /// The LoopVectorize Pass.
1727 struct LoopVectorize : public FunctionPass {
1728   /// Pass identification, replacement for typeid
1729   static char ID;
1730 
1731   LoopVectorizePass Impl;
1732 
1733   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
1734                          bool VectorizeOnlyWhenForced = false)
1735       : FunctionPass(ID),
1736         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
1737     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1738   }
1739 
1740   bool runOnFunction(Function &F) override {
1741     if (skipFunction(F))
1742       return false;
1743 
1744     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1745     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1746     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1747     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1748     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1749     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1750     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
1751     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1752     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1753     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1754     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1755     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1756     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1757 
1758     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1759         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
1760 
1761     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
1762                         GetLAA, *ORE, PSI).MadeAnyChange;
1763   }
1764 
1765   void getAnalysisUsage(AnalysisUsage &AU) const override {
1766     AU.addRequired<AssumptionCacheTracker>();
1767     AU.addRequired<BlockFrequencyInfoWrapperPass>();
1768     AU.addRequired<DominatorTreeWrapperPass>();
1769     AU.addRequired<LoopInfoWrapperPass>();
1770     AU.addRequired<ScalarEvolutionWrapperPass>();
1771     AU.addRequired<TargetTransformInfoWrapperPass>();
1772     AU.addRequired<AAResultsWrapperPass>();
1773     AU.addRequired<LoopAccessLegacyAnalysis>();
1774     AU.addRequired<DemandedBitsWrapperPass>();
1775     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1776     AU.addRequired<InjectTLIMappingsLegacy>();
1777 
1778     // We currently do not preserve loopinfo/dominator analyses with outer loop
1779     // vectorization. Until this is addressed, mark these analyses as preserved
1780     // only for non-VPlan-native path.
1781     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
1782     if (!EnableVPlanNativePath) {
1783       AU.addPreserved<LoopInfoWrapperPass>();
1784       AU.addPreserved<DominatorTreeWrapperPass>();
1785     }
1786 
1787     AU.addPreserved<BasicAAWrapperPass>();
1788     AU.addPreserved<GlobalsAAWrapperPass>();
1789     AU.addRequired<ProfileSummaryInfoWrapperPass>();
1790   }
1791 };
1792 
1793 } // end anonymous namespace
1794 
1795 //===----------------------------------------------------------------------===//
1796 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1797 // LoopVectorizationCostModel and LoopVectorizationPlanner.
1798 //===----------------------------------------------------------------------===//
1799 
1800 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1801   // We need to place the broadcast of invariant variables outside the loop,
1802   // but only if it's proven safe to do so. Else, broadcast will be inside
1803   // vector loop body.
1804   Instruction *Instr = dyn_cast<Instruction>(V);
1805   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
1806                      (!Instr ||
1807                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
1808   // Place the code for broadcasting invariant variables in the new preheader.
1809   IRBuilder<>::InsertPointGuard Guard(Builder);
1810   if (SafeToHoist)
1811     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1812 
1813   // Broadcast the scalar into all locations in the vector.
1814   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1815 
1816   return Shuf;
1817 }
1818 
1819 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
1820     const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
1821   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1822          "Expected either an induction phi-node or a truncate of it!");
1823   Value *Start = II.getStartValue();
1824 
1825   // Construct the initial value of the vector IV in the vector loop preheader
1826   auto CurrIP = Builder.saveIP();
1827   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1828   if (isa<TruncInst>(EntryVal)) {
1829     assert(Start->getType()->isIntegerTy() &&
1830            "Truncation requires an integer type");
1831     auto *TruncType = cast<IntegerType>(EntryVal->getType());
1832     Step = Builder.CreateTrunc(Step, TruncType);
1833     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
1834   }
1835   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
1836   Value *SteppedStart =
1837       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
1838 
1839   // We create vector phi nodes for both integer and floating-point induction
1840   // variables. Here, we determine the kind of arithmetic we will perform.
1841   Instruction::BinaryOps AddOp;
1842   Instruction::BinaryOps MulOp;
1843   if (Step->getType()->isIntegerTy()) {
1844     AddOp = Instruction::Add;
1845     MulOp = Instruction::Mul;
1846   } else {
1847     AddOp = II.getInductionOpcode();
1848     MulOp = Instruction::FMul;
1849   }
1850 
1851   // Multiply the vectorization factor by the step using integer or
1852   // floating-point arithmetic as appropriate.
1853   Value *ConstVF =
1854       getSignedIntOrFpConstant(Step->getType(), VF.getKnownMinValue());
1855   Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
1856 
1857   // Create a vector splat to use in the induction update.
1858   //
1859   // FIXME: If the step is non-constant, we create the vector splat with
1860   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
1861   //        handle a constant vector splat.
1862   assert(!VF.isScalable() && "scalable vectors not yet supported.");
1863   Value *SplatVF = isa<Constant>(Mul)
1864                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
1865                        : Builder.CreateVectorSplat(VF, Mul);
1866   Builder.restoreIP(CurrIP);
1867 
1868   // We may need to add the step a number of times, depending on the unroll
1869   // factor. The last of those goes into the PHI.
1870   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
1871                                     &*LoopVectorBody->getFirstInsertionPt());
1872   VecInd->setDebugLoc(EntryVal->getDebugLoc());
1873   Instruction *LastInduction = VecInd;
1874   for (unsigned Part = 0; Part < UF; ++Part) {
1875     VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
1876 
1877     if (isa<TruncInst>(EntryVal))
1878       addMetadata(LastInduction, EntryVal);
1879     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
1880 
1881     LastInduction = cast<Instruction>(addFastMathFlag(
1882         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
1883     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
1884   }
1885 
1886   // Move the last step to the end of the latch block. This ensures consistent
1887   // placement of all induction updates.
1888   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
1889   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
1890   auto *ICmp = cast<Instruction>(Br->getCondition());
1891   LastInduction->moveBefore(ICmp);
1892   LastInduction->setName("vec.ind.next");
1893 
1894   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
1895   VecInd->addIncoming(LastInduction, LoopVectorLatch);
1896 }
1897 
1898 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
1899   return Cost->isScalarAfterVectorization(I, VF) ||
1900          Cost->isProfitableToScalarize(I, VF);
1901 }
1902 
1903 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
1904   if (shouldScalarizeInstruction(IV))
1905     return true;
1906   auto isScalarInst = [&](User *U) -> bool {
1907     auto *I = cast<Instruction>(U);
1908     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
1909   };
1910   return llvm::any_of(IV->users(), isScalarInst);
1911 }
1912 
1913 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
1914     const InductionDescriptor &ID, const Instruction *EntryVal,
1915     Value *VectorLoopVal, unsigned Part, unsigned Lane) {
1916   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
1917          "Expected either an induction phi-node or a truncate of it!");
1918 
1919   // This induction variable is not the phi from the original loop but the
1920   // newly-created IV based on the proof that casted Phi is equal to the
1921   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
1922   // re-uses the same InductionDescriptor that original IV uses but we don't
1923   // have to do any recording in this case - that is done when original IV is
1924   // processed.
1925   if (isa<TruncInst>(EntryVal))
1926     return;
1927 
1928   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
1929   if (Casts.empty())
1930     return;
1931   // Only the first Cast instruction in the Casts vector is of interest.
1932   // The rest of the Casts (if exist) have no uses outside the
1933   // induction update chain itself.
1934   Instruction *CastInst = *Casts.begin();
1935   if (Lane < UINT_MAX)
1936     VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
1937   else
1938     VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
1939 }
1940 
1941 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
1942   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
1943          "Primary induction variable must have an integer type");
1944 
1945   auto II = Legal->getInductionVars().find(IV);
1946   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
1947 
1948   auto ID = II->second;
1949   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
1950 
1951   // The value from the original loop to which we are mapping the new induction
1952   // variable.
1953   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
1954 
1955   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
1956 
1957   // Generate code for the induction step. Note that induction steps are
1958   // required to be loop-invariant
1959   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
1960     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
1961            "Induction step should be loop invariant");
1962     if (PSE.getSE()->isSCEVable(IV->getType())) {
1963       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
1964       return Exp.expandCodeFor(Step, Step->getType(),
1965                                LoopVectorPreHeader->getTerminator());
1966     }
1967     return cast<SCEVUnknown>(Step)->getValue();
1968   };
1969 
1970   // The scalar value to broadcast. This is derived from the canonical
1971   // induction variable. If a truncation type is given, truncate the canonical
1972   // induction variable and step. Otherwise, derive these values from the
1973   // induction descriptor.
1974   auto CreateScalarIV = [&](Value *&Step) -> Value * {
1975     Value *ScalarIV = Induction;
1976     if (IV != OldInduction) {
1977       ScalarIV = IV->getType()->isIntegerTy()
1978                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
1979                      : Builder.CreateCast(Instruction::SIToFP, Induction,
1980                                           IV->getType());
1981       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
1982       ScalarIV->setName("offset.idx");
1983     }
1984     if (Trunc) {
1985       auto *TruncType = cast<IntegerType>(Trunc->getType());
1986       assert(Step->getType()->isIntegerTy() &&
1987              "Truncation requires an integer step");
1988       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
1989       Step = Builder.CreateTrunc(Step, TruncType);
1990     }
1991     return ScalarIV;
1992   };
1993 
1994   // Create the vector values from the scalar IV, in the absence of creating a
1995   // vector IV.
1996   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
1997     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
1998     for (unsigned Part = 0; Part < UF; ++Part) {
1999       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2000       Value *EntryPart =
2001           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2002                         ID.getInductionOpcode());
2003       VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
2004       if (Trunc)
2005         addMetadata(EntryPart, Trunc);
2006       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
2007     }
2008   };
2009 
2010   // Now do the actual transformations, and start with creating the step value.
2011   Value *Step = CreateStepValue(ID.getStep());
2012   if (VF.isZero() || VF.isScalar()) {
2013     Value *ScalarIV = CreateScalarIV(Step);
2014     CreateSplatIV(ScalarIV, Step);
2015     return;
2016   }
2017 
2018   // Determine if we want a scalar version of the induction variable. This is
2019   // true if the induction variable itself is not widened, or if it has at
2020   // least one user in the loop that is not widened.
2021   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2022   if (!NeedsScalarIV) {
2023     createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2024     return;
2025   }
2026 
2027   // Try to create a new independent vector induction variable. If we can't
2028   // create the phi node, we will splat the scalar induction variable in each
2029   // loop iteration.
2030   if (!shouldScalarizeInstruction(EntryVal)) {
2031     createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2032     Value *ScalarIV = CreateScalarIV(Step);
2033     // Create scalar steps that can be used by instructions we will later
2034     // scalarize. Note that the addition of the scalar steps will not increase
2035     // the number of instructions in the loop in the common case prior to
2036     // InstCombine. We will be trading one vector extract for each scalar step.
2037     buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2038     return;
2039   }
2040 
2041   // All IV users are scalar instructions, so only emit a scalar IV, not a
2042   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2043   // predicate used by the masked loads/stores.
2044   Value *ScalarIV = CreateScalarIV(Step);
2045   if (!Cost->isScalarEpilogueAllowed())
2046     CreateSplatIV(ScalarIV, Step);
2047   buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2048 }
2049 
2050 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2051                                           Instruction::BinaryOps BinOp) {
2052   // Create and check the types.
2053   auto *ValVTy = cast<FixedVectorType>(Val->getType());
2054   int VLen = ValVTy->getNumElements();
2055 
2056   Type *STy = Val->getType()->getScalarType();
2057   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2058          "Induction Step must be an integer or FP");
2059   assert(Step->getType() == STy && "Step has wrong type");
2060 
2061   SmallVector<Constant *, 8> Indices;
2062 
2063   if (STy->isIntegerTy()) {
2064     // Create a vector of consecutive numbers from zero to VF.
2065     for (int i = 0; i < VLen; ++i)
2066       Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2067 
2068     // Add the consecutive indices to the vector value.
2069     Constant *Cv = ConstantVector::get(Indices);
2070     assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2071     Step = Builder.CreateVectorSplat(VLen, Step);
2072     assert(Step->getType() == Val->getType() && "Invalid step vec");
2073     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2074     // which can be found from the original scalar operations.
2075     Step = Builder.CreateMul(Cv, Step);
2076     return Builder.CreateAdd(Val, Step, "induction");
2077   }
2078 
2079   // Floating point induction.
2080   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2081          "Binary Opcode should be specified for FP induction");
2082   // Create a vector of consecutive numbers from zero to VF.
2083   for (int i = 0; i < VLen; ++i)
2084     Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2085 
2086   // Add the consecutive indices to the vector value.
2087   Constant *Cv = ConstantVector::get(Indices);
2088 
2089   Step = Builder.CreateVectorSplat(VLen, Step);
2090 
2091   // Floating point operations had to be 'fast' to enable the induction.
2092   FastMathFlags Flags;
2093   Flags.setFast();
2094 
2095   Value *MulOp = Builder.CreateFMul(Cv, Step);
2096   if (isa<Instruction>(MulOp))
2097     // Have to check, MulOp may be a constant
2098     cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2099 
2100   Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2101   if (isa<Instruction>(BOp))
2102     cast<Instruction>(BOp)->setFastMathFlags(Flags);
2103   return BOp;
2104 }
2105 
2106 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2107                                            Instruction *EntryVal,
2108                                            const InductionDescriptor &ID) {
2109   // We shouldn't have to build scalar steps if we aren't vectorizing.
2110   assert(VF.isVector() && "VF should be greater than one");
2111   assert(!VF.isScalable() &&
2112          "the code below assumes a fixed number of elements at compile time");
2113   // Get the value type and ensure it and the step have the same integer type.
2114   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2115   assert(ScalarIVTy == Step->getType() &&
2116          "Val and Step should have the same type");
2117 
2118   // We build scalar steps for both integer and floating-point induction
2119   // variables. Here, we determine the kind of arithmetic we will perform.
2120   Instruction::BinaryOps AddOp;
2121   Instruction::BinaryOps MulOp;
2122   if (ScalarIVTy->isIntegerTy()) {
2123     AddOp = Instruction::Add;
2124     MulOp = Instruction::Mul;
2125   } else {
2126     AddOp = ID.getInductionOpcode();
2127     MulOp = Instruction::FMul;
2128   }
2129 
2130   // Determine the number of scalars we need to generate for each unroll
2131   // iteration. If EntryVal is uniform, we only need to generate the first
2132   // lane. Otherwise, we generate all VF values.
2133   unsigned Lanes =
2134       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF)
2135           ? 1
2136           : VF.getKnownMinValue();
2137   // Compute the scalar steps and save the results in VectorLoopValueMap.
2138   for (unsigned Part = 0; Part < UF; ++Part) {
2139     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2140       auto *StartIdx = getSignedIntOrFpConstant(
2141           ScalarIVTy, VF.getKnownMinValue() * Part + Lane);
2142       auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2143       auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2144       VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
2145       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
2146     }
2147   }
2148 }
2149 
2150 Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
2151   assert(V != Induction && "The new induction variable should not be used.");
2152   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2153   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2154 
2155   // If we have a stride that is replaced by one, do it here. Defer this for
2156   // the VPlan-native path until we start running Legal checks in that path.
2157   if (!EnableVPlanNativePath && Legal->hasStride(V))
2158     V = ConstantInt::get(V->getType(), 1);
2159 
2160   // If we have a vector mapped to this value, return it.
2161   if (VectorLoopValueMap.hasVectorValue(V, Part))
2162     return VectorLoopValueMap.getVectorValue(V, Part);
2163 
2164   // If the value has not been vectorized, check if it has been scalarized
2165   // instead. If it has been scalarized, and we actually need the value in
2166   // vector form, we will construct the vector values on demand.
2167   if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2168     Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
2169 
2170     // If we've scalarized a value, that value should be an instruction.
2171     auto *I = cast<Instruction>(V);
2172 
2173     // If we aren't vectorizing, we can just copy the scalar map values over to
2174     // the vector map.
2175     if (VF.isScalar()) {
2176       VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2177       return ScalarValue;
2178     }
2179 
2180     // Get the last scalar instruction we generated for V and Part. If the value
2181     // is known to be uniform after vectorization, this corresponds to lane zero
2182     // of the Part unroll iteration. Otherwise, the last instruction is the one
2183     // we created for the last vector lane of the Part unroll iteration.
2184     assert(!VF.isScalable() && "scalable vectors not yet supported.");
2185     unsigned LastLane = Cost->isUniformAfterVectorization(I, VF)
2186                             ? 0
2187                             : VF.getKnownMinValue() - 1;
2188     auto *LastInst = cast<Instruction>(
2189         VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
2190 
2191     // Set the insert point after the last scalarized instruction. This ensures
2192     // the insertelement sequence will directly follow the scalar definitions.
2193     auto OldIP = Builder.saveIP();
2194     auto NewIP = std::next(BasicBlock::iterator(LastInst));
2195     Builder.SetInsertPoint(&*NewIP);
2196 
2197     // However, if we are vectorizing, we need to construct the vector values.
2198     // If the value is known to be uniform after vectorization, we can just
2199     // broadcast the scalar value corresponding to lane zero for each unroll
2200     // iteration. Otherwise, we construct the vector values using insertelement
2201     // instructions. Since the resulting vectors are stored in
2202     // VectorLoopValueMap, we will only generate the insertelements once.
2203     Value *VectorValue = nullptr;
2204     if (Cost->isUniformAfterVectorization(I, VF)) {
2205       VectorValue = getBroadcastInstrs(ScalarValue);
2206       VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2207     } else {
2208       // Initialize packing with insertelements to start from undef.
2209       assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2210       Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
2211       VectorLoopValueMap.setVectorValue(V, Part, Undef);
2212       for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
2213         packScalarIntoVectorValue(V, {Part, Lane});
2214       VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2215     }
2216     Builder.restoreIP(OldIP);
2217     return VectorValue;
2218   }
2219 
2220   // If this scalar is unknown, assume that it is a constant or that it is
2221   // loop invariant. Broadcast V and save the value for future uses.
2222   Value *B = getBroadcastInstrs(V);
2223   VectorLoopValueMap.setVectorValue(V, Part, B);
2224   return B;
2225 }
2226 
2227 Value *
2228 InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
2229                                             const VPIteration &Instance) {
2230   // If the value is not an instruction contained in the loop, it should
2231   // already be scalar.
2232   if (OrigLoop->isLoopInvariant(V))
2233     return V;
2234 
2235   assert(Instance.Lane > 0
2236              ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2237              : true && "Uniform values only have lane zero");
2238 
2239   // If the value from the original loop has not been vectorized, it is
2240   // represented by UF x VF scalar values in the new loop. Return the requested
2241   // scalar value.
2242   if (VectorLoopValueMap.hasScalarValue(V, Instance))
2243     return VectorLoopValueMap.getScalarValue(V, Instance);
2244 
2245   // If the value has not been scalarized, get its entry in VectorLoopValueMap
2246   // for the given unroll part. If this entry is not a vector type (i.e., the
2247   // vectorization factor is one), there is no need to generate an
2248   // extractelement instruction.
2249   auto *U = getOrCreateVectorValue(V, Instance.Part);
2250   if (!U->getType()->isVectorTy()) {
2251     assert(VF.isScalar() && "Value not scalarized has non-vector type");
2252     return U;
2253   }
2254 
2255   // Otherwise, the value from the original loop has been vectorized and is
2256   // represented by UF vector values. Extract and return the requested scalar
2257   // value from the appropriate vector lane.
2258   return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2259 }
2260 
2261 void InnerLoopVectorizer::packScalarIntoVectorValue(
2262     Value *V, const VPIteration &Instance) {
2263   assert(V != Induction && "The new induction variable should not be used.");
2264   assert(!V->getType()->isVectorTy() && "Can't pack a vector");
2265   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2266 
2267   Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2268   Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2269   VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2270                                             Builder.getInt32(Instance.Lane));
2271   VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2272 }
2273 
2274 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2275   assert(Vec->getType()->isVectorTy() && "Invalid type");
2276   assert(!VF.isScalable() && "Cannot reverse scalable vectors");
2277   SmallVector<int, 8> ShuffleMask;
2278   for (unsigned i = 0; i < VF.getKnownMinValue(); ++i)
2279     ShuffleMask.push_back(VF.getKnownMinValue() - i - 1);
2280 
2281   return Builder.CreateShuffleVector(Vec, ShuffleMask, "reverse");
2282 }
2283 
2284 // Return whether we allow using masked interleave-groups (for dealing with
2285 // strided loads/stores that reside in predicated blocks, or for dealing
2286 // with gaps).
2287 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2288   // If an override option has been passed in for interleaved accesses, use it.
2289   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2290     return EnableMaskedInterleavedMemAccesses;
2291 
2292   return TTI.enableMaskedInterleavedAccessVectorization();
2293 }
2294 
2295 // Try to vectorize the interleave group that \p Instr belongs to.
2296 //
2297 // E.g. Translate following interleaved load group (factor = 3):
2298 //   for (i = 0; i < N; i+=3) {
2299 //     R = Pic[i];             // Member of index 0
2300 //     G = Pic[i+1];           // Member of index 1
2301 //     B = Pic[i+2];           // Member of index 2
2302 //     ... // do something to R, G, B
2303 //   }
2304 // To:
2305 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2306 //   %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9>   ; R elements
2307 //   %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10>  ; G elements
2308 //   %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11>  ; B elements
2309 //
2310 // Or translate following interleaved store group (factor = 3):
2311 //   for (i = 0; i < N; i+=3) {
2312 //     ... do something to R, G, B
2313 //     Pic[i]   = R;           // Member of index 0
2314 //     Pic[i+1] = G;           // Member of index 1
2315 //     Pic[i+2] = B;           // Member of index 2
2316 //   }
2317 // To:
2318 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2319 //   %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2320 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2321 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2322 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2323 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2324     const InterleaveGroup<Instruction> *Group, VPTransformState &State,
2325     VPValue *Addr, VPValue *BlockInMask) {
2326   Instruction *Instr = Group->getInsertPos();
2327   const DataLayout &DL = Instr->getModule()->getDataLayout();
2328 
2329   // Prepare for the vector type of the interleaved load/store.
2330   Type *ScalarTy = getMemInstValueType(Instr);
2331   unsigned InterleaveFactor = Group->getFactor();
2332   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2333   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2334 
2335   // Prepare for the new pointers.
2336   SmallVector<Value *, 2> AddrParts;
2337   unsigned Index = Group->getIndex(Instr);
2338 
2339   // TODO: extend the masked interleaved-group support to reversed access.
2340   assert((!BlockInMask || !Group->isReverse()) &&
2341          "Reversed masked interleave-group not supported.");
2342 
2343   // If the group is reverse, adjust the index to refer to the last vector lane
2344   // instead of the first. We adjust the index from the first vector lane,
2345   // rather than directly getting the pointer for lane VF - 1, because the
2346   // pointer operand of the interleaved access is supposed to be uniform. For
2347   // uniform instructions, we're only required to generate a value for the
2348   // first vector lane in each unroll iteration.
2349   assert(!VF.isScalable() &&
2350          "scalable vector reverse operation is not implemented");
2351   if (Group->isReverse())
2352     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2353 
2354   for (unsigned Part = 0; Part < UF; Part++) {
2355     Value *AddrPart = State.get(Addr, {Part, 0});
2356     setDebugLocFromInst(Builder, AddrPart);
2357 
2358     // Notice current instruction could be any index. Need to adjust the address
2359     // to the member of index 0.
2360     //
2361     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2362     //       b = A[i];       // Member of index 0
2363     // Current pointer is pointed to A[i+1], adjust it to A[i].
2364     //
2365     // E.g.  A[i+1] = a;     // Member of index 1
2366     //       A[i]   = b;     // Member of index 0
2367     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2368     // Current pointer is pointed to A[i+2], adjust it to A[i].
2369 
2370     bool InBounds = false;
2371     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2372       InBounds = gep->isInBounds();
2373     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2374     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2375 
2376     // Cast to the vector pointer type.
2377     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2378     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2379     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2380   }
2381 
2382   setDebugLocFromInst(Builder, Instr);
2383   Value *UndefVec = UndefValue::get(VecTy);
2384 
2385   Value *MaskForGaps = nullptr;
2386   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2387     assert(!VF.isScalable() && "scalable vectors not yet supported.");
2388     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2389     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2390   }
2391 
2392   // Vectorize the interleaved load group.
2393   if (isa<LoadInst>(Instr)) {
2394     // For each unroll part, create a wide load for the group.
2395     SmallVector<Value *, 2> NewLoads;
2396     for (unsigned Part = 0; Part < UF; Part++) {
2397       Instruction *NewLoad;
2398       if (BlockInMask || MaskForGaps) {
2399         assert(useMaskedInterleavedAccesses(*TTI) &&
2400                "masked interleaved groups are not allowed.");
2401         Value *GroupMask = MaskForGaps;
2402         if (BlockInMask) {
2403           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2404           assert(!VF.isScalable() && "scalable vectors not yet supported.");
2405           Value *ShuffledMask = Builder.CreateShuffleVector(
2406               BlockInMaskPart,
2407               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2408               "interleaved.mask");
2409           GroupMask = MaskForGaps
2410                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2411                                                 MaskForGaps)
2412                           : ShuffledMask;
2413         }
2414         NewLoad =
2415             Builder.CreateMaskedLoad(AddrParts[Part], Group->getAlign(),
2416                                      GroupMask, UndefVec, "wide.masked.vec");
2417       }
2418       else
2419         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2420                                             Group->getAlign(), "wide.vec");
2421       Group->addMetadata(NewLoad);
2422       NewLoads.push_back(NewLoad);
2423     }
2424 
2425     // For each member in the group, shuffle out the appropriate data from the
2426     // wide loads.
2427     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2428       Instruction *Member = Group->getMember(I);
2429 
2430       // Skip the gaps in the group.
2431       if (!Member)
2432         continue;
2433 
2434       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2435       auto StrideMask =
2436           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2437       for (unsigned Part = 0; Part < UF; Part++) {
2438         Value *StridedVec = Builder.CreateShuffleVector(
2439             NewLoads[Part], StrideMask, "strided.vec");
2440 
2441         // If this member has different type, cast the result type.
2442         if (Member->getType() != ScalarTy) {
2443           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2444           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2445           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2446         }
2447 
2448         if (Group->isReverse())
2449           StridedVec = reverseVector(StridedVec);
2450 
2451         VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
2452       }
2453     }
2454     return;
2455   }
2456 
2457   // The sub vector type for current instruction.
2458   assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2459   auto *SubVT = VectorType::get(ScalarTy, VF);
2460 
2461   // Vectorize the interleaved store group.
2462   for (unsigned Part = 0; Part < UF; Part++) {
2463     // Collect the stored vector from each member.
2464     SmallVector<Value *, 4> StoredVecs;
2465     for (unsigned i = 0; i < InterleaveFactor; i++) {
2466       // Interleaved store group doesn't allow a gap, so each index has a member
2467       Instruction *Member = Group->getMember(i);
2468       assert(Member && "Fail to get a member from an interleaved store group");
2469 
2470       Value *StoredVec = getOrCreateVectorValue(
2471           cast<StoreInst>(Member)->getValueOperand(), Part);
2472       if (Group->isReverse())
2473         StoredVec = reverseVector(StoredVec);
2474 
2475       // If this member has different type, cast it to a unified type.
2476 
2477       if (StoredVec->getType() != SubVT)
2478         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2479 
2480       StoredVecs.push_back(StoredVec);
2481     }
2482 
2483     // Concatenate all vectors into a wide vector.
2484     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2485 
2486     // Interleave the elements in the wide vector.
2487     assert(!VF.isScalable() && "scalable vectors not yet supported.");
2488     Value *IVec = Builder.CreateShuffleVector(
2489         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2490         "interleaved.vec");
2491 
2492     Instruction *NewStoreInstr;
2493     if (BlockInMask) {
2494       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2495       Value *ShuffledMask = Builder.CreateShuffleVector(
2496           BlockInMaskPart,
2497           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2498           "interleaved.mask");
2499       NewStoreInstr = Builder.CreateMaskedStore(
2500           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2501     }
2502     else
2503       NewStoreInstr =
2504           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2505 
2506     Group->addMetadata(NewStoreInstr);
2507   }
2508 }
2509 
2510 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2511     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2512     VPValue *StoredValue, VPValue *BlockInMask) {
2513   // Attempt to issue a wide load.
2514   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2515   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2516 
2517   assert((LI || SI) && "Invalid Load/Store instruction");
2518   assert((!SI || StoredValue) && "No stored value provided for widened store");
2519   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2520 
2521   LoopVectorizationCostModel::InstWidening Decision =
2522       Cost->getWideningDecision(Instr, VF);
2523   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2524           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2525           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2526          "CM decision is not to widen the memory instruction");
2527 
2528   Type *ScalarDataTy = getMemInstValueType(Instr);
2529 
2530   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2531   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2532   const Align Alignment = getLoadStoreAlignment(Instr);
2533 
2534   // Determine if the pointer operand of the access is either consecutive or
2535   // reverse consecutive.
2536   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2537   bool ConsecutiveStride =
2538       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2539   bool CreateGatherScatter =
2540       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2541 
2542   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2543   // gather/scatter. Otherwise Decision should have been to Scalarize.
2544   assert((ConsecutiveStride || CreateGatherScatter) &&
2545          "The instruction should be scalarized");
2546   (void)ConsecutiveStride;
2547 
2548   VectorParts BlockInMaskParts(UF);
2549   bool isMaskRequired = BlockInMask;
2550   if (isMaskRequired)
2551     for (unsigned Part = 0; Part < UF; ++Part)
2552       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2553 
2554   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2555     // Calculate the pointer for the specific unroll-part.
2556     GetElementPtrInst *PartPtr = nullptr;
2557 
2558     bool InBounds = false;
2559     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2560       InBounds = gep->isInBounds();
2561 
2562     if (Reverse) {
2563       // If the address is consecutive but reversed, then the
2564       // wide store needs to start at the last vector element.
2565       PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
2566           ScalarDataTy, Ptr, Builder.getInt32(-Part * VF.getKnownMinValue())));
2567       PartPtr->setIsInBounds(InBounds);
2568       PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
2569           ScalarDataTy, PartPtr, Builder.getInt32(1 - VF.getKnownMinValue())));
2570       PartPtr->setIsInBounds(InBounds);
2571       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2572         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2573     } else {
2574       PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
2575           ScalarDataTy, Ptr, Builder.getInt32(Part * VF.getKnownMinValue())));
2576       PartPtr->setIsInBounds(InBounds);
2577     }
2578 
2579     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2580     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2581   };
2582 
2583   // Handle Stores:
2584   if (SI) {
2585     setDebugLocFromInst(Builder, SI);
2586 
2587     for (unsigned Part = 0; Part < UF; ++Part) {
2588       Instruction *NewSI = nullptr;
2589       Value *StoredVal = State.get(StoredValue, Part);
2590       if (CreateGatherScatter) {
2591         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2592         Value *VectorGep = State.get(Addr, Part);
2593         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2594                                             MaskPart);
2595       } else {
2596         if (Reverse) {
2597           // If we store to reverse consecutive memory locations, then we need
2598           // to reverse the order of elements in the stored value.
2599           StoredVal = reverseVector(StoredVal);
2600           // We don't want to update the value in the map as it might be used in
2601           // another expression. So don't call resetVectorValue(StoredVal).
2602         }
2603         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, {0, 0}));
2604         if (isMaskRequired)
2605           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2606                                             BlockInMaskParts[Part]);
2607         else
2608           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2609       }
2610       addMetadata(NewSI, SI);
2611     }
2612     return;
2613   }
2614 
2615   // Handle loads.
2616   assert(LI && "Must have a load instruction");
2617   setDebugLocFromInst(Builder, LI);
2618   for (unsigned Part = 0; Part < UF; ++Part) {
2619     Value *NewLI;
2620     if (CreateGatherScatter) {
2621       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2622       Value *VectorGep = State.get(Addr, Part);
2623       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2624                                          nullptr, "wide.masked.gather");
2625       addMetadata(NewLI, LI);
2626     } else {
2627       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, {0, 0}));
2628       if (isMaskRequired)
2629         NewLI = Builder.CreateMaskedLoad(
2630             VecPtr, Alignment, BlockInMaskParts[Part], UndefValue::get(DataTy),
2631             "wide.masked.load");
2632       else
2633         NewLI =
2634             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
2635 
2636       // Add metadata to the load, but setVectorValue to the reverse shuffle.
2637       addMetadata(NewLI, LI);
2638       if (Reverse)
2639         NewLI = reverseVector(NewLI);
2640     }
2641 
2642     State.set(Def, Instr, NewLI, Part);
2643   }
2644 }
2645 
2646 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPUser &User,
2647                                                const VPIteration &Instance,
2648                                                bool IfPredicateInstr,
2649                                                VPTransformState &State) {
2650   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2651 
2652   setDebugLocFromInst(Builder, Instr);
2653 
2654   // Does this instruction return a value ?
2655   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2656 
2657   Instruction *Cloned = Instr->clone();
2658   if (!IsVoidRetTy)
2659     Cloned->setName(Instr->getName() + ".cloned");
2660 
2661   // Replace the operands of the cloned instructions with their scalar
2662   // equivalents in the new loop.
2663   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
2664     auto *NewOp = State.get(User.getOperand(op), Instance);
2665     Cloned->setOperand(op, NewOp);
2666   }
2667   addNewMetadata(Cloned, Instr);
2668 
2669   // Place the cloned scalar in the new loop.
2670   Builder.Insert(Cloned);
2671 
2672   // Add the cloned scalar to the scalar map entry.
2673   VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
2674 
2675   // If we just cloned a new assumption, add it the assumption cache.
2676   if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
2677     if (II->getIntrinsicID() == Intrinsic::assume)
2678       AC->registerAssumption(II);
2679 
2680   // End if-block.
2681   if (IfPredicateInstr)
2682     PredicatedInstructions.push_back(Cloned);
2683 }
2684 
2685 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2686                                                       Value *End, Value *Step,
2687                                                       Instruction *DL) {
2688   BasicBlock *Header = L->getHeader();
2689   BasicBlock *Latch = L->getLoopLatch();
2690   // As we're just creating this loop, it's possible no latch exists
2691   // yet. If so, use the header as this will be a single block loop.
2692   if (!Latch)
2693     Latch = Header;
2694 
2695   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2696   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
2697   setDebugLocFromInst(Builder, OldInst);
2698   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2699 
2700   Builder.SetInsertPoint(Latch->getTerminator());
2701   setDebugLocFromInst(Builder, OldInst);
2702 
2703   // Create i+1 and fill the PHINode.
2704   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2705   Induction->addIncoming(Start, L->getLoopPreheader());
2706   Induction->addIncoming(Next, Latch);
2707   // Create the compare.
2708   Value *ICmp = Builder.CreateICmpEQ(Next, End);
2709   Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
2710 
2711   // Now we have two terminators. Remove the old one from the block.
2712   Latch->getTerminator()->eraseFromParent();
2713 
2714   return Induction;
2715 }
2716 
2717 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2718   if (TripCount)
2719     return TripCount;
2720 
2721   assert(L && "Create Trip Count for null loop.");
2722   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2723   // Find the loop boundaries.
2724   ScalarEvolution *SE = PSE.getSE();
2725   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2726   assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
2727          "Invalid loop count");
2728 
2729   Type *IdxTy = Legal->getWidestInductionType();
2730   assert(IdxTy && "No type for induction");
2731 
2732   // The exit count might have the type of i64 while the phi is i32. This can
2733   // happen if we have an induction variable that is sign extended before the
2734   // compare. The only way that we get a backedge taken count is that the
2735   // induction variable was signed and as such will not overflow. In such a case
2736   // truncation is legal.
2737   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2738       IdxTy->getPrimitiveSizeInBits())
2739     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2740   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2741 
2742   // Get the total trip count from the count by adding 1.
2743   const SCEV *ExitCount = SE->getAddExpr(
2744       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2745 
2746   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2747 
2748   // Expand the trip count and place the new instructions in the preheader.
2749   // Notice that the pre-header does not change, only the loop body.
2750   SCEVExpander Exp(*SE, DL, "induction");
2751 
2752   // Count holds the overall loop count (N).
2753   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2754                                 L->getLoopPreheader()->getTerminator());
2755 
2756   if (TripCount->getType()->isPointerTy())
2757     TripCount =
2758         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2759                                     L->getLoopPreheader()->getTerminator());
2760 
2761   return TripCount;
2762 }
2763 
2764 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
2765   if (VectorTripCount)
2766     return VectorTripCount;
2767 
2768   Value *TC = getOrCreateTripCount(L);
2769   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2770 
2771   Type *Ty = TC->getType();
2772   // This is where we can make the step a runtime constant.
2773   assert(!VF.isScalable() && "scalable vectorization is not supported yet");
2774   Constant *Step = ConstantInt::get(Ty, VF.getKnownMinValue() * UF);
2775 
2776   // If the tail is to be folded by masking, round the number of iterations N
2777   // up to a multiple of Step instead of rounding down. This is done by first
2778   // adding Step-1 and then rounding down. Note that it's ok if this addition
2779   // overflows: the vector induction variable will eventually wrap to zero given
2780   // that it starts at zero and its Step is a power of two; the loop will then
2781   // exit, with the last early-exit vector comparison also producing all-true.
2782   if (Cost->foldTailByMasking()) {
2783     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2784            "VF*UF must be a power of 2 when folding tail by masking");
2785     TC = Builder.CreateAdd(
2786         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
2787   }
2788 
2789   // Now we need to generate the expression for the part of the loop that the
2790   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2791   // iterations are not required for correctness, or N - Step, otherwise. Step
2792   // is equal to the vectorization factor (number of SIMD elements) times the
2793   // unroll factor (number of SIMD instructions).
2794   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2795 
2796   // If there is a non-reversed interleaved group that may speculatively access
2797   // memory out-of-bounds, we need to ensure that there will be at least one
2798   // iteration of the scalar epilogue loop. Thus, if the step evenly divides
2799   // the trip count, we set the remainder to be equal to the step. If the step
2800   // does not evenly divide the trip count, no adjustment is necessary since
2801   // there will already be scalar iterations. Note that the minimum iterations
2802   // check ensures that N >= Step.
2803   if (VF.isVector() && Cost->requiresScalarEpilogue()) {
2804     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2805     R = Builder.CreateSelect(IsZero, Step, R);
2806   }
2807 
2808   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2809 
2810   return VectorTripCount;
2811 }
2812 
2813 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2814                                                    const DataLayout &DL) {
2815   // Verify that V is a vector type with same number of elements as DstVTy.
2816   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2817   unsigned VF = DstFVTy->getNumElements();
2818   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2819   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2820   Type *SrcElemTy = SrcVecTy->getElementType();
2821   Type *DstElemTy = DstFVTy->getElementType();
2822   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2823          "Vector elements must have same size");
2824 
2825   // Do a direct cast if element types are castable.
2826   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2827     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2828   }
2829   // V cannot be directly casted to desired vector type.
2830   // May happen when V is a floating point vector but DstVTy is a vector of
2831   // pointers or vice-versa. Handle this using a two-step bitcast using an
2832   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2833   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2834          "Only one type should be a pointer type");
2835   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2836          "Only one type should be a floating point type");
2837   Type *IntTy =
2838       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2839   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2840   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2841   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2842 }
2843 
2844 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
2845                                                          BasicBlock *Bypass) {
2846   Value *Count = getOrCreateTripCount(L);
2847   // Reuse existing vector loop preheader for TC checks.
2848   // Note that new preheader block is generated for vector loop.
2849   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2850   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2851 
2852   // Generate code to check if the loop's trip count is less than VF * UF, or
2853   // equal to it in case a scalar epilogue is required; this implies that the
2854   // vector trip count is zero. This check also covers the case where adding one
2855   // to the backedge-taken count overflowed leading to an incorrect trip count
2856   // of zero. In this case we will also jump to the scalar loop.
2857   auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
2858                                           : ICmpInst::ICMP_ULT;
2859 
2860   // If tail is to be folded, vector loop takes care of all iterations.
2861   Value *CheckMinIters = Builder.getFalse();
2862   if (!Cost->foldTailByMasking()) {
2863     assert(!VF.isScalable() && "scalable vectors not yet supported.");
2864     CheckMinIters = Builder.CreateICmp(
2865         P, Count,
2866         ConstantInt::get(Count->getType(), VF.getKnownMinValue() * UF),
2867         "min.iters.check");
2868   }
2869   // Create new preheader for vector loop.
2870   LoopVectorPreHeader =
2871       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2872                  "vector.ph");
2873 
2874   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
2875                                DT->getNode(Bypass)->getIDom()) &&
2876          "TC check is expected to dominate Bypass");
2877 
2878   // Update dominator for Bypass & LoopExit.
2879   DT->changeImmediateDominator(Bypass, TCCheckBlock);
2880   DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
2881 
2882   ReplaceInstWithInst(
2883       TCCheckBlock->getTerminator(),
2884       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
2885   LoopBypassBlocks.push_back(TCCheckBlock);
2886 }
2887 
2888 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
2889   // Reuse existing vector loop preheader for SCEV checks.
2890   // Note that new preheader block is generated for vector loop.
2891   BasicBlock *const SCEVCheckBlock = LoopVectorPreHeader;
2892 
2893   // Generate the code to check that the SCEV assumptions that we made.
2894   // We want the new basic block to start at the first instruction in a
2895   // sequence of instructions that form a check.
2896   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
2897                    "scev.check");
2898   Value *SCEVCheck = Exp.expandCodeForPredicate(
2899       &PSE.getUnionPredicate(), SCEVCheckBlock->getTerminator());
2900 
2901   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
2902     if (C->isZero())
2903       return;
2904 
2905   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
2906            (OptForSizeBasedOnProfile &&
2907             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
2908          "Cannot SCEV check stride or overflow when optimizing for size");
2909 
2910   SCEVCheckBlock->setName("vector.scevcheck");
2911   // Create new preheader for vector loop.
2912   LoopVectorPreHeader =
2913       SplitBlock(SCEVCheckBlock, SCEVCheckBlock->getTerminator(), DT, LI,
2914                  nullptr, "vector.ph");
2915 
2916   // Update dominator only if this is first RT check.
2917   if (LoopBypassBlocks.empty()) {
2918     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
2919     DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
2920   }
2921 
2922   ReplaceInstWithInst(
2923       SCEVCheckBlock->getTerminator(),
2924       BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheck));
2925   LoopBypassBlocks.push_back(SCEVCheckBlock);
2926   AddedSafetyChecks = true;
2927 }
2928 
2929 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
2930   // VPlan-native path does not do any analysis for runtime checks currently.
2931   if (EnableVPlanNativePath)
2932     return;
2933 
2934   // Reuse existing vector loop preheader for runtime memory checks.
2935   // Note that new preheader block is generated for vector loop.
2936   BasicBlock *const MemCheckBlock = L->getLoopPreheader();
2937 
2938   // Generate the code that checks in runtime if arrays overlap. We put the
2939   // checks into a separate block to make the more common case of few elements
2940   // faster.
2941   auto *LAI = Legal->getLAI();
2942   const auto &RtPtrChecking = *LAI->getRuntimePointerChecking();
2943   if (!RtPtrChecking.Need)
2944     return;
2945 
2946   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
2947     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
2948            "Cannot emit memory checks when optimizing for size, unless forced "
2949            "to vectorize.");
2950     ORE->emit([&]() {
2951       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
2952                                         L->getStartLoc(), L->getHeader())
2953              << "Code-size may be reduced by not forcing "
2954                 "vectorization, or by source-code modifications "
2955                 "eliminating the need for runtime checks "
2956                 "(e.g., adding 'restrict').";
2957     });
2958   }
2959 
2960   MemCheckBlock->setName("vector.memcheck");
2961   // Create new preheader for vector loop.
2962   LoopVectorPreHeader =
2963       SplitBlock(MemCheckBlock, MemCheckBlock->getTerminator(), DT, LI, nullptr,
2964                  "vector.ph");
2965 
2966   auto *CondBranch = cast<BranchInst>(
2967       Builder.CreateCondBr(Builder.getTrue(), Bypass, LoopVectorPreHeader));
2968   ReplaceInstWithInst(MemCheckBlock->getTerminator(), CondBranch);
2969   LoopBypassBlocks.push_back(MemCheckBlock);
2970   AddedSafetyChecks = true;
2971 
2972   // Update dominator only if this is first RT check.
2973   if (LoopBypassBlocks.empty()) {
2974     DT->changeImmediateDominator(Bypass, MemCheckBlock);
2975     DT->changeImmediateDominator(LoopExitBlock, MemCheckBlock);
2976   }
2977 
2978   Instruction *FirstCheckInst;
2979   Instruction *MemRuntimeCheck;
2980   std::tie(FirstCheckInst, MemRuntimeCheck) =
2981       addRuntimeChecks(MemCheckBlock->getTerminator(), OrigLoop,
2982                        RtPtrChecking.getChecks(), RtPtrChecking.getSE());
2983   assert(MemRuntimeCheck && "no RT checks generated although RtPtrChecking "
2984                             "claimed checks are required");
2985   CondBranch->setCondition(MemRuntimeCheck);
2986 
2987   // We currently don't use LoopVersioning for the actual loop cloning but we
2988   // still use it to add the noalias metadata.
2989   LVer = std::make_unique<LoopVersioning>(
2990       *Legal->getLAI(),
2991       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
2992       DT, PSE.getSE());
2993   LVer->prepareNoAliasMetadata();
2994 }
2995 
2996 Value *InnerLoopVectorizer::emitTransformedIndex(
2997     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
2998     const InductionDescriptor &ID) const {
2999 
3000   SCEVExpander Exp(*SE, DL, "induction");
3001   auto Step = ID.getStep();
3002   auto StartValue = ID.getStartValue();
3003   assert(Index->getType() == Step->getType() &&
3004          "Index type does not match StepValue type");
3005 
3006   // Note: the IR at this point is broken. We cannot use SE to create any new
3007   // SCEV and then expand it, hoping that SCEV's simplification will give us
3008   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3009   // lead to various SCEV crashes. So all we can do is to use builder and rely
3010   // on InstCombine for future simplifications. Here we handle some trivial
3011   // cases only.
3012   auto CreateAdd = [&B](Value *X, Value *Y) {
3013     assert(X->getType() == Y->getType() && "Types don't match!");
3014     if (auto *CX = dyn_cast<ConstantInt>(X))
3015       if (CX->isZero())
3016         return Y;
3017     if (auto *CY = dyn_cast<ConstantInt>(Y))
3018       if (CY->isZero())
3019         return X;
3020     return B.CreateAdd(X, Y);
3021   };
3022 
3023   auto CreateMul = [&B](Value *X, Value *Y) {
3024     assert(X->getType() == Y->getType() && "Types don't match!");
3025     if (auto *CX = dyn_cast<ConstantInt>(X))
3026       if (CX->isOne())
3027         return Y;
3028     if (auto *CY = dyn_cast<ConstantInt>(Y))
3029       if (CY->isOne())
3030         return X;
3031     return B.CreateMul(X, Y);
3032   };
3033 
3034   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3035   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3036   // the DomTree is not kept up-to-date for additional blocks generated in the
3037   // vector loop. By using the header as insertion point, we guarantee that the
3038   // expanded instructions dominate all their uses.
3039   auto GetInsertPoint = [this, &B]() {
3040     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3041     if (InsertBB != LoopVectorBody &&
3042         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3043       return LoopVectorBody->getTerminator();
3044     return &*B.GetInsertPoint();
3045   };
3046   switch (ID.getKind()) {
3047   case InductionDescriptor::IK_IntInduction: {
3048     assert(Index->getType() == StartValue->getType() &&
3049            "Index type does not match StartValue type");
3050     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3051       return B.CreateSub(StartValue, Index);
3052     auto *Offset = CreateMul(
3053         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3054     return CreateAdd(StartValue, Offset);
3055   }
3056   case InductionDescriptor::IK_PtrInduction: {
3057     assert(isa<SCEVConstant>(Step) &&
3058            "Expected constant step for pointer induction");
3059     return B.CreateGEP(
3060         StartValue->getType()->getPointerElementType(), StartValue,
3061         CreateMul(Index,
3062                   Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint())));
3063   }
3064   case InductionDescriptor::IK_FpInduction: {
3065     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3066     auto InductionBinOp = ID.getInductionBinOp();
3067     assert(InductionBinOp &&
3068            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3069             InductionBinOp->getOpcode() == Instruction::FSub) &&
3070            "Original bin op should be defined for FP induction");
3071 
3072     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3073 
3074     // Floating point operations had to be 'fast' to enable the induction.
3075     FastMathFlags Flags;
3076     Flags.setFast();
3077 
3078     Value *MulExp = B.CreateFMul(StepValue, Index);
3079     if (isa<Instruction>(MulExp))
3080       // We have to check, the MulExp may be a constant.
3081       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
3082 
3083     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3084                                "induction");
3085     if (isa<Instruction>(BOp))
3086       cast<Instruction>(BOp)->setFastMathFlags(Flags);
3087 
3088     return BOp;
3089   }
3090   case InductionDescriptor::IK_NoInduction:
3091     return nullptr;
3092   }
3093   llvm_unreachable("invalid enum");
3094 }
3095 
3096 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3097   LoopScalarBody = OrigLoop->getHeader();
3098   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3099   LoopExitBlock = OrigLoop->getExitBlock();
3100   assert(LoopExitBlock && "Must have an exit block");
3101   assert(LoopVectorPreHeader && "Invalid loop structure");
3102 
3103   LoopMiddleBlock =
3104       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3105                  LI, nullptr, Twine(Prefix) + "middle.block");
3106   LoopScalarPreHeader =
3107       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3108                  nullptr, Twine(Prefix) + "scalar.ph");
3109   // We intentionally don't let SplitBlock to update LoopInfo since
3110   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3111   // LoopVectorBody is explicitly added to the correct place few lines later.
3112   LoopVectorBody =
3113       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3114                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3115 
3116   // Update dominator for loop exit.
3117   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3118 
3119   // Create and register the new vector loop.
3120   Loop *Lp = LI->AllocateLoop();
3121   Loop *ParentLoop = OrigLoop->getParentLoop();
3122 
3123   // Insert the new loop into the loop nest and register the new basic blocks
3124   // before calling any utilities such as SCEV that require valid LoopInfo.
3125   if (ParentLoop) {
3126     ParentLoop->addChildLoop(Lp);
3127   } else {
3128     LI->addTopLevelLoop(Lp);
3129   }
3130   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3131   return Lp;
3132 }
3133 
3134 void InnerLoopVectorizer::createInductionResumeValues(Loop *L,
3135                                                       Value *VectorTripCount) {
3136   assert(VectorTripCount && L && "Expected valid arguments");
3137   // We are going to resume the execution of the scalar loop.
3138   // Go over all of the induction variables that we found and fix the
3139   // PHIs that are left in the scalar version of the loop.
3140   // The starting values of PHI nodes depend on the counter of the last
3141   // iteration in the vectorized loop.
3142   // If we come from a bypass edge then we need to start from the original
3143   // start value.
3144   for (auto &InductionEntry : Legal->getInductionVars()) {
3145     PHINode *OrigPhi = InductionEntry.first;
3146     InductionDescriptor II = InductionEntry.second;
3147 
3148     // Create phi nodes to merge from the  backedge-taken check block.
3149     PHINode *BCResumeVal =
3150         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3151                         LoopScalarPreHeader->getTerminator());
3152     // Copy original phi DL over to the new one.
3153     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3154     Value *&EndValue = IVEndValues[OrigPhi];
3155     if (OrigPhi == OldInduction) {
3156       // We know what the end value is.
3157       EndValue = VectorTripCount;
3158     } else {
3159       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3160       Type *StepType = II.getStep()->getType();
3161       Instruction::CastOps CastOp =
3162           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3163       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3164       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3165       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3166       EndValue->setName("ind.end");
3167     }
3168 
3169     // The new PHI merges the original incoming value, in case of a bypass,
3170     // or the value at the end of the vectorized loop.
3171     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3172 
3173     // Fix the scalar body counter (PHI node).
3174     // The old induction's phi node in the scalar body needs the truncated
3175     // value.
3176     for (BasicBlock *BB : LoopBypassBlocks)
3177       BCResumeVal->addIncoming(II.getStartValue(), BB);
3178     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3179   }
3180 }
3181 
3182 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3183                                                       MDNode *OrigLoopID) {
3184   assert(L && "Expected valid loop.");
3185 
3186   // The trip counts should be cached by now.
3187   Value *Count = getOrCreateTripCount(L);
3188   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3189 
3190   // We need the OrigLoop (scalar loop part) latch terminator to help
3191   // produce correct debug info for the middle block BB instructions.
3192   // The legality check stage guarantees that the loop will have a single
3193   // latch.
3194   assert(isa<BranchInst>(OrigLoop->getLoopLatch()->getTerminator()) &&
3195          "Scalar loop latch terminator isn't a branch");
3196   BranchInst *ScalarLatchBr =
3197       cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator());
3198 
3199   // Add a check in the middle block to see if we have completed
3200   // all of the iterations in the first vector loop.
3201   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3202   // If tail is to be folded, we know we don't need to run the remainder.
3203   Value *CmpN = Builder.getTrue();
3204   if (!Cost->foldTailByMasking()) {
3205     CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3206                            VectorTripCount, "cmp.n",
3207                            LoopMiddleBlock->getTerminator());
3208 
3209     // Here we use the same DebugLoc as the scalar loop latch branch instead
3210     // of the corresponding compare because they may have ended up with
3211     // different line numbers and we want to avoid awkward line stepping while
3212     // debugging. Eg. if the compare has got a line number inside the loop.
3213     cast<Instruction>(CmpN)->setDebugLoc(ScalarLatchBr->getDebugLoc());
3214   }
3215 
3216   BranchInst *BrInst =
3217       BranchInst::Create(LoopExitBlock, LoopScalarPreHeader, CmpN);
3218   BrInst->setDebugLoc(ScalarLatchBr->getDebugLoc());
3219   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3220 
3221   // Get ready to start creating new instructions into the vectorized body.
3222   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3223          "Inconsistent vector loop preheader");
3224   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3225 
3226   Optional<MDNode *> VectorizedLoopID =
3227       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3228                                       LLVMLoopVectorizeFollowupVectorized});
3229   if (VectorizedLoopID.hasValue()) {
3230     L->setLoopID(VectorizedLoopID.getValue());
3231 
3232     // Do not setAlreadyVectorized if loop attributes have been defined
3233     // explicitly.
3234     return LoopVectorPreHeader;
3235   }
3236 
3237   // Keep all loop hints from the original loop on the vector loop (we'll
3238   // replace the vectorizer-specific hints below).
3239   if (MDNode *LID = OrigLoop->getLoopID())
3240     L->setLoopID(LID);
3241 
3242   LoopVectorizeHints Hints(L, true, *ORE);
3243   Hints.setAlreadyVectorized();
3244 
3245 #ifdef EXPENSIVE_CHECKS
3246   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3247   LI->verify(*DT);
3248 #endif
3249 
3250   return LoopVectorPreHeader;
3251 }
3252 
3253 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3254   /*
3255    In this function we generate a new loop. The new loop will contain
3256    the vectorized instructions while the old loop will continue to run the
3257    scalar remainder.
3258 
3259        [ ] <-- loop iteration number check.
3260     /   |
3261    /    v
3262   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3263   |  /  |
3264   | /   v
3265   ||   [ ]     <-- vector pre header.
3266   |/    |
3267   |     v
3268   |    [  ] \
3269   |    [  ]_|   <-- vector loop.
3270   |     |
3271   |     v
3272   |   -[ ]   <--- middle-block.
3273   |  /  |
3274   | /   v
3275   -|- >[ ]     <--- new preheader.
3276    |    |
3277    |    v
3278    |   [ ] \
3279    |   [ ]_|   <-- old scalar loop to handle remainder.
3280     \   |
3281      \  v
3282       >[ ]     <-- exit block.
3283    ...
3284    */
3285 
3286   // Get the metadata of the original loop before it gets modified.
3287   MDNode *OrigLoopID = OrigLoop->getLoopID();
3288 
3289   // Create an empty vector loop, and prepare basic blocks for the runtime
3290   // checks.
3291   Loop *Lp = createVectorLoopSkeleton("");
3292 
3293   // Now, compare the new count to zero. If it is zero skip the vector loop and
3294   // jump to the scalar loop. This check also covers the case where the
3295   // backedge-taken count is uint##_max: adding one to it will overflow leading
3296   // to an incorrect trip count of zero. In this (rare) case we will also jump
3297   // to the scalar loop.
3298   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3299 
3300   // Generate the code to check any assumptions that we've made for SCEV
3301   // expressions.
3302   emitSCEVChecks(Lp, LoopScalarPreHeader);
3303 
3304   // Generate the code that checks in runtime if arrays overlap. We put the
3305   // checks into a separate block to make the more common case of few elements
3306   // faster.
3307   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3308 
3309   // Some loops have a single integer induction variable, while other loops
3310   // don't. One example is c++ iterators that often have multiple pointer
3311   // induction variables. In the code below we also support a case where we
3312   // don't have a single induction variable.
3313   //
3314   // We try to obtain an induction variable from the original loop as hard
3315   // as possible. However if we don't find one that:
3316   //   - is an integer
3317   //   - counts from zero, stepping by one
3318   //   - is the size of the widest induction variable type
3319   // then we create a new one.
3320   OldInduction = Legal->getPrimaryInduction();
3321   Type *IdxTy = Legal->getWidestInductionType();
3322   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3323   // The loop step is equal to the vectorization factor (num of SIMD elements)
3324   // times the unroll factor (num of SIMD instructions).
3325   assert(!VF.isScalable() && "scalable vectors not yet supported.");
3326   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
3327   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3328   Induction =
3329       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3330                               getDebugLocFromInstOrOperands(OldInduction));
3331 
3332   // Emit phis for the new starting index of the scalar loop.
3333   createInductionResumeValues(Lp, CountRoundDown);
3334 
3335   return completeLoopSkeleton(Lp, OrigLoopID);
3336 }
3337 
3338 // Fix up external users of the induction variable. At this point, we are
3339 // in LCSSA form, with all external PHIs that use the IV having one input value,
3340 // coming from the remainder loop. We need those PHIs to also have a correct
3341 // value for the IV when arriving directly from the middle block.
3342 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3343                                        const InductionDescriptor &II,
3344                                        Value *CountRoundDown, Value *EndValue,
3345                                        BasicBlock *MiddleBlock) {
3346   // There are two kinds of external IV usages - those that use the value
3347   // computed in the last iteration (the PHI) and those that use the penultimate
3348   // value (the value that feeds into the phi from the loop latch).
3349   // We allow both, but they, obviously, have different values.
3350 
3351   assert(OrigLoop->getExitBlock() && "Expected a single exit block");
3352 
3353   DenseMap<Value *, Value *> MissingVals;
3354 
3355   // An external user of the last iteration's value should see the value that
3356   // the remainder loop uses to initialize its own IV.
3357   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3358   for (User *U : PostInc->users()) {
3359     Instruction *UI = cast<Instruction>(U);
3360     if (!OrigLoop->contains(UI)) {
3361       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3362       MissingVals[UI] = EndValue;
3363     }
3364   }
3365 
3366   // An external user of the penultimate value need to see EndValue - Step.
3367   // The simplest way to get this is to recompute it from the constituent SCEVs,
3368   // that is Start + (Step * (CRD - 1)).
3369   for (User *U : OrigPhi->users()) {
3370     auto *UI = cast<Instruction>(U);
3371     if (!OrigLoop->contains(UI)) {
3372       const DataLayout &DL =
3373           OrigLoop->getHeader()->getModule()->getDataLayout();
3374       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3375 
3376       IRBuilder<> B(MiddleBlock->getTerminator());
3377       Value *CountMinusOne = B.CreateSub(
3378           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3379       Value *CMO =
3380           !II.getStep()->getType()->isIntegerTy()
3381               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3382                              II.getStep()->getType())
3383               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3384       CMO->setName("cast.cmo");
3385       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3386       Escape->setName("ind.escape");
3387       MissingVals[UI] = Escape;
3388     }
3389   }
3390 
3391   for (auto &I : MissingVals) {
3392     PHINode *PHI = cast<PHINode>(I.first);
3393     // One corner case we have to handle is two IVs "chasing" each-other,
3394     // that is %IV2 = phi [...], [ %IV1, %latch ]
3395     // In this case, if IV1 has an external use, we need to avoid adding both
3396     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3397     // don't already have an incoming value for the middle block.
3398     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3399       PHI->addIncoming(I.second, MiddleBlock);
3400   }
3401 }
3402 
3403 namespace {
3404 
3405 struct CSEDenseMapInfo {
3406   static bool canHandle(const Instruction *I) {
3407     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3408            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3409   }
3410 
3411   static inline Instruction *getEmptyKey() {
3412     return DenseMapInfo<Instruction *>::getEmptyKey();
3413   }
3414 
3415   static inline Instruction *getTombstoneKey() {
3416     return DenseMapInfo<Instruction *>::getTombstoneKey();
3417   }
3418 
3419   static unsigned getHashValue(const Instruction *I) {
3420     assert(canHandle(I) && "Unknown instruction!");
3421     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3422                                                            I->value_op_end()));
3423   }
3424 
3425   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3426     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3427         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3428       return LHS == RHS;
3429     return LHS->isIdenticalTo(RHS);
3430   }
3431 };
3432 
3433 } // end anonymous namespace
3434 
3435 ///Perform cse of induction variable instructions.
3436 static void cse(BasicBlock *BB) {
3437   // Perform simple cse.
3438   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3439   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3440     Instruction *In = &*I++;
3441 
3442     if (!CSEDenseMapInfo::canHandle(In))
3443       continue;
3444 
3445     // Check if we can replace this instruction with any of the
3446     // visited instructions.
3447     if (Instruction *V = CSEMap.lookup(In)) {
3448       In->replaceAllUsesWith(V);
3449       In->eraseFromParent();
3450       continue;
3451     }
3452 
3453     CSEMap[In] = In;
3454   }
3455 }
3456 
3457 unsigned LoopVectorizationCostModel::getVectorCallCost(CallInst *CI,
3458                                                        ElementCount VF,
3459                                                        bool &NeedToScalarize) {
3460   assert(!VF.isScalable() && "scalable vectors not yet supported.");
3461   Function *F = CI->getCalledFunction();
3462   Type *ScalarRetTy = CI->getType();
3463   SmallVector<Type *, 4> Tys, ScalarTys;
3464   for (auto &ArgOp : CI->arg_operands())
3465     ScalarTys.push_back(ArgOp->getType());
3466 
3467   // Estimate cost of scalarized vector call. The source operands are assumed
3468   // to be vectors, so we need to extract individual elements from there,
3469   // execute VF scalar calls, and then gather the result into the vector return
3470   // value.
3471   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys,
3472                                                  TTI::TCK_RecipThroughput);
3473   if (VF.isScalar())
3474     return ScalarCallCost;
3475 
3476   // Compute corresponding vector type for return value and arguments.
3477   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3478   for (Type *ScalarTy : ScalarTys)
3479     Tys.push_back(ToVectorTy(ScalarTy, VF));
3480 
3481   // Compute costs of unpacking argument values for the scalar calls and
3482   // packing the return values to a vector.
3483   unsigned ScalarizationCost = getScalarizationOverhead(CI, VF);
3484 
3485   unsigned Cost = ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3486 
3487   // If we can't emit a vector call for this function, then the currently found
3488   // cost is the cost we need to return.
3489   NeedToScalarize = true;
3490   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3491   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3492 
3493   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3494     return Cost;
3495 
3496   // If the corresponding vector cost is cheaper, return its cost.
3497   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys,
3498                                                  TTI::TCK_RecipThroughput);
3499   if (VectorCallCost < Cost) {
3500     NeedToScalarize = false;
3501     return VectorCallCost;
3502   }
3503   return Cost;
3504 }
3505 
3506 unsigned LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3507                                                             ElementCount VF) {
3508   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3509   assert(ID && "Expected intrinsic call!");
3510 
3511   IntrinsicCostAttributes CostAttrs(ID, *CI, VF);
3512   return TTI.getIntrinsicInstrCost(CostAttrs,
3513                                    TargetTransformInfo::TCK_RecipThroughput);
3514 }
3515 
3516 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3517   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3518   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3519   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3520 }
3521 
3522 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3523   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3524   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3525   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3526 }
3527 
3528 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3529   // For every instruction `I` in MinBWs, truncate the operands, create a
3530   // truncated version of `I` and reextend its result. InstCombine runs
3531   // later and will remove any ext/trunc pairs.
3532   SmallPtrSet<Value *, 4> Erased;
3533   for (const auto &KV : Cost->getMinimalBitwidths()) {
3534     // If the value wasn't vectorized, we must maintain the original scalar
3535     // type. The absence of the value from VectorLoopValueMap indicates that it
3536     // wasn't vectorized.
3537     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3538       continue;
3539     for (unsigned Part = 0; Part < UF; ++Part) {
3540       Value *I = getOrCreateVectorValue(KV.first, Part);
3541       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3542         continue;
3543       Type *OriginalTy = I->getType();
3544       Type *ScalarTruncatedTy =
3545           IntegerType::get(OriginalTy->getContext(), KV.second);
3546       auto *TruncatedTy = FixedVectorType::get(
3547           ScalarTruncatedTy,
3548           cast<FixedVectorType>(OriginalTy)->getNumElements());
3549       if (TruncatedTy == OriginalTy)
3550         continue;
3551 
3552       IRBuilder<> B(cast<Instruction>(I));
3553       auto ShrinkOperand = [&](Value *V) -> Value * {
3554         if (auto *ZI = dyn_cast<ZExtInst>(V))
3555           if (ZI->getSrcTy() == TruncatedTy)
3556             return ZI->getOperand(0);
3557         return B.CreateZExtOrTrunc(V, TruncatedTy);
3558       };
3559 
3560       // The actual instruction modification depends on the instruction type,
3561       // unfortunately.
3562       Value *NewI = nullptr;
3563       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3564         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3565                              ShrinkOperand(BO->getOperand(1)));
3566 
3567         // Any wrapping introduced by shrinking this operation shouldn't be
3568         // considered undefined behavior. So, we can't unconditionally copy
3569         // arithmetic wrapping flags to NewI.
3570         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3571       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3572         NewI =
3573             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3574                          ShrinkOperand(CI->getOperand(1)));
3575       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3576         NewI = B.CreateSelect(SI->getCondition(),
3577                               ShrinkOperand(SI->getTrueValue()),
3578                               ShrinkOperand(SI->getFalseValue()));
3579       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3580         switch (CI->getOpcode()) {
3581         default:
3582           llvm_unreachable("Unhandled cast!");
3583         case Instruction::Trunc:
3584           NewI = ShrinkOperand(CI->getOperand(0));
3585           break;
3586         case Instruction::SExt:
3587           NewI = B.CreateSExtOrTrunc(
3588               CI->getOperand(0),
3589               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3590           break;
3591         case Instruction::ZExt:
3592           NewI = B.CreateZExtOrTrunc(
3593               CI->getOperand(0),
3594               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3595           break;
3596         }
3597       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3598         auto Elements0 = cast<FixedVectorType>(SI->getOperand(0)->getType())
3599                              ->getNumElements();
3600         auto *O0 = B.CreateZExtOrTrunc(
3601             SI->getOperand(0),
3602             FixedVectorType::get(ScalarTruncatedTy, Elements0));
3603         auto Elements1 = cast<FixedVectorType>(SI->getOperand(1)->getType())
3604                              ->getNumElements();
3605         auto *O1 = B.CreateZExtOrTrunc(
3606             SI->getOperand(1),
3607             FixedVectorType::get(ScalarTruncatedTy, Elements1));
3608 
3609         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3610       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3611         // Don't do anything with the operands, just extend the result.
3612         continue;
3613       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3614         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
3615                             ->getNumElements();
3616         auto *O0 = B.CreateZExtOrTrunc(
3617             IE->getOperand(0),
3618             FixedVectorType::get(ScalarTruncatedTy, Elements));
3619         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3620         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3621       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3622         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
3623                             ->getNumElements();
3624         auto *O0 = B.CreateZExtOrTrunc(
3625             EE->getOperand(0),
3626             FixedVectorType::get(ScalarTruncatedTy, Elements));
3627         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3628       } else {
3629         // If we don't know what to do, be conservative and don't do anything.
3630         continue;
3631       }
3632 
3633       // Lastly, extend the result.
3634       NewI->takeName(cast<Instruction>(I));
3635       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3636       I->replaceAllUsesWith(Res);
3637       cast<Instruction>(I)->eraseFromParent();
3638       Erased.insert(I);
3639       VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3640     }
3641   }
3642 
3643   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3644   for (const auto &KV : Cost->getMinimalBitwidths()) {
3645     // If the value wasn't vectorized, we must maintain the original scalar
3646     // type. The absence of the value from VectorLoopValueMap indicates that it
3647     // wasn't vectorized.
3648     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3649       continue;
3650     for (unsigned Part = 0; Part < UF; ++Part) {
3651       Value *I = getOrCreateVectorValue(KV.first, Part);
3652       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3653       if (Inst && Inst->use_empty()) {
3654         Value *NewI = Inst->getOperand(0);
3655         Inst->eraseFromParent();
3656         VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3657       }
3658     }
3659   }
3660 }
3661 
3662 void InnerLoopVectorizer::fixVectorizedLoop() {
3663   // Insert truncates and extends for any truncated instructions as hints to
3664   // InstCombine.
3665   if (VF.isVector())
3666     truncateToMinimalBitwidths();
3667 
3668   // Fix widened non-induction PHIs by setting up the PHI operands.
3669   if (OrigPHIsToFix.size()) {
3670     assert(EnableVPlanNativePath &&
3671            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
3672     fixNonInductionPHIs();
3673   }
3674 
3675   // At this point every instruction in the original loop is widened to a
3676   // vector form. Now we need to fix the recurrences in the loop. These PHI
3677   // nodes are currently empty because we did not want to introduce cycles.
3678   // This is the second stage of vectorizing recurrences.
3679   fixCrossIterationPHIs();
3680 
3681   // Forget the original basic block.
3682   PSE.getSE()->forgetLoop(OrigLoop);
3683 
3684   // Fix-up external users of the induction variables.
3685   for (auto &Entry : Legal->getInductionVars())
3686     fixupIVUsers(Entry.first, Entry.second,
3687                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3688                  IVEndValues[Entry.first], LoopMiddleBlock);
3689 
3690   fixLCSSAPHIs();
3691   for (Instruction *PI : PredicatedInstructions)
3692     sinkScalarOperands(&*PI);
3693 
3694   // Remove redundant induction instructions.
3695   cse(LoopVectorBody);
3696 
3697   // Set/update profile weights for the vector and remainder loops as original
3698   // loop iterations are now distributed among them. Note that original loop
3699   // represented by LoopScalarBody becomes remainder loop after vectorization.
3700   //
3701   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3702   // end up getting slightly roughened result but that should be OK since
3703   // profile is not inherently precise anyway. Note also possible bypass of
3704   // vector code caused by legality checks is ignored, assigning all the weight
3705   // to the vector loop, optimistically.
3706   assert(!VF.isScalable() &&
3707          "cannot use scalable ElementCount to determine unroll factor");
3708   setProfileInfoAfterUnrolling(
3709       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
3710       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
3711 }
3712 
3713 void InnerLoopVectorizer::fixCrossIterationPHIs() {
3714   // In order to support recurrences we need to be able to vectorize Phi nodes.
3715   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3716   // stage #2: We now need to fix the recurrences by adding incoming edges to
3717   // the currently empty PHI nodes. At this point every instruction in the
3718   // original loop is widened to a vector form so we can use them to construct
3719   // the incoming edges.
3720   for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
3721     // Handle first-order recurrences and reductions that need to be fixed.
3722     if (Legal->isFirstOrderRecurrence(&Phi))
3723       fixFirstOrderRecurrence(&Phi);
3724     else if (Legal->isReductionVariable(&Phi))
3725       fixReduction(&Phi);
3726   }
3727 }
3728 
3729 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3730   // This is the second phase of vectorizing first-order recurrences. An
3731   // overview of the transformation is described below. Suppose we have the
3732   // following loop.
3733   //
3734   //   for (int i = 0; i < n; ++i)
3735   //     b[i] = a[i] - a[i - 1];
3736   //
3737   // There is a first-order recurrence on "a". For this loop, the shorthand
3738   // scalar IR looks like:
3739   //
3740   //   scalar.ph:
3741   //     s_init = a[-1]
3742   //     br scalar.body
3743   //
3744   //   scalar.body:
3745   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3746   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3747   //     s2 = a[i]
3748   //     b[i] = s2 - s1
3749   //     br cond, scalar.body, ...
3750   //
3751   // In this example, s1 is a recurrence because it's value depends on the
3752   // previous iteration. In the first phase of vectorization, we created a
3753   // temporary value for s1. We now complete the vectorization and produce the
3754   // shorthand vector IR shown below (for VF = 4, UF = 1).
3755   //
3756   //   vector.ph:
3757   //     v_init = vector(..., ..., ..., a[-1])
3758   //     br vector.body
3759   //
3760   //   vector.body
3761   //     i = phi [0, vector.ph], [i+4, vector.body]
3762   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3763   //     v2 = a[i, i+1, i+2, i+3];
3764   //     v3 = vector(v1(3), v2(0, 1, 2))
3765   //     b[i, i+1, i+2, i+3] = v2 - v3
3766   //     br cond, vector.body, middle.block
3767   //
3768   //   middle.block:
3769   //     x = v2(3)
3770   //     br scalar.ph
3771   //
3772   //   scalar.ph:
3773   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3774   //     br scalar.body
3775   //
3776   // After execution completes the vector loop, we extract the next value of
3777   // the recurrence (x) to use as the initial value in the scalar loop.
3778 
3779   // Get the original loop preheader and single loop latch.
3780   auto *Preheader = OrigLoop->getLoopPreheader();
3781   auto *Latch = OrigLoop->getLoopLatch();
3782 
3783   // Get the initial and previous values of the scalar recurrence.
3784   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
3785   auto *Previous = Phi->getIncomingValueForBlock(Latch);
3786 
3787   // Create a vector from the initial value.
3788   auto *VectorInit = ScalarInit;
3789   if (VF.isVector()) {
3790     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3791     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
3792     VectorInit = Builder.CreateInsertElement(
3793         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
3794         Builder.getInt32(VF.getKnownMinValue() - 1), "vector.recur.init");
3795   }
3796 
3797   // We constructed a temporary phi node in the first phase of vectorization.
3798   // This phi node will eventually be deleted.
3799   Builder.SetInsertPoint(
3800       cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
3801 
3802   // Create a phi node for the new recurrence. The current value will either be
3803   // the initial value inserted into a vector or loop-varying vector value.
3804   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
3805   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
3806 
3807   // Get the vectorized previous value of the last part UF - 1. It appears last
3808   // among all unrolled iterations, due to the order of their construction.
3809   Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
3810 
3811   // Find and set the insertion point after the previous value if it is an
3812   // instruction.
3813   BasicBlock::iterator InsertPt;
3814   // Note that the previous value may have been constant-folded so it is not
3815   // guaranteed to be an instruction in the vector loop.
3816   // FIXME: Loop invariant values do not form recurrences. We should deal with
3817   //        them earlier.
3818   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
3819     InsertPt = LoopVectorBody->getFirstInsertionPt();
3820   else {
3821     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
3822     if (isa<PHINode>(PreviousLastPart))
3823       // If the previous value is a phi node, we should insert after all the phi
3824       // nodes in the block containing the PHI to avoid breaking basic block
3825       // verification. Note that the basic block may be different to
3826       // LoopVectorBody, in case we predicate the loop.
3827       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
3828     else
3829       InsertPt = ++PreviousInst->getIterator();
3830   }
3831   Builder.SetInsertPoint(&*InsertPt);
3832 
3833   // We will construct a vector for the recurrence by combining the values for
3834   // the current and previous iterations. This is the required shuffle mask.
3835   assert(!VF.isScalable());
3836   SmallVector<int, 8> ShuffleMask(VF.getKnownMinValue());
3837   ShuffleMask[0] = VF.getKnownMinValue() - 1;
3838   for (unsigned I = 1; I < VF.getKnownMinValue(); ++I)
3839     ShuffleMask[I] = I + VF.getKnownMinValue() - 1;
3840 
3841   // The vector from which to take the initial value for the current iteration
3842   // (actual or unrolled). Initially, this is the vector phi node.
3843   Value *Incoming = VecPhi;
3844 
3845   // Shuffle the current and previous vector and update the vector parts.
3846   for (unsigned Part = 0; Part < UF; ++Part) {
3847     Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
3848     Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
3849     auto *Shuffle =
3850         VF.isVector()
3851             ? Builder.CreateShuffleVector(Incoming, PreviousPart, ShuffleMask)
3852             : Incoming;
3853     PhiPart->replaceAllUsesWith(Shuffle);
3854     cast<Instruction>(PhiPart)->eraseFromParent();
3855     VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
3856     Incoming = PreviousPart;
3857   }
3858 
3859   // Fix the latch value of the new recurrence in the vector loop.
3860   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3861 
3862   // Extract the last vector element in the middle block. This will be the
3863   // initial value for the recurrence when jumping to the scalar loop.
3864   auto *ExtractForScalar = Incoming;
3865   if (VF.isVector()) {
3866     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3867     ExtractForScalar = Builder.CreateExtractElement(
3868         ExtractForScalar, Builder.getInt32(VF.getKnownMinValue() - 1),
3869         "vector.recur.extract");
3870   }
3871   // Extract the second last element in the middle block if the
3872   // Phi is used outside the loop. We need to extract the phi itself
3873   // and not the last element (the phi update in the current iteration). This
3874   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3875   // when the scalar loop is not run at all.
3876   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3877   if (VF.isVector())
3878     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3879         Incoming, Builder.getInt32(VF.getKnownMinValue() - 2),
3880         "vector.recur.extract.for.phi");
3881   // When loop is unrolled without vectorizing, initialize
3882   // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
3883   // `Incoming`. This is analogous to the vectorized case above: extracting the
3884   // second last element when VF > 1.
3885   else if (UF > 1)
3886     ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
3887 
3888   // Fix the initial value of the original recurrence in the scalar loop.
3889   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3890   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3891   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3892     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3893     Start->addIncoming(Incoming, BB);
3894   }
3895 
3896   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3897   Phi->setName("scalar.recur");
3898 
3899   // Finally, fix users of the recurrence outside the loop. The users will need
3900   // either the last value of the scalar recurrence or the last value of the
3901   // vector recurrence we extracted in the middle block. Since the loop is in
3902   // LCSSA form, we just need to find all the phi nodes for the original scalar
3903   // recurrence in the exit block, and then add an edge for the middle block.
3904   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
3905     if (LCSSAPhi.getIncomingValue(0) == Phi) {
3906       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3907     }
3908   }
3909 }
3910 
3911 void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
3912   Constant *Zero = Builder.getInt32(0);
3913 
3914   // Get it's reduction variable descriptor.
3915   assert(Legal->isReductionVariable(Phi) &&
3916          "Unable to find the reduction variable");
3917   RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[Phi];
3918 
3919   RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
3920   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3921   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3922   RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
3923     RdxDesc.getMinMaxRecurrenceKind();
3924   setDebugLocFromInst(Builder, ReductionStartValue);
3925   bool IsInLoopReductionPhi = Cost->isInLoopReduction(Phi);
3926 
3927   // We need to generate a reduction vector from the incoming scalar.
3928   // To do so, we need to generate the 'identity' vector and override
3929   // one of the elements with the incoming scalar reduction. We need
3930   // to do it in the vector-loop preheader.
3931   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
3932 
3933   // This is the vector-clone of the value that leaves the loop.
3934   Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
3935 
3936   // Find the reduction identity variable. Zero for addition, or, xor,
3937   // one for multiplication, -1 for And.
3938   Value *Identity;
3939   Value *VectorStart;
3940   if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
3941       RK == RecurrenceDescriptor::RK_FloatMinMax) {
3942     // MinMax reduction have the start value as their identify.
3943     if (VF.isScalar() || IsInLoopReductionPhi) {
3944       VectorStart = Identity = ReductionStartValue;
3945     } else {
3946       VectorStart = Identity =
3947         Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
3948     }
3949   } else {
3950     // Handle other reduction kinds:
3951     Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
3952         RK, MinMaxKind, VecTy->getScalarType());
3953     if (VF.isScalar() || IsInLoopReductionPhi) {
3954       Identity = Iden;
3955       // This vector is the Identity vector where the first element is the
3956       // incoming scalar reduction.
3957       VectorStart = ReductionStartValue;
3958     } else {
3959       Identity = ConstantVector::getSplat(VF, Iden);
3960 
3961       // This vector is the Identity vector where the first element is the
3962       // incoming scalar reduction.
3963       VectorStart =
3964         Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
3965     }
3966   }
3967 
3968   // Wrap flags are in general invalid after vectorization, clear them.
3969   clearReductionWrapFlags(RdxDesc);
3970 
3971   // Fix the vector-loop phi.
3972 
3973   // Reductions do not have to start at zero. They can start with
3974   // any loop invariant values.
3975   BasicBlock *Latch = OrigLoop->getLoopLatch();
3976   Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
3977 
3978   for (unsigned Part = 0; Part < UF; ++Part) {
3979     Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
3980     Value *Val = getOrCreateVectorValue(LoopVal, Part);
3981     // Make sure to add the reduction start value only to the
3982     // first unroll part.
3983     Value *StartVal = (Part == 0) ? VectorStart : Identity;
3984     cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
3985     cast<PHINode>(VecRdxPhi)
3986       ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
3987   }
3988 
3989   // Before each round, move the insertion point right between
3990   // the PHIs and the values we are going to write.
3991   // This allows us to write both PHINodes and the extractelement
3992   // instructions.
3993   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3994 
3995   setDebugLocFromInst(Builder, LoopExitInst);
3996 
3997   // If tail is folded by masking, the vector value to leave the loop should be
3998   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3999   // instead of the former. For an inloop reduction the reduction will already
4000   // be predicated, and does not need to be handled here.
4001   if (Cost->foldTailByMasking() && !IsInLoopReductionPhi) {
4002     for (unsigned Part = 0; Part < UF; ++Part) {
4003       Value *VecLoopExitInst =
4004           VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4005       Value *Sel = nullptr;
4006       for (User *U : VecLoopExitInst->users()) {
4007         if (isa<SelectInst>(U)) {
4008           assert(!Sel && "Reduction exit feeding two selects");
4009           Sel = U;
4010         } else
4011           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4012       }
4013       assert(Sel && "Reduction exit feeds no select");
4014       VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, Sel);
4015 
4016       // If the target can create a predicated operator for the reduction at no
4017       // extra cost in the loop (for example a predicated vadd), it can be
4018       // cheaper for the select to remain in the loop than be sunk out of it,
4019       // and so use the select value for the phi instead of the old
4020       // LoopExitValue.
4021       RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[Phi];
4022       if (PreferPredicatedReductionSelect ||
4023           TTI->preferPredicatedReductionSelect(
4024               RdxDesc.getRecurrenceBinOp(), Phi->getType(),
4025               TargetTransformInfo::ReductionFlags())) {
4026         auto *VecRdxPhi = cast<PHINode>(getOrCreateVectorValue(Phi, Part));
4027         VecRdxPhi->setIncomingValueForBlock(
4028             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4029       }
4030     }
4031   }
4032 
4033   // If the vector reduction can be performed in a smaller type, we truncate
4034   // then extend the loop exit value to enable InstCombine to evaluate the
4035   // entire expression in the smaller type.
4036   if (VF.isVector() && Phi->getType() != RdxDesc.getRecurrenceType()) {
4037     assert(!IsInLoopReductionPhi && "Unexpected truncated inloop reduction!");
4038     assert(!VF.isScalable() && "scalable vectors not yet supported.");
4039     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4040     Builder.SetInsertPoint(
4041         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4042     VectorParts RdxParts(UF);
4043     for (unsigned Part = 0; Part < UF; ++Part) {
4044       RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4045       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4046       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4047                                         : Builder.CreateZExt(Trunc, VecTy);
4048       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4049            UI != RdxParts[Part]->user_end();)
4050         if (*UI != Trunc) {
4051           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4052           RdxParts[Part] = Extnd;
4053         } else {
4054           ++UI;
4055         }
4056     }
4057     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4058     for (unsigned Part = 0; Part < UF; ++Part) {
4059       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4060       VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
4061     }
4062   }
4063 
4064   // Reduce all of the unrolled parts into a single vector.
4065   Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
4066   unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
4067 
4068   // The middle block terminator has already been assigned a DebugLoc here (the
4069   // OrigLoop's single latch terminator). We want the whole middle block to
4070   // appear to execute on this line because: (a) it is all compiler generated,
4071   // (b) these instructions are always executed after evaluating the latch
4072   // conditional branch, and (c) other passes may add new predecessors which
4073   // terminate on this line. This is the easiest way to ensure we don't
4074   // accidentally cause an extra step back into the loop while debugging.
4075   setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
4076   for (unsigned Part = 1; Part < UF; ++Part) {
4077     Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
4078     if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4079       // Floating point operations had to be 'fast' to enable the reduction.
4080       ReducedPartRdx = addFastMathFlag(
4081           Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
4082                               ReducedPartRdx, "bin.rdx"),
4083           RdxDesc.getFastMathFlags());
4084     else
4085       ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
4086                                       RdxPart);
4087   }
4088 
4089   // Create the reduction after the loop. Note that inloop reductions create the
4090   // target reduction in the loop using a Reduction recipe.
4091   if (VF.isVector() && !IsInLoopReductionPhi) {
4092     bool NoNaN = Legal->hasFunNoNaNAttr();
4093     ReducedPartRdx =
4094         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
4095     // If the reduction can be performed in a smaller type, we need to extend
4096     // the reduction to the wider type before we branch to the original loop.
4097     if (Phi->getType() != RdxDesc.getRecurrenceType())
4098       ReducedPartRdx =
4099         RdxDesc.isSigned()
4100         ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4101         : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4102   }
4103 
4104   // Create a phi node that merges control-flow from the backedge-taken check
4105   // block and the middle block.
4106   PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4107                                         LoopScalarPreHeader->getTerminator());
4108   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4109     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4110   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4111 
4112   // Now, we need to fix the users of the reduction variable
4113   // inside and outside of the scalar remainder loop.
4114   // We know that the loop is in LCSSA form. We need to update the
4115   // PHI nodes in the exit blocks.
4116   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4117     // All PHINodes need to have a single entry edge, or two if
4118     // we already fixed them.
4119     assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
4120 
4121     // We found a reduction value exit-PHI. Update it with the
4122     // incoming bypass edge.
4123     if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
4124       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4125   } // end of the LCSSA phi scan.
4126 
4127     // Fix the scalar loop reduction variable with the incoming reduction sum
4128     // from the vector body and from the backedge value.
4129   int IncomingEdgeBlockIdx =
4130     Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4131   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4132   // Pick the other block.
4133   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4134   Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4135   Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4136 }
4137 
4138 void InnerLoopVectorizer::clearReductionWrapFlags(
4139     RecurrenceDescriptor &RdxDesc) {
4140   RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
4141   if (RK != RecurrenceDescriptor::RK_IntegerAdd &&
4142       RK != RecurrenceDescriptor::RK_IntegerMult)
4143     return;
4144 
4145   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4146   assert(LoopExitInstr && "null loop exit instruction");
4147   SmallVector<Instruction *, 8> Worklist;
4148   SmallPtrSet<Instruction *, 8> Visited;
4149   Worklist.push_back(LoopExitInstr);
4150   Visited.insert(LoopExitInstr);
4151 
4152   while (!Worklist.empty()) {
4153     Instruction *Cur = Worklist.pop_back_val();
4154     if (isa<OverflowingBinaryOperator>(Cur))
4155       for (unsigned Part = 0; Part < UF; ++Part) {
4156         Value *V = getOrCreateVectorValue(Cur, Part);
4157         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4158       }
4159 
4160     for (User *U : Cur->users()) {
4161       Instruction *UI = cast<Instruction>(U);
4162       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4163           Visited.insert(UI).second)
4164         Worklist.push_back(UI);
4165     }
4166   }
4167 }
4168 
4169 void InnerLoopVectorizer::fixLCSSAPHIs() {
4170   assert(!VF.isScalable() && "the code below assumes fixed width vectors");
4171   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4172     if (LCSSAPhi.getNumIncomingValues() == 1) {
4173       auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4174       // Non-instruction incoming values will have only one value.
4175       unsigned LastLane = 0;
4176       if (isa<Instruction>(IncomingValue))
4177         LastLane = Cost->isUniformAfterVectorization(
4178                        cast<Instruction>(IncomingValue), VF)
4179                        ? 0
4180                        : VF.getKnownMinValue() - 1;
4181       // Can be a loop invariant incoming value or the last scalar value to be
4182       // extracted from the vectorized loop.
4183       Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4184       Value *lastIncomingValue =
4185           getOrCreateScalarValue(IncomingValue, { UF - 1, LastLane });
4186       LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4187     }
4188   }
4189 }
4190 
4191 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4192   // The basic block and loop containing the predicated instruction.
4193   auto *PredBB = PredInst->getParent();
4194   auto *VectorLoop = LI->getLoopFor(PredBB);
4195 
4196   // Initialize a worklist with the operands of the predicated instruction.
4197   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4198 
4199   // Holds instructions that we need to analyze again. An instruction may be
4200   // reanalyzed if we don't yet know if we can sink it or not.
4201   SmallVector<Instruction *, 8> InstsToReanalyze;
4202 
4203   // Returns true if a given use occurs in the predicated block. Phi nodes use
4204   // their operands in their corresponding predecessor blocks.
4205   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4206     auto *I = cast<Instruction>(U.getUser());
4207     BasicBlock *BB = I->getParent();
4208     if (auto *Phi = dyn_cast<PHINode>(I))
4209       BB = Phi->getIncomingBlock(
4210           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4211     return BB == PredBB;
4212   };
4213 
4214   // Iteratively sink the scalarized operands of the predicated instruction
4215   // into the block we created for it. When an instruction is sunk, it's
4216   // operands are then added to the worklist. The algorithm ends after one pass
4217   // through the worklist doesn't sink a single instruction.
4218   bool Changed;
4219   do {
4220     // Add the instructions that need to be reanalyzed to the worklist, and
4221     // reset the changed indicator.
4222     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4223     InstsToReanalyze.clear();
4224     Changed = false;
4225 
4226     while (!Worklist.empty()) {
4227       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4228 
4229       // We can't sink an instruction if it is a phi node, is already in the
4230       // predicated block, is not in the loop, or may have side effects.
4231       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4232           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4233         continue;
4234 
4235       // It's legal to sink the instruction if all its uses occur in the
4236       // predicated block. Otherwise, there's nothing to do yet, and we may
4237       // need to reanalyze the instruction.
4238       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4239         InstsToReanalyze.push_back(I);
4240         continue;
4241       }
4242 
4243       // Move the instruction to the beginning of the predicated block, and add
4244       // it's operands to the worklist.
4245       I->moveBefore(&*PredBB->getFirstInsertionPt());
4246       Worklist.insert(I->op_begin(), I->op_end());
4247 
4248       // The sinking may have enabled other instructions to be sunk, so we will
4249       // need to iterate.
4250       Changed = true;
4251     }
4252   } while (Changed);
4253 }
4254 
4255 void InnerLoopVectorizer::fixNonInductionPHIs() {
4256   for (PHINode *OrigPhi : OrigPHIsToFix) {
4257     PHINode *NewPhi =
4258         cast<PHINode>(VectorLoopValueMap.getVectorValue(OrigPhi, 0));
4259     unsigned NumIncomingValues = OrigPhi->getNumIncomingValues();
4260 
4261     SmallVector<BasicBlock *, 2> ScalarBBPredecessors(
4262         predecessors(OrigPhi->getParent()));
4263     SmallVector<BasicBlock *, 2> VectorBBPredecessors(
4264         predecessors(NewPhi->getParent()));
4265     assert(ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
4266            "Scalar and Vector BB should have the same number of predecessors");
4267 
4268     // The insertion point in Builder may be invalidated by the time we get
4269     // here. Force the Builder insertion point to something valid so that we do
4270     // not run into issues during insertion point restore in
4271     // getOrCreateVectorValue calls below.
4272     Builder.SetInsertPoint(NewPhi);
4273 
4274     // The predecessor order is preserved and we can rely on mapping between
4275     // scalar and vector block predecessors.
4276     for (unsigned i = 0; i < NumIncomingValues; ++i) {
4277       BasicBlock *NewPredBB = VectorBBPredecessors[i];
4278 
4279       // When looking up the new scalar/vector values to fix up, use incoming
4280       // values from original phi.
4281       Value *ScIncV =
4282           OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
4283 
4284       // Scalar incoming value may need a broadcast
4285       Value *NewIncV = getOrCreateVectorValue(ScIncV, 0);
4286       NewPhi->addIncoming(NewIncV, NewPredBB);
4287     }
4288   }
4289 }
4290 
4291 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPUser &Operands,
4292                                    unsigned UF, ElementCount VF,
4293                                    bool IsPtrLoopInvariant,
4294                                    SmallBitVector &IsIndexLoopInvariant,
4295                                    VPTransformState &State) {
4296   // Construct a vector GEP by widening the operands of the scalar GEP as
4297   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4298   // results in a vector of pointers when at least one operand of the GEP
4299   // is vector-typed. Thus, to keep the representation compact, we only use
4300   // vector-typed operands for loop-varying values.
4301 
4302   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4303     // If we are vectorizing, but the GEP has only loop-invariant operands,
4304     // the GEP we build (by only using vector-typed operands for
4305     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4306     // produce a vector of pointers, we need to either arbitrarily pick an
4307     // operand to broadcast, or broadcast a clone of the original GEP.
4308     // Here, we broadcast a clone of the original.
4309     //
4310     // TODO: If at some point we decide to scalarize instructions having
4311     //       loop-invariant operands, this special case will no longer be
4312     //       required. We would add the scalarization decision to
4313     //       collectLoopScalars() and teach getVectorValue() to broadcast
4314     //       the lane-zero scalar value.
4315     auto *Clone = Builder.Insert(GEP->clone());
4316     for (unsigned Part = 0; Part < UF; ++Part) {
4317       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4318       VectorLoopValueMap.setVectorValue(GEP, Part, EntryPart);
4319       addMetadata(EntryPart, GEP);
4320     }
4321   } else {
4322     // If the GEP has at least one loop-varying operand, we are sure to
4323     // produce a vector of pointers. But if we are only unrolling, we want
4324     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4325     // produce with the code below will be scalar (if VF == 1) or vector
4326     // (otherwise). Note that for the unroll-only case, we still maintain
4327     // values in the vector mapping with initVector, as we do for other
4328     // instructions.
4329     for (unsigned Part = 0; Part < UF; ++Part) {
4330       // The pointer operand of the new GEP. If it's loop-invariant, we
4331       // won't broadcast it.
4332       auto *Ptr = IsPtrLoopInvariant ? State.get(Operands.getOperand(0), {0, 0})
4333                                      : State.get(Operands.getOperand(0), Part);
4334 
4335       // Collect all the indices for the new GEP. If any index is
4336       // loop-invariant, we won't broadcast it.
4337       SmallVector<Value *, 4> Indices;
4338       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4339         VPValue *Operand = Operands.getOperand(I);
4340         if (IsIndexLoopInvariant[I - 1])
4341           Indices.push_back(State.get(Operand, {0, 0}));
4342         else
4343           Indices.push_back(State.get(Operand, Part));
4344       }
4345 
4346       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4347       // but it should be a vector, otherwise.
4348       auto *NewGEP =
4349           GEP->isInBounds()
4350               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4351                                           Indices)
4352               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4353       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4354              "NewGEP is not a pointer vector");
4355       VectorLoopValueMap.setVectorValue(GEP, Part, NewGEP);
4356       addMetadata(NewGEP, GEP);
4357     }
4358   }
4359 }
4360 
4361 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4362                                               ElementCount VF) {
4363   assert(!VF.isScalable() && "scalable vectors not yet supported.");
4364   PHINode *P = cast<PHINode>(PN);
4365   if (EnableVPlanNativePath) {
4366     // Currently we enter here in the VPlan-native path for non-induction
4367     // PHIs where all control flow is uniform. We simply widen these PHIs.
4368     // Create a vector phi with no operands - the vector phi operands will be
4369     // set at the end of vector code generation.
4370     Type *VecTy =
4371         (VF.isScalar()) ? PN->getType() : VectorType::get(PN->getType(), VF);
4372     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4373     VectorLoopValueMap.setVectorValue(P, 0, VecPhi);
4374     OrigPHIsToFix.push_back(P);
4375 
4376     return;
4377   }
4378 
4379   assert(PN->getParent() == OrigLoop->getHeader() &&
4380          "Non-header phis should have been handled elsewhere");
4381 
4382   // In order to support recurrences we need to be able to vectorize Phi nodes.
4383   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4384   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4385   // this value when we vectorize all of the instructions that use the PHI.
4386   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4387     for (unsigned Part = 0; Part < UF; ++Part) {
4388       // This is phase one of vectorizing PHIs.
4389       bool ScalarPHI =
4390           (VF.isScalar()) || Cost->isInLoopReduction(cast<PHINode>(PN));
4391       Type *VecTy =
4392           ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), VF);
4393       Value *EntryPart = PHINode::Create(
4394           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4395       VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4396     }
4397     return;
4398   }
4399 
4400   setDebugLocFromInst(Builder, P);
4401 
4402   // This PHINode must be an induction variable.
4403   // Make sure that we know about it.
4404   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4405 
4406   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4407   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4408 
4409   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4410   // which can be found from the original scalar operations.
4411   switch (II.getKind()) {
4412   case InductionDescriptor::IK_NoInduction:
4413     llvm_unreachable("Unknown induction");
4414   case InductionDescriptor::IK_IntInduction:
4415   case InductionDescriptor::IK_FpInduction:
4416     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4417   case InductionDescriptor::IK_PtrInduction: {
4418     // Handle the pointer induction variable case.
4419     assert(P->getType()->isPointerTy() && "Unexpected type.");
4420 
4421     if (Cost->isScalarAfterVectorization(P, VF)) {
4422       // This is the normalized GEP that starts counting at zero.
4423       Value *PtrInd =
4424           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4425       // Determine the number of scalars we need to generate for each unroll
4426       // iteration. If the instruction is uniform, we only need to generate the
4427       // first lane. Otherwise, we generate all VF values.
4428       unsigned Lanes =
4429           Cost->isUniformAfterVectorization(P, VF) ? 1 : VF.getKnownMinValue();
4430       for (unsigned Part = 0; Part < UF; ++Part) {
4431         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4432           Constant *Idx = ConstantInt::get(PtrInd->getType(),
4433                                            Lane + Part * VF.getKnownMinValue());
4434           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4435           Value *SclrGep =
4436               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4437           SclrGep->setName("next.gep");
4438           VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
4439         }
4440       }
4441       return;
4442     }
4443     assert(isa<SCEVConstant>(II.getStep()) &&
4444            "Induction step not a SCEV constant!");
4445     Type *PhiType = II.getStep()->getType();
4446 
4447     // Build a pointer phi
4448     Value *ScalarStartValue = II.getStartValue();
4449     Type *ScStValueType = ScalarStartValue->getType();
4450     PHINode *NewPointerPhi =
4451         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4452     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4453 
4454     // A pointer induction, performed by using a gep
4455     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4456     Instruction *InductionLoc = LoopLatch->getTerminator();
4457     const SCEV *ScalarStep = II.getStep();
4458     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4459     Value *ScalarStepValue =
4460         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4461     Value *InductionGEP = GetElementPtrInst::Create(
4462         ScStValueType->getPointerElementType(), NewPointerPhi,
4463         Builder.CreateMul(
4464             ScalarStepValue,
4465             ConstantInt::get(PhiType, VF.getKnownMinValue() * UF)),
4466         "ptr.ind", InductionLoc);
4467     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4468 
4469     // Create UF many actual address geps that use the pointer
4470     // phi as base and a vectorized version of the step value
4471     // (<step*0, ..., step*N>) as offset.
4472     for (unsigned Part = 0; Part < UF; ++Part) {
4473       SmallVector<Constant *, 8> Indices;
4474       // Create a vector of consecutive numbers from zero to VF.
4475       for (unsigned i = 0; i < VF.getKnownMinValue(); ++i)
4476         Indices.push_back(
4477             ConstantInt::get(PhiType, i + Part * VF.getKnownMinValue()));
4478       Constant *StartOffset = ConstantVector::get(Indices);
4479 
4480       Value *GEP = Builder.CreateGEP(
4481           ScStValueType->getPointerElementType(), NewPointerPhi,
4482           Builder.CreateMul(
4483               StartOffset,
4484               Builder.CreateVectorSplat(VF.getKnownMinValue(), ScalarStepValue),
4485               "vector.gep"));
4486       VectorLoopValueMap.setVectorValue(P, Part, GEP);
4487     }
4488   }
4489   }
4490 }
4491 
4492 /// A helper function for checking whether an integer division-related
4493 /// instruction may divide by zero (in which case it must be predicated if
4494 /// executed conditionally in the scalar code).
4495 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4496 /// Non-zero divisors that are non compile-time constants will not be
4497 /// converted into multiplication, so we will still end up scalarizing
4498 /// the division, but can do so w/o predication.
4499 static bool mayDivideByZero(Instruction &I) {
4500   assert((I.getOpcode() == Instruction::UDiv ||
4501           I.getOpcode() == Instruction::SDiv ||
4502           I.getOpcode() == Instruction::URem ||
4503           I.getOpcode() == Instruction::SRem) &&
4504          "Unexpected instruction");
4505   Value *Divisor = I.getOperand(1);
4506   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4507   return !CInt || CInt->isZero();
4508 }
4509 
4510 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPUser &User,
4511                                            VPTransformState &State) {
4512   assert(!VF.isScalable() && "scalable vectors not yet supported.");
4513   switch (I.getOpcode()) {
4514   case Instruction::Call:
4515   case Instruction::Br:
4516   case Instruction::PHI:
4517   case Instruction::GetElementPtr:
4518   case Instruction::Select:
4519     llvm_unreachable("This instruction is handled by a different recipe.");
4520   case Instruction::UDiv:
4521   case Instruction::SDiv:
4522   case Instruction::SRem:
4523   case Instruction::URem:
4524   case Instruction::Add:
4525   case Instruction::FAdd:
4526   case Instruction::Sub:
4527   case Instruction::FSub:
4528   case Instruction::FNeg:
4529   case Instruction::Mul:
4530   case Instruction::FMul:
4531   case Instruction::FDiv:
4532   case Instruction::FRem:
4533   case Instruction::Shl:
4534   case Instruction::LShr:
4535   case Instruction::AShr:
4536   case Instruction::And:
4537   case Instruction::Or:
4538   case Instruction::Xor: {
4539     // Just widen unops and binops.
4540     setDebugLocFromInst(Builder, &I);
4541 
4542     for (unsigned Part = 0; Part < UF; ++Part) {
4543       SmallVector<Value *, 2> Ops;
4544       for (VPValue *VPOp : User.operands())
4545         Ops.push_back(State.get(VPOp, Part));
4546 
4547       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4548 
4549       if (auto *VecOp = dyn_cast<Instruction>(V))
4550         VecOp->copyIRFlags(&I);
4551 
4552       // Use this vector value for all users of the original instruction.
4553       VectorLoopValueMap.setVectorValue(&I, Part, V);
4554       addMetadata(V, &I);
4555     }
4556 
4557     break;
4558   }
4559   case Instruction::ICmp:
4560   case Instruction::FCmp: {
4561     // Widen compares. Generate vector compares.
4562     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4563     auto *Cmp = cast<CmpInst>(&I);
4564     setDebugLocFromInst(Builder, Cmp);
4565     for (unsigned Part = 0; Part < UF; ++Part) {
4566       Value *A = State.get(User.getOperand(0), Part);
4567       Value *B = State.get(User.getOperand(1), Part);
4568       Value *C = nullptr;
4569       if (FCmp) {
4570         // Propagate fast math flags.
4571         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4572         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4573         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4574       } else {
4575         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4576       }
4577       VectorLoopValueMap.setVectorValue(&I, Part, C);
4578       addMetadata(C, &I);
4579     }
4580 
4581     break;
4582   }
4583 
4584   case Instruction::ZExt:
4585   case Instruction::SExt:
4586   case Instruction::FPToUI:
4587   case Instruction::FPToSI:
4588   case Instruction::FPExt:
4589   case Instruction::PtrToInt:
4590   case Instruction::IntToPtr:
4591   case Instruction::SIToFP:
4592   case Instruction::UIToFP:
4593   case Instruction::Trunc:
4594   case Instruction::FPTrunc:
4595   case Instruction::BitCast: {
4596     auto *CI = cast<CastInst>(&I);
4597     setDebugLocFromInst(Builder, CI);
4598 
4599     /// Vectorize casts.
4600     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
4601     Type *DestTy =
4602         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
4603 
4604     for (unsigned Part = 0; Part < UF; ++Part) {
4605       Value *A = State.get(User.getOperand(0), Part);
4606       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4607       VectorLoopValueMap.setVectorValue(&I, Part, Cast);
4608       addMetadata(Cast, &I);
4609     }
4610     break;
4611   }
4612   default:
4613     // This instruction is not vectorized by simple widening.
4614     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4615     llvm_unreachable("Unhandled instruction!");
4616   } // end of switch.
4617 }
4618 
4619 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4620                                                VPUser &ArgOperands,
4621                                                VPTransformState &State) {
4622   assert(!isa<DbgInfoIntrinsic>(I) &&
4623          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4624   setDebugLocFromInst(Builder, &I);
4625 
4626   Module *M = I.getParent()->getParent()->getParent();
4627   auto *CI = cast<CallInst>(&I);
4628 
4629   SmallVector<Type *, 4> Tys;
4630   for (Value *ArgOperand : CI->arg_operands())
4631     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4632 
4633   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4634 
4635   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4636   // version of the instruction.
4637   // Is it beneficial to perform intrinsic call compared to lib call?
4638   bool NeedToScalarize = false;
4639   unsigned CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4640   bool UseVectorIntrinsic =
4641       ID && Cost->getVectorIntrinsicCost(CI, VF) <= CallCost;
4642   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4643          "Instruction should be scalarized elsewhere.");
4644 
4645   for (unsigned Part = 0; Part < UF; ++Part) {
4646     SmallVector<Value *, 4> Args;
4647     for (auto &I : enumerate(ArgOperands.operands())) {
4648       // Some intrinsics have a scalar argument - don't replace it with a
4649       // vector.
4650       Value *Arg;
4651       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
4652         Arg = State.get(I.value(), Part);
4653       else
4654         Arg = State.get(I.value(), {0, 0});
4655       Args.push_back(Arg);
4656     }
4657 
4658     Function *VectorF;
4659     if (UseVectorIntrinsic) {
4660       // Use vector version of the intrinsic.
4661       Type *TysForDecl[] = {CI->getType()};
4662       if (VF.isVector()) {
4663         assert(!VF.isScalable() && "VF is assumed to be non scalable.");
4664         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4665       }
4666       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4667       assert(VectorF && "Can't retrieve vector intrinsic.");
4668     } else {
4669       // Use vector version of the function call.
4670       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4671 #ifndef NDEBUG
4672       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4673              "Can't create vector function.");
4674 #endif
4675         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4676     }
4677       SmallVector<OperandBundleDef, 1> OpBundles;
4678       CI->getOperandBundlesAsDefs(OpBundles);
4679       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4680 
4681       if (isa<FPMathOperator>(V))
4682         V->copyFastMathFlags(CI);
4683 
4684       State.set(Def, &I, V, Part);
4685       addMetadata(V, &I);
4686   }
4687 }
4688 
4689 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I,
4690                                                  VPUser &Operands,
4691                                                  bool InvariantCond,
4692                                                  VPTransformState &State) {
4693   setDebugLocFromInst(Builder, &I);
4694 
4695   // The condition can be loop invariant  but still defined inside the
4696   // loop. This means that we can't just use the original 'cond' value.
4697   // We have to take the 'vectorized' value and pick the first lane.
4698   // Instcombine will make this a no-op.
4699   auto *InvarCond =
4700       InvariantCond ? State.get(Operands.getOperand(0), {0, 0}) : nullptr;
4701 
4702   for (unsigned Part = 0; Part < UF; ++Part) {
4703     Value *Cond =
4704         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
4705     Value *Op0 = State.get(Operands.getOperand(1), Part);
4706     Value *Op1 = State.get(Operands.getOperand(2), Part);
4707     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
4708     VectorLoopValueMap.setVectorValue(&I, Part, Sel);
4709     addMetadata(Sel, &I);
4710   }
4711 }
4712 
4713 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4714   // We should not collect Scalars more than once per VF. Right now, this
4715   // function is called from collectUniformsAndScalars(), which already does
4716   // this check. Collecting Scalars for VF=1 does not make any sense.
4717   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4718          "This function should not be visited twice for the same VF");
4719 
4720   SmallSetVector<Instruction *, 8> Worklist;
4721 
4722   // These sets are used to seed the analysis with pointers used by memory
4723   // accesses that will remain scalar.
4724   SmallSetVector<Instruction *, 8> ScalarPtrs;
4725   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4726   auto *Latch = TheLoop->getLoopLatch();
4727 
4728   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4729   // The pointer operands of loads and stores will be scalar as long as the
4730   // memory access is not a gather or scatter operation. The value operand of a
4731   // store will remain scalar if the store is scalarized.
4732   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4733     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4734     assert(WideningDecision != CM_Unknown &&
4735            "Widening decision should be ready at this moment");
4736     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4737       if (Ptr == Store->getValueOperand())
4738         return WideningDecision == CM_Scalarize;
4739     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4740            "Ptr is neither a value or pointer operand");
4741     return WideningDecision != CM_GatherScatter;
4742   };
4743 
4744   // A helper that returns true if the given value is a bitcast or
4745   // getelementptr instruction contained in the loop.
4746   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4747     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4748             isa<GetElementPtrInst>(V)) &&
4749            !TheLoop->isLoopInvariant(V);
4750   };
4751 
4752   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
4753     if (!isa<PHINode>(Ptr) ||
4754         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
4755       return false;
4756     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
4757     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
4758       return false;
4759     return isScalarUse(MemAccess, Ptr);
4760   };
4761 
4762   // A helper that evaluates a memory access's use of a pointer. If the
4763   // pointer is actually the pointer induction of a loop, it is being
4764   // inserted into Worklist. If the use will be a scalar use, and the
4765   // pointer is only used by memory accesses, we place the pointer in
4766   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
4767   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4768     if (isScalarPtrInduction(MemAccess, Ptr)) {
4769       Worklist.insert(cast<Instruction>(Ptr));
4770       Instruction *Update = cast<Instruction>(
4771           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
4772       Worklist.insert(Update);
4773       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
4774                         << "\n");
4775       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
4776                         << "\n");
4777       return;
4778     }
4779     // We only care about bitcast and getelementptr instructions contained in
4780     // the loop.
4781     if (!isLoopVaryingBitCastOrGEP(Ptr))
4782       return;
4783 
4784     // If the pointer has already been identified as scalar (e.g., if it was
4785     // also identified as uniform), there's nothing to do.
4786     auto *I = cast<Instruction>(Ptr);
4787     if (Worklist.count(I))
4788       return;
4789 
4790     // If the use of the pointer will be a scalar use, and all users of the
4791     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4792     // place the pointer in PossibleNonScalarPtrs.
4793     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4794           return isa<LoadInst>(U) || isa<StoreInst>(U);
4795         }))
4796       ScalarPtrs.insert(I);
4797     else
4798       PossibleNonScalarPtrs.insert(I);
4799   };
4800 
4801   // We seed the scalars analysis with three classes of instructions: (1)
4802   // instructions marked uniform-after-vectorization and (2) bitcast,
4803   // getelementptr and (pointer) phi instructions used by memory accesses
4804   // requiring a scalar use.
4805   //
4806   // (1) Add to the worklist all instructions that have been identified as
4807   // uniform-after-vectorization.
4808   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4809 
4810   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4811   // memory accesses requiring a scalar use. The pointer operands of loads and
4812   // stores will be scalar as long as the memory accesses is not a gather or
4813   // scatter operation. The value operand of a store will remain scalar if the
4814   // store is scalarized.
4815   for (auto *BB : TheLoop->blocks())
4816     for (auto &I : *BB) {
4817       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4818         evaluatePtrUse(Load, Load->getPointerOperand());
4819       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4820         evaluatePtrUse(Store, Store->getPointerOperand());
4821         evaluatePtrUse(Store, Store->getValueOperand());
4822       }
4823     }
4824   for (auto *I : ScalarPtrs)
4825     if (!PossibleNonScalarPtrs.count(I)) {
4826       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4827       Worklist.insert(I);
4828     }
4829 
4830   // Insert the forced scalars.
4831   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4832   // induction variable when the PHI user is scalarized.
4833   auto ForcedScalar = ForcedScalars.find(VF);
4834   if (ForcedScalar != ForcedScalars.end())
4835     for (auto *I : ForcedScalar->second)
4836       Worklist.insert(I);
4837 
4838   // Expand the worklist by looking through any bitcasts and getelementptr
4839   // instructions we've already identified as scalar. This is similar to the
4840   // expansion step in collectLoopUniforms(); however, here we're only
4841   // expanding to include additional bitcasts and getelementptr instructions.
4842   unsigned Idx = 0;
4843   while (Idx != Worklist.size()) {
4844     Instruction *Dst = Worklist[Idx++];
4845     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4846       continue;
4847     auto *Src = cast<Instruction>(Dst->getOperand(0));
4848     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4849           auto *J = cast<Instruction>(U);
4850           return !TheLoop->contains(J) || Worklist.count(J) ||
4851                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4852                   isScalarUse(J, Src));
4853         })) {
4854       Worklist.insert(Src);
4855       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4856     }
4857   }
4858 
4859   // An induction variable will remain scalar if all users of the induction
4860   // variable and induction variable update remain scalar.
4861   for (auto &Induction : Legal->getInductionVars()) {
4862     auto *Ind = Induction.first;
4863     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4864 
4865     // If tail-folding is applied, the primary induction variable will be used
4866     // to feed a vector compare.
4867     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4868       continue;
4869 
4870     // Determine if all users of the induction variable are scalar after
4871     // vectorization.
4872     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4873       auto *I = cast<Instruction>(U);
4874       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
4875     });
4876     if (!ScalarInd)
4877       continue;
4878 
4879     // Determine if all users of the induction variable update instruction are
4880     // scalar after vectorization.
4881     auto ScalarIndUpdate =
4882         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4883           auto *I = cast<Instruction>(U);
4884           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
4885         });
4886     if (!ScalarIndUpdate)
4887       continue;
4888 
4889     // The induction variable and its update instruction will remain scalar.
4890     Worklist.insert(Ind);
4891     Worklist.insert(IndUpdate);
4892     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4893     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4894                       << "\n");
4895   }
4896 
4897   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4898 }
4899 
4900 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I,
4901                                                          ElementCount VF) {
4902   assert(!VF.isScalable() && "scalable vectors not yet supported.");
4903   if (!blockNeedsPredication(I->getParent()))
4904     return false;
4905   switch(I->getOpcode()) {
4906   default:
4907     break;
4908   case Instruction::Load:
4909   case Instruction::Store: {
4910     if (!Legal->isMaskRequired(I))
4911       return false;
4912     auto *Ptr = getLoadStorePointerOperand(I);
4913     auto *Ty = getMemInstValueType(I);
4914     // We have already decided how to vectorize this instruction, get that
4915     // result.
4916     if (VF.isVector()) {
4917       InstWidening WideningDecision = getWideningDecision(I, VF);
4918       assert(WideningDecision != CM_Unknown &&
4919              "Widening decision should be ready at this moment");
4920       return WideningDecision == CM_Scalarize;
4921     }
4922     const Align Alignment = getLoadStoreAlignment(I);
4923     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4924                                 isLegalMaskedGather(Ty, Alignment))
4925                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4926                                 isLegalMaskedScatter(Ty, Alignment));
4927   }
4928   case Instruction::UDiv:
4929   case Instruction::SDiv:
4930   case Instruction::SRem:
4931   case Instruction::URem:
4932     return mayDivideByZero(*I);
4933   }
4934   return false;
4935 }
4936 
4937 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4938     Instruction *I, ElementCount VF) {
4939   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4940   assert(getWideningDecision(I, VF) == CM_Unknown &&
4941          "Decision should not be set yet.");
4942   auto *Group = getInterleavedAccessGroup(I);
4943   assert(Group && "Must have a group.");
4944 
4945   // If the instruction's allocated size doesn't equal it's type size, it
4946   // requires padding and will be scalarized.
4947   auto &DL = I->getModule()->getDataLayout();
4948   auto *ScalarTy = getMemInstValueType(I);
4949   if (hasIrregularType(ScalarTy, DL, VF))
4950     return false;
4951 
4952   // Check if masking is required.
4953   // A Group may need masking for one of two reasons: it resides in a block that
4954   // needs predication, or it was decided to use masking to deal with gaps.
4955   bool PredicatedAccessRequiresMasking =
4956       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
4957   bool AccessWithGapsRequiresMasking =
4958       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
4959   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
4960     return true;
4961 
4962   // If masked interleaving is required, we expect that the user/target had
4963   // enabled it, because otherwise it either wouldn't have been created or
4964   // it should have been invalidated by the CostModel.
4965   assert(useMaskedInterleavedAccesses(TTI) &&
4966          "Masked interleave-groups for predicated accesses are not enabled.");
4967 
4968   auto *Ty = getMemInstValueType(I);
4969   const Align Alignment = getLoadStoreAlignment(I);
4970   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4971                           : TTI.isLegalMaskedStore(Ty, Alignment);
4972 }
4973 
4974 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4975     Instruction *I, ElementCount VF) {
4976   // Get and ensure we have a valid memory instruction.
4977   LoadInst *LI = dyn_cast<LoadInst>(I);
4978   StoreInst *SI = dyn_cast<StoreInst>(I);
4979   assert((LI || SI) && "Invalid memory instruction");
4980 
4981   auto *Ptr = getLoadStorePointerOperand(I);
4982 
4983   // In order to be widened, the pointer should be consecutive, first of all.
4984   if (!Legal->isConsecutivePtr(Ptr))
4985     return false;
4986 
4987   // If the instruction is a store located in a predicated block, it will be
4988   // scalarized.
4989   if (isScalarWithPredication(I))
4990     return false;
4991 
4992   // If the instruction's allocated size doesn't equal it's type size, it
4993   // requires padding and will be scalarized.
4994   auto &DL = I->getModule()->getDataLayout();
4995   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
4996   if (hasIrregularType(ScalarTy, DL, VF))
4997     return false;
4998 
4999   return true;
5000 }
5001 
5002 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5003   // We should not collect Uniforms more than once per VF. Right now,
5004   // this function is called from collectUniformsAndScalars(), which
5005   // already does this check. Collecting Uniforms for VF=1 does not make any
5006   // sense.
5007 
5008   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5009          "This function should not be visited twice for the same VF");
5010 
5011   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5012   // not analyze again.  Uniforms.count(VF) will return 1.
5013   Uniforms[VF].clear();
5014 
5015   // We now know that the loop is vectorizable!
5016   // Collect instructions inside the loop that will remain uniform after
5017   // vectorization.
5018 
5019   // Global values, params and instructions outside of current loop are out of
5020   // scope.
5021   auto isOutOfScope = [&](Value *V) -> bool {
5022     Instruction *I = dyn_cast<Instruction>(V);
5023     return (!I || !TheLoop->contains(I));
5024   };
5025 
5026   SetVector<Instruction *> Worklist;
5027   BasicBlock *Latch = TheLoop->getLoopLatch();
5028 
5029   // Instructions that are scalar with predication must not be considered
5030   // uniform after vectorization, because that would create an erroneous
5031   // replicating region where only a single instance out of VF should be formed.
5032   // TODO: optimize such seldom cases if found important, see PR40816.
5033   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5034     if (isScalarWithPredication(I, VF)) {
5035       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5036                         << *I << "\n");
5037       return;
5038     }
5039     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5040     Worklist.insert(I);
5041   };
5042 
5043   // Start with the conditional branch. If the branch condition is an
5044   // instruction contained in the loop that is only used by the branch, it is
5045   // uniform.
5046   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5047   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5048     addToWorklistIfAllowed(Cmp);
5049 
5050   // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5051   // are pointers that are treated like consecutive pointers during
5052   // vectorization. The pointer operands of interleaved accesses are an
5053   // example.
5054   SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5055 
5056   // Holds pointer operands of instructions that are possibly non-uniform.
5057   SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5058 
5059   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5060     InstWidening WideningDecision = getWideningDecision(I, VF);
5061     assert(WideningDecision != CM_Unknown &&
5062            "Widening decision should be ready at this moment");
5063 
5064     return (WideningDecision == CM_Widen ||
5065             WideningDecision == CM_Widen_Reverse ||
5066             WideningDecision == CM_Interleave);
5067   };
5068   // Iterate over the instructions in the loop, and collect all
5069   // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5070   // that a consecutive-like pointer operand will be scalarized, we collect it
5071   // in PossibleNonUniformPtrs instead. We use two sets here because a single
5072   // getelementptr instruction can be used by both vectorized and scalarized
5073   // memory instructions. For example, if a loop loads and stores from the same
5074   // location, but the store is conditional, the store will be scalarized, and
5075   // the getelementptr won't remain uniform.
5076   for (auto *BB : TheLoop->blocks())
5077     for (auto &I : *BB) {
5078       // If there's no pointer operand, there's nothing to do.
5079       auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
5080       if (!Ptr)
5081         continue;
5082 
5083       // True if all users of Ptr are memory accesses that have Ptr as their
5084       // pointer operand.
5085       auto UsersAreMemAccesses =
5086           llvm::all_of(Ptr->users(), [&](User *U) -> bool {
5087             return getLoadStorePointerOperand(U) == Ptr;
5088           });
5089 
5090       // Ensure the memory instruction will not be scalarized or used by
5091       // gather/scatter, making its pointer operand non-uniform. If the pointer
5092       // operand is used by any instruction other than a memory access, we
5093       // conservatively assume the pointer operand may be non-uniform.
5094       if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5095         PossibleNonUniformPtrs.insert(Ptr);
5096 
5097       // If the memory instruction will be vectorized and its pointer operand
5098       // is consecutive-like, or interleaving - the pointer operand should
5099       // remain uniform.
5100       else
5101         ConsecutiveLikePtrs.insert(Ptr);
5102     }
5103 
5104   // Add to the Worklist all consecutive and consecutive-like pointers that
5105   // aren't also identified as possibly non-uniform.
5106   for (auto *V : ConsecutiveLikePtrs)
5107     if (!PossibleNonUniformPtrs.count(V))
5108       addToWorklistIfAllowed(V);
5109 
5110   // Expand Worklist in topological order: whenever a new instruction
5111   // is added , its users should be already inside Worklist.  It ensures
5112   // a uniform instruction will only be used by uniform instructions.
5113   unsigned idx = 0;
5114   while (idx != Worklist.size()) {
5115     Instruction *I = Worklist[idx++];
5116 
5117     for (auto OV : I->operand_values()) {
5118       // isOutOfScope operands cannot be uniform instructions.
5119       if (isOutOfScope(OV))
5120         continue;
5121       // First order recurrence Phi's should typically be considered
5122       // non-uniform.
5123       auto *OP = dyn_cast<PHINode>(OV);
5124       if (OP && Legal->isFirstOrderRecurrence(OP))
5125         continue;
5126       // If all the users of the operand are uniform, then add the
5127       // operand into the uniform worklist.
5128       auto *OI = cast<Instruction>(OV);
5129       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5130             auto *J = cast<Instruction>(U);
5131             return Worklist.count(J) ||
5132                    (OI == getLoadStorePointerOperand(J) &&
5133                     isUniformDecision(J, VF));
5134           }))
5135         addToWorklistIfAllowed(OI);
5136     }
5137   }
5138 
5139   // Returns true if Ptr is the pointer operand of a memory access instruction
5140   // I, and I is known to not require scalarization.
5141   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5142     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5143   };
5144 
5145   // For an instruction to be added into Worklist above, all its users inside
5146   // the loop should also be in Worklist. However, this condition cannot be
5147   // true for phi nodes that form a cyclic dependence. We must process phi
5148   // nodes separately. An induction variable will remain uniform if all users
5149   // of the induction variable and induction variable update remain uniform.
5150   // The code below handles both pointer and non-pointer induction variables.
5151   for (auto &Induction : Legal->getInductionVars()) {
5152     auto *Ind = Induction.first;
5153     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5154 
5155     // Determine if all users of the induction variable are uniform after
5156     // vectorization.
5157     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5158       auto *I = cast<Instruction>(U);
5159       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5160              isVectorizedMemAccessUse(I, Ind);
5161     });
5162     if (!UniformInd)
5163       continue;
5164 
5165     // Determine if all users of the induction variable update instruction are
5166     // uniform after vectorization.
5167     auto UniformIndUpdate =
5168         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5169           auto *I = cast<Instruction>(U);
5170           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5171                  isVectorizedMemAccessUse(I, IndUpdate);
5172         });
5173     if (!UniformIndUpdate)
5174       continue;
5175 
5176     // The induction variable and its update instruction will remain uniform.
5177     addToWorklistIfAllowed(Ind);
5178     addToWorklistIfAllowed(IndUpdate);
5179   }
5180 
5181   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5182 }
5183 
5184 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5185   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5186 
5187   if (Legal->getRuntimePointerChecking()->Need) {
5188     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5189         "runtime pointer checks needed. Enable vectorization of this "
5190         "loop with '#pragma clang loop vectorize(enable)' when "
5191         "compiling with -Os/-Oz",
5192         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5193     return true;
5194   }
5195 
5196   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5197     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5198         "runtime SCEV checks needed. Enable vectorization of this "
5199         "loop with '#pragma clang loop vectorize(enable)' when "
5200         "compiling with -Os/-Oz",
5201         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5202     return true;
5203   }
5204 
5205   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5206   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5207     reportVectorizationFailure("Runtime stride check for small trip count",
5208         "runtime stride == 1 checks needed. Enable vectorization of "
5209         "this loop without such check by compiling with -Os/-Oz",
5210         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5211     return true;
5212   }
5213 
5214   return false;
5215 }
5216 
5217 Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(unsigned UserVF,
5218                                                             unsigned UserIC) {
5219   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5220     // TODO: It may by useful to do since it's still likely to be dynamically
5221     // uniform if the target can skip.
5222     reportVectorizationFailure(
5223         "Not inserting runtime ptr check for divergent target",
5224         "runtime pointer checks needed. Not enabled for divergent target",
5225         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5226     return None;
5227   }
5228 
5229   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5230   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5231   if (TC == 1) {
5232     reportVectorizationFailure("Single iteration (non) loop",
5233         "loop trip count is one, irrelevant for vectorization",
5234         "SingleIterationLoop", ORE, TheLoop);
5235     return None;
5236   }
5237 
5238   switch (ScalarEpilogueStatus) {
5239   case CM_ScalarEpilogueAllowed:
5240     return UserVF ? UserVF : computeFeasibleMaxVF(TC);
5241   case CM_ScalarEpilogueNotNeededUsePredicate:
5242     LLVM_DEBUG(
5243         dbgs() << "LV: vector predicate hint/switch found.\n"
5244                << "LV: Not allowing scalar epilogue, creating predicated "
5245                << "vector loop.\n");
5246     break;
5247   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5248     // fallthrough as a special case of OptForSize
5249   case CM_ScalarEpilogueNotAllowedOptSize:
5250     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5251       LLVM_DEBUG(
5252           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5253     else
5254       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5255                         << "count.\n");
5256 
5257     // Bail if runtime checks are required, which are not good when optimising
5258     // for size.
5259     if (runtimeChecksRequired())
5260       return None;
5261     break;
5262   }
5263 
5264   // Now try the tail folding
5265 
5266   // Invalidate interleave groups that require an epilogue if we can't mask
5267   // the interleave-group.
5268   if (!useMaskedInterleavedAccesses(TTI)) {
5269     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5270            "No decisions should have been taken at this point");
5271     // Note: There is no need to invalidate any cost modeling decisions here, as
5272     // non where taken so far.
5273     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5274   }
5275 
5276   unsigned MaxVF = UserVF ? UserVF : computeFeasibleMaxVF(TC);
5277   assert((UserVF || isPowerOf2_32(MaxVF)) && "MaxVF must be a power of 2");
5278   unsigned MaxVFtimesIC = UserIC ? MaxVF * UserIC : MaxVF;
5279   if (TC > 0 && TC % MaxVFtimesIC == 0) {
5280     // Accept MaxVF if we do not have a tail.
5281     LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5282     return MaxVF;
5283   }
5284 
5285   // If we don't know the precise trip count, or if the trip count that we
5286   // found modulo the vectorization factor is not zero, try to fold the tail
5287   // by masking.
5288   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5289   if (Legal->prepareToFoldTailByMasking()) {
5290     FoldTailByMasking = true;
5291     return MaxVF;
5292   }
5293 
5294   // If there was a tail-folding hint/switch, but we can't fold the tail by
5295   // masking, fallback to a vectorization with a scalar epilogue.
5296   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5297     if (PreferPredicateOverEpilogue == PreferPredicateTy::PredicateOrDontVectorize) {
5298       LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5299       return None;
5300     }
5301     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5302                          "scalar epilogue instead.\n");
5303     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5304     return MaxVF;
5305   }
5306 
5307   if (TC == 0) {
5308     reportVectorizationFailure(
5309         "Unable to calculate the loop count due to complex control flow",
5310         "unable to calculate the loop count due to complex control flow",
5311         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5312     return None;
5313   }
5314 
5315   reportVectorizationFailure(
5316       "Cannot optimize for size and vectorize at the same time.",
5317       "cannot optimize for size and vectorize at the same time. "
5318       "Enable vectorization of this loop with '#pragma clang loop "
5319       "vectorize(enable)' when compiling with -Os/-Oz",
5320       "NoTailLoopWithOptForSize", ORE, TheLoop);
5321   return None;
5322 }
5323 
5324 unsigned
5325 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount) {
5326   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5327   unsigned SmallestType, WidestType;
5328   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5329   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5330 
5331   // Get the maximum safe dependence distance in bits computed by LAA.
5332   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5333   // the memory accesses that is most restrictive (involved in the smallest
5334   // dependence distance).
5335   unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
5336 
5337   WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
5338 
5339   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5340   // Note that both WidestRegister and WidestType may not be a powers of 2.
5341   unsigned MaxVectorSize = PowerOf2Floor(WidestRegister / WidestType);
5342 
5343   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5344                     << " / " << WidestType << " bits.\n");
5345   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5346                     << WidestRegister << " bits.\n");
5347 
5348   assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"
5349                                  " into one vector!");
5350   if (MaxVectorSize == 0) {
5351     LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5352     MaxVectorSize = 1;
5353     return MaxVectorSize;
5354   } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
5355              isPowerOf2_32(ConstTripCount)) {
5356     // We need to clamp the VF to be the ConstTripCount. There is no point in
5357     // choosing a higher viable VF as done in the loop below.
5358     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5359                       << ConstTripCount << "\n");
5360     MaxVectorSize = ConstTripCount;
5361     return MaxVectorSize;
5362   }
5363 
5364   unsigned MaxVF = MaxVectorSize;
5365   if (TTI.shouldMaximizeVectorBandwidth(!isScalarEpilogueAllowed()) ||
5366       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5367     // Collect all viable vectorization factors larger than the default MaxVF
5368     // (i.e. MaxVectorSize).
5369     SmallVector<ElementCount, 8> VFs;
5370     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
5371     for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
5372       VFs.push_back(ElementCount::getFixed(VS));
5373 
5374     // For each VF calculate its register usage.
5375     auto RUs = calculateRegisterUsage(VFs);
5376 
5377     // Select the largest VF which doesn't require more registers than existing
5378     // ones.
5379     for (int i = RUs.size() - 1; i >= 0; --i) {
5380       bool Selected = true;
5381       for (auto& pair : RUs[i].MaxLocalUsers) {
5382         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5383         if (pair.second > TargetNumRegisters)
5384           Selected = false;
5385       }
5386       if (Selected) {
5387         MaxVF = VFs[i].getKnownMinValue();
5388         break;
5389       }
5390     }
5391     if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
5392       if (MaxVF < MinVF) {
5393         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5394                           << ") with target's minimum: " << MinVF << '\n');
5395         MaxVF = MinVF;
5396       }
5397     }
5398   }
5399   return MaxVF;
5400 }
5401 
5402 VectorizationFactor
5403 LoopVectorizationCostModel::selectVectorizationFactor(ElementCount MaxVF) {
5404   assert(!MaxVF.isScalable() && "scalable vectors not yet supported");
5405 
5406   float Cost = expectedCost(ElementCount::getFixed(1)).first;
5407   const float ScalarCost = Cost;
5408   unsigned Width = 1;
5409   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
5410 
5411   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5412   if (ForceVectorization && MaxVF.isVector()) {
5413     // Ignore scalar width, because the user explicitly wants vectorization.
5414     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5415     // evaluation.
5416     Cost = std::numeric_limits<float>::max();
5417   }
5418 
5419   for (unsigned i = 2; i <= MaxVF.getFixedValue(); i *= 2) {
5420     // Notice that the vector loop needs to be executed less times, so
5421     // we need to divide the cost of the vector loops by the width of
5422     // the vector elements.
5423     VectorizationCostTy C = expectedCost(ElementCount::getFixed(i));
5424     float VectorCost = C.first / (float)i;
5425     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5426                       << " costs: " << (int)VectorCost << ".\n");
5427     if (!C.second && !ForceVectorization) {
5428       LLVM_DEBUG(
5429           dbgs() << "LV: Not considering vector loop of width " << i
5430                  << " because it will not generate any vector instructions.\n");
5431       continue;
5432     }
5433     if (VectorCost < Cost) {
5434       Cost = VectorCost;
5435       Width = i;
5436     }
5437   }
5438 
5439   if (!EnableCondStoresVectorization && NumPredStores) {
5440     reportVectorizationFailure("There are conditional stores.",
5441         "store that is conditionally executed prevents vectorization",
5442         "ConditionalStore", ORE, TheLoop);
5443     Width = 1;
5444     Cost = ScalarCost;
5445   }
5446 
5447   LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
5448              << "LV: Vectorization seems to be not beneficial, "
5449              << "but was forced by a user.\n");
5450   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
5451   VectorizationFactor Factor = {ElementCount::getFixed(Width),
5452                                 (unsigned)(Width * Cost)};
5453   return Factor;
5454 }
5455 
5456 std::pair<unsigned, unsigned>
5457 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5458   unsigned MinWidth = -1U;
5459   unsigned MaxWidth = 8;
5460   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5461 
5462   // For each block.
5463   for (BasicBlock *BB : TheLoop->blocks()) {
5464     // For each instruction in the loop.
5465     for (Instruction &I : BB->instructionsWithoutDebug()) {
5466       Type *T = I.getType();
5467 
5468       // Skip ignored values.
5469       if (ValuesToIgnore.count(&I))
5470         continue;
5471 
5472       // Only examine Loads, Stores and PHINodes.
5473       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5474         continue;
5475 
5476       // Examine PHI nodes that are reduction variables. Update the type to
5477       // account for the recurrence type.
5478       if (auto *PN = dyn_cast<PHINode>(&I)) {
5479         if (!Legal->isReductionVariable(PN))
5480           continue;
5481         RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[PN];
5482         T = RdxDesc.getRecurrenceType();
5483       }
5484 
5485       // Examine the stored values.
5486       if (auto *ST = dyn_cast<StoreInst>(&I))
5487         T = ST->getValueOperand()->getType();
5488 
5489       // Ignore loaded pointer types and stored pointer types that are not
5490       // vectorizable.
5491       //
5492       // FIXME: The check here attempts to predict whether a load or store will
5493       //        be vectorized. We only know this for certain after a VF has
5494       //        been selected. Here, we assume that if an access can be
5495       //        vectorized, it will be. We should also look at extending this
5496       //        optimization to non-pointer types.
5497       //
5498       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
5499           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
5500         continue;
5501 
5502       MinWidth = std::min(MinWidth,
5503                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5504       MaxWidth = std::max(MaxWidth,
5505                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
5506     }
5507   }
5508 
5509   return {MinWidth, MaxWidth};
5510 }
5511 
5512 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5513                                                            unsigned LoopCost) {
5514   // -- The interleave heuristics --
5515   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5516   // There are many micro-architectural considerations that we can't predict
5517   // at this level. For example, frontend pressure (on decode or fetch) due to
5518   // code size, or the number and capabilities of the execution ports.
5519   //
5520   // We use the following heuristics to select the interleave count:
5521   // 1. If the code has reductions, then we interleave to break the cross
5522   // iteration dependency.
5523   // 2. If the loop is really small, then we interleave to reduce the loop
5524   // overhead.
5525   // 3. We don't interleave if we think that we will spill registers to memory
5526   // due to the increased register pressure.
5527 
5528   if (!isScalarEpilogueAllowed())
5529     return 1;
5530 
5531   // We used the distance for the interleave count.
5532   if (Legal->getMaxSafeDepDistBytes() != -1U)
5533     return 1;
5534 
5535   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5536   const bool HasReductions = !Legal->getReductionVars().empty();
5537   // Do not interleave loops with a relatively small known or estimated trip
5538   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5539   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5540   // because with the above conditions interleaving can expose ILP and break
5541   // cross iteration dependences for reductions.
5542   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5543       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5544     return 1;
5545 
5546   RegisterUsage R = calculateRegisterUsage({VF})[0];
5547   // We divide by these constants so assume that we have at least one
5548   // instruction that uses at least one register.
5549   for (auto& pair : R.MaxLocalUsers) {
5550     pair.second = std::max(pair.second, 1U);
5551   }
5552 
5553   // We calculate the interleave count using the following formula.
5554   // Subtract the number of loop invariants from the number of available
5555   // registers. These registers are used by all of the interleaved instances.
5556   // Next, divide the remaining registers by the number of registers that is
5557   // required by the loop, in order to estimate how many parallel instances
5558   // fit without causing spills. All of this is rounded down if necessary to be
5559   // a power of two. We want power of two interleave count to simplify any
5560   // addressing operations or alignment considerations.
5561   // We also want power of two interleave counts to ensure that the induction
5562   // variable of the vector loop wraps to zero, when tail is folded by masking;
5563   // this currently happens when OptForSize, in which case IC is set to 1 above.
5564   unsigned IC = UINT_MAX;
5565 
5566   for (auto& pair : R.MaxLocalUsers) {
5567     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5568     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5569                       << " registers of "
5570                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5571     if (VF.isScalar()) {
5572       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5573         TargetNumRegisters = ForceTargetNumScalarRegs;
5574     } else {
5575       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5576         TargetNumRegisters = ForceTargetNumVectorRegs;
5577     }
5578     unsigned MaxLocalUsers = pair.second;
5579     unsigned LoopInvariantRegs = 0;
5580     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5581       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5582 
5583     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5584     // Don't count the induction variable as interleaved.
5585     if (EnableIndVarRegisterHeur) {
5586       TmpIC =
5587           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5588                         std::max(1U, (MaxLocalUsers - 1)));
5589     }
5590 
5591     IC = std::min(IC, TmpIC);
5592   }
5593 
5594   // Clamp the interleave ranges to reasonable counts.
5595   assert(!VF.isScalable() && "scalable vectors not yet supported.");
5596   unsigned MaxInterleaveCount =
5597       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5598 
5599   // Check if the user has overridden the max.
5600   if (VF.isScalar()) {
5601     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5602       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5603   } else {
5604     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5605       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5606   }
5607 
5608   // If trip count is known or estimated compile time constant, limit the
5609   // interleave count to be less than the trip count divided by VF, provided it
5610   // is at least 1.
5611   if (BestKnownTC) {
5612     MaxInterleaveCount =
5613         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5614     // Make sure MaxInterleaveCount is greater than 0.
5615     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5616   }
5617 
5618   assert(MaxInterleaveCount > 0 &&
5619          "Maximum interleave count must be greater than 0");
5620 
5621   // Clamp the calculated IC to be between the 1 and the max interleave count
5622   // that the target and trip count allows.
5623   if (IC > MaxInterleaveCount)
5624     IC = MaxInterleaveCount;
5625   else
5626     // Make sure IC is greater than 0.
5627     IC = std::max(1u, IC);
5628 
5629   assert(IC > 0 && "Interleave count must be greater than 0.");
5630 
5631   // If we did not calculate the cost for VF (because the user selected the VF)
5632   // then we calculate the cost of VF here.
5633   if (LoopCost == 0)
5634     LoopCost = expectedCost(VF).first;
5635 
5636   assert(LoopCost && "Non-zero loop cost expected");
5637 
5638   // Interleave if we vectorized this loop and there is a reduction that could
5639   // benefit from interleaving.
5640   if (VF.isVector() && HasReductions) {
5641     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5642     return IC;
5643   }
5644 
5645   // Note that if we've already vectorized the loop we will have done the
5646   // runtime check and so interleaving won't require further checks.
5647   bool InterleavingRequiresRuntimePointerCheck =
5648       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5649 
5650   // We want to interleave small loops in order to reduce the loop overhead and
5651   // potentially expose ILP opportunities.
5652   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5653                     << "LV: IC is " << IC << '\n'
5654                     << "LV: VF is " << VF.getKnownMinValue() << '\n');
5655   const bool AggressivelyInterleaveReductions =
5656       TTI.enableAggressiveInterleaving(HasReductions);
5657   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
5658     // We assume that the cost overhead is 1 and we use the cost model
5659     // to estimate the cost of the loop and interleave until the cost of the
5660     // loop overhead is about 5% of the cost of the loop.
5661     unsigned SmallIC =
5662         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5663 
5664     // Interleave until store/load ports (estimated by max interleave count) are
5665     // saturated.
5666     unsigned NumStores = Legal->getNumStores();
5667     unsigned NumLoads = Legal->getNumLoads();
5668     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5669     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5670 
5671     // If we have a scalar reduction (vector reductions are already dealt with
5672     // by this point), we can increase the critical path length if the loop
5673     // we're interleaving is inside another loop. Limit, by default to 2, so the
5674     // critical path only gets increased by one reduction operation.
5675     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5676       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5677       SmallIC = std::min(SmallIC, F);
5678       StoresIC = std::min(StoresIC, F);
5679       LoadsIC = std::min(LoadsIC, F);
5680     }
5681 
5682     if (EnableLoadStoreRuntimeInterleave &&
5683         std::max(StoresIC, LoadsIC) > SmallIC) {
5684       LLVM_DEBUG(
5685           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5686       return std::max(StoresIC, LoadsIC);
5687     }
5688 
5689     // If there are scalar reductions and TTI has enabled aggressive
5690     // interleaving for reductions, we will interleave to expose ILP.
5691     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5692         AggressivelyInterleaveReductions) {
5693       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5694       // Interleave no less than SmallIC but not as aggressive as the normal IC
5695       // to satisfy the rare situation when resources are too limited.
5696       return std::max(IC / 2, SmallIC);
5697     } else {
5698       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5699       return SmallIC;
5700     }
5701   }
5702 
5703   // Interleave if this is a large loop (small loops are already dealt with by
5704   // this point) that could benefit from interleaving.
5705   if (AggressivelyInterleaveReductions) {
5706     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5707     return IC;
5708   }
5709 
5710   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5711   return 1;
5712 }
5713 
5714 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5715 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5716   // This function calculates the register usage by measuring the highest number
5717   // of values that are alive at a single location. Obviously, this is a very
5718   // rough estimation. We scan the loop in a topological order in order and
5719   // assign a number to each instruction. We use RPO to ensure that defs are
5720   // met before their users. We assume that each instruction that has in-loop
5721   // users starts an interval. We record every time that an in-loop value is
5722   // used, so we have a list of the first and last occurrences of each
5723   // instruction. Next, we transpose this data structure into a multi map that
5724   // holds the list of intervals that *end* at a specific location. This multi
5725   // map allows us to perform a linear search. We scan the instructions linearly
5726   // and record each time that a new interval starts, by placing it in a set.
5727   // If we find this value in the multi-map then we remove it from the set.
5728   // The max register usage is the maximum size of the set.
5729   // We also search for instructions that are defined outside the loop, but are
5730   // used inside the loop. We need this number separately from the max-interval
5731   // usage number because when we unroll, loop-invariant values do not take
5732   // more register.
5733   LoopBlocksDFS DFS(TheLoop);
5734   DFS.perform(LI);
5735 
5736   RegisterUsage RU;
5737 
5738   // Each 'key' in the map opens a new interval. The values
5739   // of the map are the index of the 'last seen' usage of the
5740   // instruction that is the key.
5741   using IntervalMap = DenseMap<Instruction *, unsigned>;
5742 
5743   // Maps instruction to its index.
5744   SmallVector<Instruction *, 64> IdxToInstr;
5745   // Marks the end of each interval.
5746   IntervalMap EndPoint;
5747   // Saves the list of instruction indices that are used in the loop.
5748   SmallPtrSet<Instruction *, 8> Ends;
5749   // Saves the list of values that are used in the loop but are
5750   // defined outside the loop, such as arguments and constants.
5751   SmallPtrSet<Value *, 8> LoopInvariants;
5752 
5753   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5754     for (Instruction &I : BB->instructionsWithoutDebug()) {
5755       IdxToInstr.push_back(&I);
5756 
5757       // Save the end location of each USE.
5758       for (Value *U : I.operands()) {
5759         auto *Instr = dyn_cast<Instruction>(U);
5760 
5761         // Ignore non-instruction values such as arguments, constants, etc.
5762         if (!Instr)
5763           continue;
5764 
5765         // If this instruction is outside the loop then record it and continue.
5766         if (!TheLoop->contains(Instr)) {
5767           LoopInvariants.insert(Instr);
5768           continue;
5769         }
5770 
5771         // Overwrite previous end points.
5772         EndPoint[Instr] = IdxToInstr.size();
5773         Ends.insert(Instr);
5774       }
5775     }
5776   }
5777 
5778   // Saves the list of intervals that end with the index in 'key'.
5779   using InstrList = SmallVector<Instruction *, 2>;
5780   DenseMap<unsigned, InstrList> TransposeEnds;
5781 
5782   // Transpose the EndPoints to a list of values that end at each index.
5783   for (auto &Interval : EndPoint)
5784     TransposeEnds[Interval.second].push_back(Interval.first);
5785 
5786   SmallPtrSet<Instruction *, 8> OpenIntervals;
5787 
5788   // Get the size of the widest register.
5789   unsigned MaxSafeDepDist = -1U;
5790   if (Legal->getMaxSafeDepDistBytes() != -1U)
5791     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
5792   unsigned WidestRegister =
5793       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
5794   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5795 
5796   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5797   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5798 
5799   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5800 
5801   // A lambda that gets the register usage for the given type and VF.
5802   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, ElementCount VF) {
5803     if (Ty->isTokenTy())
5804       return 0U;
5805     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
5806     assert(!VF.isScalable() && "scalable vectors not yet supported.");
5807     return std::max<unsigned>(1, VF.getKnownMinValue() * TypeSize /
5808                                      WidestRegister);
5809   };
5810 
5811   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
5812     Instruction *I = IdxToInstr[i];
5813 
5814     // Remove all of the instructions that end at this location.
5815     InstrList &List = TransposeEnds[i];
5816     for (Instruction *ToRemove : List)
5817       OpenIntervals.erase(ToRemove);
5818 
5819     // Ignore instructions that are never used within the loop.
5820     if (!Ends.count(I))
5821       continue;
5822 
5823     // Skip ignored values.
5824     if (ValuesToIgnore.count(I))
5825       continue;
5826 
5827     // For each VF find the maximum usage of registers.
5828     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5829       // Count the number of live intervals.
5830       SmallMapVector<unsigned, unsigned, 4> RegUsage;
5831 
5832       if (VFs[j].isScalar()) {
5833         for (auto Inst : OpenIntervals) {
5834           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5835           if (RegUsage.find(ClassID) == RegUsage.end())
5836             RegUsage[ClassID] = 1;
5837           else
5838             RegUsage[ClassID] += 1;
5839         }
5840       } else {
5841         collectUniformsAndScalars(VFs[j]);
5842         for (auto Inst : OpenIntervals) {
5843           // Skip ignored values for VF > 1.
5844           if (VecValuesToIgnore.count(Inst))
5845             continue;
5846           if (isScalarAfterVectorization(Inst, VFs[j])) {
5847             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5848             if (RegUsage.find(ClassID) == RegUsage.end())
5849               RegUsage[ClassID] = 1;
5850             else
5851               RegUsage[ClassID] += 1;
5852           } else {
5853             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
5854             if (RegUsage.find(ClassID) == RegUsage.end())
5855               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
5856             else
5857               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
5858           }
5859         }
5860       }
5861 
5862       for (auto& pair : RegUsage) {
5863         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
5864           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
5865         else
5866           MaxUsages[j][pair.first] = pair.second;
5867       }
5868     }
5869 
5870     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
5871                       << OpenIntervals.size() << '\n');
5872 
5873     // Add the current instruction to the list of open intervals.
5874     OpenIntervals.insert(I);
5875   }
5876 
5877   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
5878     SmallMapVector<unsigned, unsigned, 4> Invariant;
5879 
5880     for (auto Inst : LoopInvariants) {
5881       unsigned Usage =
5882           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
5883       unsigned ClassID =
5884           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
5885       if (Invariant.find(ClassID) == Invariant.end())
5886         Invariant[ClassID] = Usage;
5887       else
5888         Invariant[ClassID] += Usage;
5889     }
5890 
5891     LLVM_DEBUG({
5892       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
5893       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
5894              << " item\n";
5895       for (const auto &pair : MaxUsages[i]) {
5896         dbgs() << "LV(REG): RegisterClass: "
5897                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
5898                << " registers\n";
5899       }
5900       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
5901              << " item\n";
5902       for (const auto &pair : Invariant) {
5903         dbgs() << "LV(REG): RegisterClass: "
5904                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
5905                << " registers\n";
5906       }
5907     });
5908 
5909     RU.LoopInvariantRegs = Invariant;
5910     RU.MaxLocalUsers = MaxUsages[i];
5911     RUs[i] = RU;
5912   }
5913 
5914   return RUs;
5915 }
5916 
5917 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
5918   // TODO: Cost model for emulated masked load/store is completely
5919   // broken. This hack guides the cost model to use an artificially
5920   // high enough value to practically disable vectorization with such
5921   // operations, except where previously deployed legality hack allowed
5922   // using very low cost values. This is to avoid regressions coming simply
5923   // from moving "masked load/store" check from legality to cost model.
5924   // Masked Load/Gather emulation was previously never allowed.
5925   // Limited number of Masked Store/Scatter emulation was allowed.
5926   assert(isPredicatedInst(I) && "Expecting a scalar emulated instruction");
5927   return isa<LoadInst>(I) ||
5928          (isa<StoreInst>(I) &&
5929           NumPredStores > NumberOfStoresToPredicate);
5930 }
5931 
5932 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
5933   // If we aren't vectorizing the loop, or if we've already collected the
5934   // instructions to scalarize, there's nothing to do. Collection may already
5935   // have occurred if we have a user-selected VF and are now computing the
5936   // expected cost for interleaving.
5937   if (VF.isScalar() || VF.isZero() ||
5938       InstsToScalarize.find(VF) != InstsToScalarize.end())
5939     return;
5940 
5941   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
5942   // not profitable to scalarize any instructions, the presence of VF in the
5943   // map will indicate that we've analyzed it already.
5944   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
5945 
5946   // Find all the instructions that are scalar with predication in the loop and
5947   // determine if it would be better to not if-convert the blocks they are in.
5948   // If so, we also record the instructions to scalarize.
5949   for (BasicBlock *BB : TheLoop->blocks()) {
5950     if (!blockNeedsPredication(BB))
5951       continue;
5952     for (Instruction &I : *BB)
5953       if (isScalarWithPredication(&I)) {
5954         ScalarCostsTy ScalarCosts;
5955         // Do not apply discount logic if hacked cost is needed
5956         // for emulated masked memrefs.
5957         if (!useEmulatedMaskMemRefHack(&I) &&
5958             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
5959           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
5960         // Remember that BB will remain after vectorization.
5961         PredicatedBBsAfterVectorization.insert(BB);
5962       }
5963   }
5964 }
5965 
5966 int LoopVectorizationCostModel::computePredInstDiscount(
5967     Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
5968     ElementCount VF) {
5969   assert(!isUniformAfterVectorization(PredInst, VF) &&
5970          "Instruction marked uniform-after-vectorization will be predicated");
5971 
5972   // Initialize the discount to zero, meaning that the scalar version and the
5973   // vector version cost the same.
5974   int Discount = 0;
5975 
5976   // Holds instructions to analyze. The instructions we visit are mapped in
5977   // ScalarCosts. Those instructions are the ones that would be scalarized if
5978   // we find that the scalar version costs less.
5979   SmallVector<Instruction *, 8> Worklist;
5980 
5981   // Returns true if the given instruction can be scalarized.
5982   auto canBeScalarized = [&](Instruction *I) -> bool {
5983     // We only attempt to scalarize instructions forming a single-use chain
5984     // from the original predicated block that would otherwise be vectorized.
5985     // Although not strictly necessary, we give up on instructions we know will
5986     // already be scalar to avoid traversing chains that are unlikely to be
5987     // beneficial.
5988     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
5989         isScalarAfterVectorization(I, VF))
5990       return false;
5991 
5992     // If the instruction is scalar with predication, it will be analyzed
5993     // separately. We ignore it within the context of PredInst.
5994     if (isScalarWithPredication(I))
5995       return false;
5996 
5997     // If any of the instruction's operands are uniform after vectorization,
5998     // the instruction cannot be scalarized. This prevents, for example, a
5999     // masked load from being scalarized.
6000     //
6001     // We assume we will only emit a value for lane zero of an instruction
6002     // marked uniform after vectorization, rather than VF identical values.
6003     // Thus, if we scalarize an instruction that uses a uniform, we would
6004     // create uses of values corresponding to the lanes we aren't emitting code
6005     // for. This behavior can be changed by allowing getScalarValue to clone
6006     // the lane zero values for uniforms rather than asserting.
6007     for (Use &U : I->operands())
6008       if (auto *J = dyn_cast<Instruction>(U.get()))
6009         if (isUniformAfterVectorization(J, VF))
6010           return false;
6011 
6012     // Otherwise, we can scalarize the instruction.
6013     return true;
6014   };
6015 
6016   // Compute the expected cost discount from scalarizing the entire expression
6017   // feeding the predicated instruction. We currently only consider expressions
6018   // that are single-use instruction chains.
6019   Worklist.push_back(PredInst);
6020   while (!Worklist.empty()) {
6021     Instruction *I = Worklist.pop_back_val();
6022 
6023     // If we've already analyzed the instruction, there's nothing to do.
6024     if (ScalarCosts.find(I) != ScalarCosts.end())
6025       continue;
6026 
6027     // Compute the cost of the vector instruction. Note that this cost already
6028     // includes the scalarization overhead of the predicated instruction.
6029     unsigned VectorCost = getInstructionCost(I, VF).first;
6030 
6031     // Compute the cost of the scalarized instruction. This cost is the cost of
6032     // the instruction as if it wasn't if-converted and instead remained in the
6033     // predicated block. We will scale this cost by block probability after
6034     // computing the scalarization overhead.
6035     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6036     unsigned ScalarCost =
6037         VF.getKnownMinValue() *
6038         getInstructionCost(I, ElementCount::getFixed(1)).first;
6039 
6040     // Compute the scalarization overhead of needed insertelement instructions
6041     // and phi nodes.
6042     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6043       ScalarCost += TTI.getScalarizationOverhead(
6044           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6045           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6046       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6047       ScalarCost +=
6048           VF.getKnownMinValue() *
6049           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6050     }
6051 
6052     // Compute the scalarization overhead of needed extractelement
6053     // instructions. For each of the instruction's operands, if the operand can
6054     // be scalarized, add it to the worklist; otherwise, account for the
6055     // overhead.
6056     for (Use &U : I->operands())
6057       if (auto *J = dyn_cast<Instruction>(U.get())) {
6058         assert(VectorType::isValidElementType(J->getType()) &&
6059                "Instruction has non-scalar type");
6060         if (canBeScalarized(J))
6061           Worklist.push_back(J);
6062         else if (needsExtract(J, VF)) {
6063           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6064           ScalarCost += TTI.getScalarizationOverhead(
6065               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6066               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6067         }
6068       }
6069 
6070     // Scale the total scalar cost by block probability.
6071     ScalarCost /= getReciprocalPredBlockProb();
6072 
6073     // Compute the discount. A non-negative discount means the vector version
6074     // of the instruction costs more, and scalarizing would be beneficial.
6075     Discount += VectorCost - ScalarCost;
6076     ScalarCosts[I] = ScalarCost;
6077   }
6078 
6079   return Discount;
6080 }
6081 
6082 LoopVectorizationCostModel::VectorizationCostTy
6083 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6084   assert(!VF.isScalable() && "scalable vectors not yet supported.");
6085   VectorizationCostTy Cost;
6086 
6087   // For each block.
6088   for (BasicBlock *BB : TheLoop->blocks()) {
6089     VectorizationCostTy BlockCost;
6090 
6091     // For each instruction in the old loop.
6092     for (Instruction &I : BB->instructionsWithoutDebug()) {
6093       // Skip ignored values.
6094       if (ValuesToIgnore.count(&I) ||
6095           (VF.isVector() && VecValuesToIgnore.count(&I)))
6096         continue;
6097 
6098       VectorizationCostTy C = getInstructionCost(&I, VF);
6099 
6100       // Check if we should override the cost.
6101       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6102         C.first = ForceTargetInstructionCost;
6103 
6104       BlockCost.first += C.first;
6105       BlockCost.second |= C.second;
6106       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6107                         << " for VF " << VF << " For instruction: " << I
6108                         << '\n');
6109     }
6110 
6111     // If we are vectorizing a predicated block, it will have been
6112     // if-converted. This means that the block's instructions (aside from
6113     // stores and instructions that may divide by zero) will now be
6114     // unconditionally executed. For the scalar case, we may not always execute
6115     // the predicated block. Thus, scale the block's cost by the probability of
6116     // executing it.
6117     if (VF.isScalar() && blockNeedsPredication(BB))
6118       BlockCost.first /= getReciprocalPredBlockProb();
6119 
6120     Cost.first += BlockCost.first;
6121     Cost.second |= BlockCost.second;
6122   }
6123 
6124   return Cost;
6125 }
6126 
6127 /// Gets Address Access SCEV after verifying that the access pattern
6128 /// is loop invariant except the induction variable dependence.
6129 ///
6130 /// This SCEV can be sent to the Target in order to estimate the address
6131 /// calculation cost.
6132 static const SCEV *getAddressAccessSCEV(
6133               Value *Ptr,
6134               LoopVectorizationLegality *Legal,
6135               PredicatedScalarEvolution &PSE,
6136               const Loop *TheLoop) {
6137 
6138   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6139   if (!Gep)
6140     return nullptr;
6141 
6142   // We are looking for a gep with all loop invariant indices except for one
6143   // which should be an induction variable.
6144   auto SE = PSE.getSE();
6145   unsigned NumOperands = Gep->getNumOperands();
6146   for (unsigned i = 1; i < NumOperands; ++i) {
6147     Value *Opd = Gep->getOperand(i);
6148     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6149         !Legal->isInductionVariable(Opd))
6150       return nullptr;
6151   }
6152 
6153   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6154   return PSE.getSCEV(Ptr);
6155 }
6156 
6157 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6158   return Legal->hasStride(I->getOperand(0)) ||
6159          Legal->hasStride(I->getOperand(1));
6160 }
6161 
6162 unsigned
6163 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6164                                                         ElementCount VF) {
6165   assert(VF.isVector() &&
6166          "Scalarization cost of instruction implies vectorization.");
6167   assert(!VF.isScalable() && "scalable vectors not yet supported.");
6168   Type *ValTy = getMemInstValueType(I);
6169   auto SE = PSE.getSE();
6170 
6171   unsigned AS = getLoadStoreAddressSpace(I);
6172   Value *Ptr = getLoadStorePointerOperand(I);
6173   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6174 
6175   // Figure out whether the access is strided and get the stride value
6176   // if it's known in compile time
6177   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6178 
6179   // Get the cost of the scalar memory instruction and address computation.
6180   unsigned Cost =
6181       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6182 
6183   // Don't pass *I here, since it is scalar but will actually be part of a
6184   // vectorized loop where the user of it is a vectorized instruction.
6185   const Align Alignment = getLoadStoreAlignment(I);
6186   Cost += VF.getKnownMinValue() *
6187           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6188                               AS, TTI::TCK_RecipThroughput);
6189 
6190   // Get the overhead of the extractelement and insertelement instructions
6191   // we might create due to scalarization.
6192   Cost += getScalarizationOverhead(I, VF);
6193 
6194   // If we have a predicated store, it may not be executed for each vector
6195   // lane. Scale the cost by the probability of executing the predicated
6196   // block.
6197   if (isPredicatedInst(I)) {
6198     Cost /= getReciprocalPredBlockProb();
6199 
6200     if (useEmulatedMaskMemRefHack(I))
6201       // Artificially setting to a high enough value to practically disable
6202       // vectorization with such operations.
6203       Cost = 3000000;
6204   }
6205 
6206   return Cost;
6207 }
6208 
6209 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6210                                                              ElementCount VF) {
6211   Type *ValTy = getMemInstValueType(I);
6212   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6213   Value *Ptr = getLoadStorePointerOperand(I);
6214   unsigned AS = getLoadStoreAddressSpace(I);
6215   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6216   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6217 
6218   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6219          "Stride should be 1 or -1 for consecutive memory access");
6220   const Align Alignment = getLoadStoreAlignment(I);
6221   unsigned Cost = 0;
6222   if (Legal->isMaskRequired(I))
6223     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6224                                       CostKind);
6225   else
6226     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6227                                 CostKind, I);
6228 
6229   bool Reverse = ConsecutiveStride < 0;
6230   if (Reverse)
6231     Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6232   return Cost;
6233 }
6234 
6235 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6236                                                          ElementCount VF) {
6237   Type *ValTy = getMemInstValueType(I);
6238   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6239   const Align Alignment = getLoadStoreAlignment(I);
6240   unsigned AS = getLoadStoreAddressSpace(I);
6241   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6242   if (isa<LoadInst>(I)) {
6243     return TTI.getAddressComputationCost(ValTy) +
6244            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6245                                CostKind) +
6246            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6247   }
6248   StoreInst *SI = cast<StoreInst>(I);
6249 
6250   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6251   return TTI.getAddressComputationCost(ValTy) +
6252          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6253                              CostKind) +
6254          (isLoopInvariantStoreValue
6255               ? 0
6256               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6257                                        VF.getKnownMinValue() - 1));
6258 }
6259 
6260 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6261                                                           ElementCount VF) {
6262   Type *ValTy = getMemInstValueType(I);
6263   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6264   const Align Alignment = getLoadStoreAlignment(I);
6265   const Value *Ptr = getLoadStorePointerOperand(I);
6266 
6267   return TTI.getAddressComputationCost(VectorTy) +
6268          TTI.getGatherScatterOpCost(
6269              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6270              TargetTransformInfo::TCK_RecipThroughput, I);
6271 }
6272 
6273 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6274                                                             ElementCount VF) {
6275   Type *ValTy = getMemInstValueType(I);
6276   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6277   unsigned AS = getLoadStoreAddressSpace(I);
6278 
6279   auto Group = getInterleavedAccessGroup(I);
6280   assert(Group && "Fail to get an interleaved access group.");
6281 
6282   unsigned InterleaveFactor = Group->getFactor();
6283   assert(!VF.isScalable() && "scalable vectors not yet supported.");
6284   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6285 
6286   // Holds the indices of existing members in an interleaved load group.
6287   // An interleaved store group doesn't need this as it doesn't allow gaps.
6288   SmallVector<unsigned, 4> Indices;
6289   if (isa<LoadInst>(I)) {
6290     for (unsigned i = 0; i < InterleaveFactor; i++)
6291       if (Group->getMember(i))
6292         Indices.push_back(i);
6293   }
6294 
6295   // Calculate the cost of the whole interleaved group.
6296   bool UseMaskForGaps =
6297       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
6298   unsigned Cost = TTI.getInterleavedMemoryOpCost(
6299       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6300       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6301 
6302   if (Group->isReverse()) {
6303     // TODO: Add support for reversed masked interleaved access.
6304     assert(!Legal->isMaskRequired(I) &&
6305            "Reverse masked interleaved access not supported.");
6306     Cost += Group->getNumMembers() *
6307             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6308   }
6309   return Cost;
6310 }
6311 
6312 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6313                                                               ElementCount VF) {
6314   // Calculate scalar cost only. Vectorization cost should be ready at this
6315   // moment.
6316   if (VF.isScalar()) {
6317     Type *ValTy = getMemInstValueType(I);
6318     const Align Alignment = getLoadStoreAlignment(I);
6319     unsigned AS = getLoadStoreAddressSpace(I);
6320 
6321     return TTI.getAddressComputationCost(ValTy) +
6322            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6323                                TTI::TCK_RecipThroughput, I);
6324   }
6325   return getWideningCost(I, VF);
6326 }
6327 
6328 LoopVectorizationCostModel::VectorizationCostTy
6329 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6330                                                ElementCount VF) {
6331   assert(!VF.isScalable() &&
6332          "the cost model is not yet implemented for scalable vectorization");
6333   // If we know that this instruction will remain uniform, check the cost of
6334   // the scalar version.
6335   if (isUniformAfterVectorization(I, VF))
6336     VF = ElementCount::getFixed(1);
6337 
6338   if (VF.isVector() && isProfitableToScalarize(I, VF))
6339     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6340 
6341   // Forced scalars do not have any scalarization overhead.
6342   auto ForcedScalar = ForcedScalars.find(VF);
6343   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6344     auto InstSet = ForcedScalar->second;
6345     if (InstSet.count(I))
6346       return VectorizationCostTy(
6347           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6348            VF.getKnownMinValue()),
6349           false);
6350   }
6351 
6352   Type *VectorTy;
6353   unsigned C = getInstructionCost(I, VF, VectorTy);
6354 
6355   bool TypeNotScalarized =
6356       VF.isVector() && VectorTy->isVectorTy() &&
6357       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
6358   return VectorizationCostTy(C, TypeNotScalarized);
6359 }
6360 
6361 unsigned LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6362                                                               ElementCount VF) {
6363 
6364   assert(!VF.isScalable() &&
6365          "cannot compute scalarization overhead for scalable vectorization");
6366   if (VF.isScalar())
6367     return 0;
6368 
6369   unsigned Cost = 0;
6370   Type *RetTy = ToVectorTy(I->getType(), VF);
6371   if (!RetTy->isVoidTy() &&
6372       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6373     Cost += TTI.getScalarizationOverhead(
6374         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
6375         true, false);
6376 
6377   // Some targets keep addresses scalar.
6378   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6379     return Cost;
6380 
6381   // Some targets support efficient element stores.
6382   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6383     return Cost;
6384 
6385   // Collect operands to consider.
6386   CallInst *CI = dyn_cast<CallInst>(I);
6387   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
6388 
6389   // Skip operands that do not require extraction/scalarization and do not incur
6390   // any overhead.
6391   return Cost + TTI.getOperandsScalarizationOverhead(
6392                     filterExtractingOperands(Ops, VF), VF.getKnownMinValue());
6393 }
6394 
6395 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6396   assert(!VF.isScalable() && "scalable vectors not yet supported.");
6397   if (VF.isScalar())
6398     return;
6399   NumPredStores = 0;
6400   for (BasicBlock *BB : TheLoop->blocks()) {
6401     // For each instruction in the old loop.
6402     for (Instruction &I : *BB) {
6403       Value *Ptr =  getLoadStorePointerOperand(&I);
6404       if (!Ptr)
6405         continue;
6406 
6407       // TODO: We should generate better code and update the cost model for
6408       // predicated uniform stores. Today they are treated as any other
6409       // predicated store (see added test cases in
6410       // invariant-store-vectorization.ll).
6411       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
6412         NumPredStores++;
6413 
6414       if (Legal->isUniform(Ptr) &&
6415           // Conditional loads and stores should be scalarized and predicated.
6416           // isScalarWithPredication cannot be used here since masked
6417           // gather/scatters are not considered scalar with predication.
6418           !Legal->blockNeedsPredication(I.getParent())) {
6419         // TODO: Avoid replicating loads and stores instead of
6420         // relying on instcombine to remove them.
6421         // Load: Scalar load + broadcast
6422         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6423         unsigned Cost = getUniformMemOpCost(&I, VF);
6424         setWideningDecision(&I, VF, CM_Scalarize, Cost);
6425         continue;
6426       }
6427 
6428       // We assume that widening is the best solution when possible.
6429       if (memoryInstructionCanBeWidened(&I, VF)) {
6430         unsigned Cost = getConsecutiveMemOpCost(&I, VF);
6431         int ConsecutiveStride =
6432                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
6433         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6434                "Expected consecutive stride.");
6435         InstWidening Decision =
6436             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6437         setWideningDecision(&I, VF, Decision, Cost);
6438         continue;
6439       }
6440 
6441       // Choose between Interleaving, Gather/Scatter or Scalarization.
6442       unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
6443       unsigned NumAccesses = 1;
6444       if (isAccessInterleaved(&I)) {
6445         auto Group = getInterleavedAccessGroup(&I);
6446         assert(Group && "Fail to get an interleaved access group.");
6447 
6448         // Make one decision for the whole group.
6449         if (getWideningDecision(&I, VF) != CM_Unknown)
6450           continue;
6451 
6452         NumAccesses = Group->getNumMembers();
6453         if (interleavedAccessCanBeWidened(&I, VF))
6454           InterleaveCost = getInterleaveGroupCost(&I, VF);
6455       }
6456 
6457       unsigned GatherScatterCost =
6458           isLegalGatherOrScatter(&I)
6459               ? getGatherScatterCost(&I, VF) * NumAccesses
6460               : std::numeric_limits<unsigned>::max();
6461 
6462       unsigned ScalarizationCost =
6463           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6464 
6465       // Choose better solution for the current VF,
6466       // write down this decision and use it during vectorization.
6467       unsigned Cost;
6468       InstWidening Decision;
6469       if (InterleaveCost <= GatherScatterCost &&
6470           InterleaveCost < ScalarizationCost) {
6471         Decision = CM_Interleave;
6472         Cost = InterleaveCost;
6473       } else if (GatherScatterCost < ScalarizationCost) {
6474         Decision = CM_GatherScatter;
6475         Cost = GatherScatterCost;
6476       } else {
6477         Decision = CM_Scalarize;
6478         Cost = ScalarizationCost;
6479       }
6480       // If the instructions belongs to an interleave group, the whole group
6481       // receives the same decision. The whole group receives the cost, but
6482       // the cost will actually be assigned to one instruction.
6483       if (auto Group = getInterleavedAccessGroup(&I))
6484         setWideningDecision(Group, VF, Decision, Cost);
6485       else
6486         setWideningDecision(&I, VF, Decision, Cost);
6487     }
6488   }
6489 
6490   // Make sure that any load of address and any other address computation
6491   // remains scalar unless there is gather/scatter support. This avoids
6492   // inevitable extracts into address registers, and also has the benefit of
6493   // activating LSR more, since that pass can't optimize vectorized
6494   // addresses.
6495   if (TTI.prefersVectorizedAddressing())
6496     return;
6497 
6498   // Start with all scalar pointer uses.
6499   SmallPtrSet<Instruction *, 8> AddrDefs;
6500   for (BasicBlock *BB : TheLoop->blocks())
6501     for (Instruction &I : *BB) {
6502       Instruction *PtrDef =
6503         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6504       if (PtrDef && TheLoop->contains(PtrDef) &&
6505           getWideningDecision(&I, VF) != CM_GatherScatter)
6506         AddrDefs.insert(PtrDef);
6507     }
6508 
6509   // Add all instructions used to generate the addresses.
6510   SmallVector<Instruction *, 4> Worklist;
6511   for (auto *I : AddrDefs)
6512     Worklist.push_back(I);
6513   while (!Worklist.empty()) {
6514     Instruction *I = Worklist.pop_back_val();
6515     for (auto &Op : I->operands())
6516       if (auto *InstOp = dyn_cast<Instruction>(Op))
6517         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6518             AddrDefs.insert(InstOp).second)
6519           Worklist.push_back(InstOp);
6520   }
6521 
6522   for (auto *I : AddrDefs) {
6523     if (isa<LoadInst>(I)) {
6524       // Setting the desired widening decision should ideally be handled in
6525       // by cost functions, but since this involves the task of finding out
6526       // if the loaded register is involved in an address computation, it is
6527       // instead changed here when we know this is the case.
6528       InstWidening Decision = getWideningDecision(I, VF);
6529       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6530         // Scalarize a widened load of address.
6531         setWideningDecision(
6532             I, VF, CM_Scalarize,
6533             (VF.getKnownMinValue() *
6534              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6535       else if (auto Group = getInterleavedAccessGroup(I)) {
6536         // Scalarize an interleave group of address loads.
6537         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6538           if (Instruction *Member = Group->getMember(I))
6539             setWideningDecision(
6540                 Member, VF, CM_Scalarize,
6541                 (VF.getKnownMinValue() *
6542                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6543         }
6544       }
6545     } else
6546       // Make sure I gets scalarized and a cost estimate without
6547       // scalarization overhead.
6548       ForcedScalars[VF].insert(I);
6549   }
6550 }
6551 
6552 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6553                                                         ElementCount VF,
6554                                                         Type *&VectorTy) {
6555   Type *RetTy = I->getType();
6556   if (canTruncateToMinimalBitwidth(I, VF))
6557     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6558   VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
6559   auto SE = PSE.getSE();
6560   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6561 
6562   // TODO: We need to estimate the cost of intrinsic calls.
6563   switch (I->getOpcode()) {
6564   case Instruction::GetElementPtr:
6565     // We mark this instruction as zero-cost because the cost of GEPs in
6566     // vectorized code depends on whether the corresponding memory instruction
6567     // is scalarized or not. Therefore, we handle GEPs with the memory
6568     // instruction cost.
6569     return 0;
6570   case Instruction::Br: {
6571     // In cases of scalarized and predicated instructions, there will be VF
6572     // predicated blocks in the vectorized loop. Each branch around these
6573     // blocks requires also an extract of its vector compare i1 element.
6574     bool ScalarPredicatedBB = false;
6575     BranchInst *BI = cast<BranchInst>(I);
6576     if (VF.isVector() && BI->isConditional() &&
6577         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
6578          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
6579       ScalarPredicatedBB = true;
6580 
6581     if (ScalarPredicatedBB) {
6582       // Return cost for branches around scalarized and predicated blocks.
6583       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6584       auto *Vec_i1Ty =
6585           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
6586       return (TTI.getScalarizationOverhead(
6587                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
6588                   false, true) +
6589               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
6590                VF.getKnownMinValue()));
6591     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6592       // The back-edge branch will remain, as will all scalar branches.
6593       return TTI.getCFInstrCost(Instruction::Br, CostKind);
6594     else
6595       // This branch will be eliminated by if-conversion.
6596       return 0;
6597     // Note: We currently assume zero cost for an unconditional branch inside
6598     // a predicated block since it will become a fall-through, although we
6599     // may decide in the future to call TTI for all branches.
6600   }
6601   case Instruction::PHI: {
6602     auto *Phi = cast<PHINode>(I);
6603 
6604     // First-order recurrences are replaced by vector shuffles inside the loop.
6605     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
6606     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
6607       return TTI.getShuffleCost(
6608           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
6609           VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
6610 
6611     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
6612     // converted into select instructions. We require N - 1 selects per phi
6613     // node, where N is the number of incoming values.
6614     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
6615       return (Phi->getNumIncomingValues() - 1) *
6616              TTI.getCmpSelInstrCost(
6617                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
6618                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
6619                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
6620 
6621     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
6622   }
6623   case Instruction::UDiv:
6624   case Instruction::SDiv:
6625   case Instruction::URem:
6626   case Instruction::SRem:
6627     // If we have a predicated instruction, it may not be executed for each
6628     // vector lane. Get the scalarization cost and scale this amount by the
6629     // probability of executing the predicated block. If the instruction is not
6630     // predicated, we fall through to the next case.
6631     if (VF.isVector() && isScalarWithPredication(I)) {
6632       unsigned Cost = 0;
6633 
6634       // These instructions have a non-void type, so account for the phi nodes
6635       // that we will create. This cost is likely to be zero. The phi node
6636       // cost, if any, should be scaled by the block probability because it
6637       // models a copy at the end of each predicated block.
6638       Cost += VF.getKnownMinValue() *
6639               TTI.getCFInstrCost(Instruction::PHI, CostKind);
6640 
6641       // The cost of the non-predicated instruction.
6642       Cost += VF.getKnownMinValue() *
6643               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
6644 
6645       // The cost of insertelement and extractelement instructions needed for
6646       // scalarization.
6647       Cost += getScalarizationOverhead(I, VF);
6648 
6649       // Scale the cost by the probability of executing the predicated blocks.
6650       // This assumes the predicated block for each vector lane is equally
6651       // likely.
6652       return Cost / getReciprocalPredBlockProb();
6653     }
6654     LLVM_FALLTHROUGH;
6655   case Instruction::Add:
6656   case Instruction::FAdd:
6657   case Instruction::Sub:
6658   case Instruction::FSub:
6659   case Instruction::Mul:
6660   case Instruction::FMul:
6661   case Instruction::FDiv:
6662   case Instruction::FRem:
6663   case Instruction::Shl:
6664   case Instruction::LShr:
6665   case Instruction::AShr:
6666   case Instruction::And:
6667   case Instruction::Or:
6668   case Instruction::Xor: {
6669     // Since we will replace the stride by 1 the multiplication should go away.
6670     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
6671       return 0;
6672     // Certain instructions can be cheaper to vectorize if they have a constant
6673     // second vector operand. One example of this are shifts on x86.
6674     Value *Op2 = I->getOperand(1);
6675     TargetTransformInfo::OperandValueProperties Op2VP;
6676     TargetTransformInfo::OperandValueKind Op2VK =
6677         TTI.getOperandInfo(Op2, Op2VP);
6678     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
6679       Op2VK = TargetTransformInfo::OK_UniformValue;
6680 
6681     SmallVector<const Value *, 4> Operands(I->operand_values());
6682     unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
6683     return N * TTI.getArithmeticInstrCost(
6684                    I->getOpcode(), VectorTy, CostKind,
6685                    TargetTransformInfo::OK_AnyValue,
6686                    Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
6687   }
6688   case Instruction::FNeg: {
6689     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
6690     unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
6691     return N * TTI.getArithmeticInstrCost(
6692                    I->getOpcode(), VectorTy, CostKind,
6693                    TargetTransformInfo::OK_AnyValue,
6694                    TargetTransformInfo::OK_AnyValue,
6695                    TargetTransformInfo::OP_None, TargetTransformInfo::OP_None,
6696                    I->getOperand(0), I);
6697   }
6698   case Instruction::Select: {
6699     SelectInst *SI = cast<SelectInst>(I);
6700     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6701     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6702     Type *CondTy = SI->getCondition()->getType();
6703     if (!ScalarCond) {
6704       assert(!VF.isScalable() && "VF is assumed to be non scalable.");
6705       CondTy = VectorType::get(CondTy, VF);
6706     }
6707     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
6708                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
6709   }
6710   case Instruction::ICmp:
6711   case Instruction::FCmp: {
6712     Type *ValTy = I->getOperand(0)->getType();
6713     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6714     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6715       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
6716     VectorTy = ToVectorTy(ValTy, VF);
6717     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
6718                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
6719   }
6720   case Instruction::Store:
6721   case Instruction::Load: {
6722     ElementCount Width = VF;
6723     if (Width.isVector()) {
6724       InstWidening Decision = getWideningDecision(I, Width);
6725       assert(Decision != CM_Unknown &&
6726              "CM decision should be taken at this point");
6727       if (Decision == CM_Scalarize)
6728         Width = ElementCount::getFixed(1);
6729     }
6730     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
6731     return getMemoryInstructionCost(I, VF);
6732   }
6733   case Instruction::ZExt:
6734   case Instruction::SExt:
6735   case Instruction::FPToUI:
6736   case Instruction::FPToSI:
6737   case Instruction::FPExt:
6738   case Instruction::PtrToInt:
6739   case Instruction::IntToPtr:
6740   case Instruction::SIToFP:
6741   case Instruction::UIToFP:
6742   case Instruction::Trunc:
6743   case Instruction::FPTrunc:
6744   case Instruction::BitCast: {
6745     // Computes the CastContextHint from a Load/Store instruction.
6746     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
6747       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
6748              "Expected a load or a store!");
6749 
6750       if (VF.isScalar() || !TheLoop->contains(I))
6751         return TTI::CastContextHint::Normal;
6752 
6753       switch (getWideningDecision(I, VF)) {
6754       case LoopVectorizationCostModel::CM_GatherScatter:
6755         return TTI::CastContextHint::GatherScatter;
6756       case LoopVectorizationCostModel::CM_Interleave:
6757         return TTI::CastContextHint::Interleave;
6758       case LoopVectorizationCostModel::CM_Scalarize:
6759       case LoopVectorizationCostModel::CM_Widen:
6760         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
6761                                         : TTI::CastContextHint::Normal;
6762       case LoopVectorizationCostModel::CM_Widen_Reverse:
6763         return TTI::CastContextHint::Reversed;
6764       case LoopVectorizationCostModel::CM_Unknown:
6765         llvm_unreachable("Instr did not go through cost modelling?");
6766       }
6767 
6768       llvm_unreachable("Unhandled case!");
6769     };
6770 
6771     unsigned Opcode = I->getOpcode();
6772     TTI::CastContextHint CCH = TTI::CastContextHint::None;
6773     // For Trunc, the context is the only user, which must be a StoreInst.
6774     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
6775       if (I->hasOneUse())
6776         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
6777           CCH = ComputeCCH(Store);
6778     }
6779     // For Z/Sext, the context is the operand, which must be a LoadInst.
6780     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
6781              Opcode == Instruction::FPExt) {
6782       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
6783         CCH = ComputeCCH(Load);
6784     }
6785 
6786     // We optimize the truncation of induction variables having constant
6787     // integer steps. The cost of these truncations is the same as the scalar
6788     // operation.
6789     if (isOptimizableIVTruncate(I, VF)) {
6790       auto *Trunc = cast<TruncInst>(I);
6791       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
6792                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
6793     }
6794 
6795     Type *SrcScalarTy = I->getOperand(0)->getType();
6796     Type *SrcVecTy =
6797         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
6798     if (canTruncateToMinimalBitwidth(I, VF)) {
6799       // This cast is going to be shrunk. This may remove the cast or it might
6800       // turn it into slightly different cast. For example, if MinBW == 16,
6801       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
6802       //
6803       // Calculate the modified src and dest types.
6804       Type *MinVecTy = VectorTy;
6805       if (Opcode == Instruction::Trunc) {
6806         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
6807         VectorTy =
6808             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6809       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
6810         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
6811         VectorTy =
6812             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
6813       }
6814     }
6815 
6816     assert(!VF.isScalable() && "VF is assumed to be non scalable");
6817     unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
6818     return N *
6819            TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
6820   }
6821   case Instruction::Call: {
6822     bool NeedToScalarize;
6823     CallInst *CI = cast<CallInst>(I);
6824     unsigned CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
6825     if (getVectorIntrinsicIDForCall(CI, TLI))
6826       return std::min(CallCost, getVectorIntrinsicCost(CI, VF));
6827     return CallCost;
6828   }
6829   default:
6830     // The cost of executing VF copies of the scalar instruction. This opcode
6831     // is unknown. Assume that it is the same as 'mul'.
6832     return VF.getKnownMinValue() * TTI.getArithmeticInstrCost(
6833                                        Instruction::Mul, VectorTy, CostKind) +
6834            getScalarizationOverhead(I, VF);
6835   } // end of switch.
6836 }
6837 
6838 char LoopVectorize::ID = 0;
6839 
6840 static const char lv_name[] = "Loop Vectorization";
6841 
6842 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
6843 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6844 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
6845 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6846 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
6847 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6848 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
6849 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
6850 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6851 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
6852 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
6853 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6854 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6855 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
6856 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
6857 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
6858 
6859 namespace llvm {
6860 
6861 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
6862 
6863 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
6864                               bool VectorizeOnlyWhenForced) {
6865   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
6866 }
6867 
6868 } // end namespace llvm
6869 
6870 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
6871   // Check if the pointer operand of a load or store instruction is
6872   // consecutive.
6873   if (auto *Ptr = getLoadStorePointerOperand(Inst))
6874     return Legal->isConsecutivePtr(Ptr);
6875   return false;
6876 }
6877 
6878 void LoopVectorizationCostModel::collectValuesToIgnore() {
6879   // Ignore ephemeral values.
6880   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
6881 
6882   // Ignore type-promoting instructions we identified during reduction
6883   // detection.
6884   for (auto &Reduction : Legal->getReductionVars()) {
6885     RecurrenceDescriptor &RedDes = Reduction.second;
6886     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6887     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
6888   }
6889   // Ignore type-casting instructions we identified during induction
6890   // detection.
6891   for (auto &Induction : Legal->getInductionVars()) {
6892     InductionDescriptor &IndDes = Induction.second;
6893     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
6894     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
6895   }
6896 }
6897 
6898 void LoopVectorizationCostModel::collectInLoopReductions() {
6899   for (auto &Reduction : Legal->getReductionVars()) {
6900     PHINode *Phi = Reduction.first;
6901     RecurrenceDescriptor &RdxDesc = Reduction.second;
6902 
6903     // We don't collect reductions that are type promoted (yet).
6904     if (RdxDesc.getRecurrenceType() != Phi->getType())
6905       continue;
6906 
6907     // If the target would prefer this reduction to happen "in-loop", then we
6908     // want to record it as such.
6909     unsigned Opcode = RdxDesc.getRecurrenceBinOp();
6910     if (!PreferInLoopReductions &&
6911         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
6912                                    TargetTransformInfo::ReductionFlags()))
6913       continue;
6914 
6915     // Check that we can correctly put the reductions into the loop, by
6916     // finding the chain of operations that leads from the phi to the loop
6917     // exit value.
6918     SmallVector<Instruction *, 4> ReductionOperations =
6919         RdxDesc.getReductionOpChain(Phi, TheLoop);
6920     bool InLoop = !ReductionOperations.empty();
6921     if (InLoop)
6922       InLoopReductionChains[Phi] = ReductionOperations;
6923     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
6924                       << " reduction for phi: " << *Phi << "\n");
6925   }
6926 }
6927 
6928 // TODO: we could return a pair of values that specify the max VF and
6929 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
6930 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
6931 // doesn't have a cost model that can choose which plan to execute if
6932 // more than one is generated.
6933 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
6934                                  LoopVectorizationCostModel &CM) {
6935   unsigned WidestType;
6936   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
6937   return WidestVectorRegBits / WidestType;
6938 }
6939 
6940 VectorizationFactor
6941 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
6942   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
6943   ElementCount VF = UserVF;
6944   // Outer loop handling: They may require CFG and instruction level
6945   // transformations before even evaluating whether vectorization is profitable.
6946   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
6947   // the vectorization pipeline.
6948   if (!OrigLoop->isInnermost()) {
6949     // If the user doesn't provide a vectorization factor, determine a
6950     // reasonable one.
6951     if (UserVF.isZero()) {
6952       VF = ElementCount::getFixed(
6953           determineVPlanVF(TTI->getRegisterBitWidth(true /* Vector*/), CM));
6954       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
6955 
6956       // Make sure we have a VF > 1 for stress testing.
6957       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
6958         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
6959                           << "overriding computed VF.\n");
6960         VF = ElementCount::getFixed(4);
6961       }
6962     }
6963     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
6964     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
6965            "VF needs to be a power of two");
6966     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
6967                       << "VF " << VF << " to build VPlans.\n");
6968     buildVPlans(VF, VF);
6969 
6970     // For VPlan build stress testing, we bail out after VPlan construction.
6971     if (VPlanBuildStressTest)
6972       return VectorizationFactor::Disabled();
6973 
6974     return {VF, 0 /*Cost*/};
6975   }
6976 
6977   LLVM_DEBUG(
6978       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
6979                 "VPlan-native path.\n");
6980   return VectorizationFactor::Disabled();
6981 }
6982 
6983 Optional<VectorizationFactor>
6984 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
6985   assert(!UserVF.isScalable() && "scalable vectorization not yet handled");
6986   assert(OrigLoop->isInnermost() && "Inner loop expected.");
6987   Optional<unsigned> MaybeMaxVF =
6988       CM.computeMaxVF(UserVF.getKnownMinValue(), UserIC);
6989   if (!MaybeMaxVF) // Cases that should not to be vectorized nor interleaved.
6990     return None;
6991 
6992   // Invalidate interleave groups if all blocks of loop will be predicated.
6993   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
6994       !useMaskedInterleavedAccesses(*TTI)) {
6995     LLVM_DEBUG(
6996         dbgs()
6997         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
6998            "which requires masked-interleaved support.\n");
6999     if (CM.InterleaveInfo.invalidateGroups())
7000       // Invalidating interleave groups also requires invalidating all decisions
7001       // based on them, which includes widening decisions and uniform and scalar
7002       // values.
7003       CM.invalidateCostModelingDecisions();
7004   }
7005 
7006   if (!UserVF.isZero()) {
7007     LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7008     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7009            "VF needs to be a power of two");
7010     // Collect the instructions (and their associated costs) that will be more
7011     // profitable to scalarize.
7012     CM.selectUserVectorizationFactor(UserVF);
7013     CM.collectInLoopReductions();
7014     buildVPlansWithVPRecipes(UserVF, UserVF);
7015     LLVM_DEBUG(printPlans(dbgs()));
7016     return {{UserVF, 0}};
7017   }
7018 
7019   ElementCount MaxVF = ElementCount::getFixed(MaybeMaxVF.getValue());
7020   assert(MaxVF.isNonZero() && "MaxVF is zero.");
7021 
7022   for (ElementCount VF = ElementCount::getFixed(1);
7023        ElementCount::isKnownLE(VF, MaxVF); VF *= 2) {
7024     // Collect Uniform and Scalar instructions after vectorization with VF.
7025     CM.collectUniformsAndScalars(VF);
7026 
7027     // Collect the instructions (and their associated costs) that will be more
7028     // profitable to scalarize.
7029     if (VF.isVector())
7030       CM.collectInstsToScalarize(VF);
7031   }
7032 
7033   CM.collectInLoopReductions();
7034 
7035   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxVF);
7036   LLVM_DEBUG(printPlans(dbgs()));
7037   if (MaxVF.isScalar())
7038     return VectorizationFactor::Disabled();
7039 
7040   // Select the optimal vectorization factor.
7041   return CM.selectVectorizationFactor(MaxVF);
7042 }
7043 
7044 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
7045   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
7046                     << '\n');
7047   BestVF = VF;
7048   BestUF = UF;
7049 
7050   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
7051     return !Plan->hasVF(VF);
7052   });
7053   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
7054 }
7055 
7056 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
7057                                            DominatorTree *DT) {
7058   // Perform the actual loop transformation.
7059 
7060   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7061   VPCallbackILV CallbackILV(ILV);
7062 
7063   assert(BestVF.hasValue() && "Vectorization Factor is missing");
7064 
7065   VPTransformState State{*BestVF, BestUF,      LI,
7066                          DT,      ILV.Builder, ILV.VectorLoopValueMap,
7067                          &ILV,    CallbackILV};
7068   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7069   State.TripCount = ILV.getOrCreateTripCount(nullptr);
7070   State.CanonicalIV = ILV.Induction;
7071 
7072   //===------------------------------------------------===//
7073   //
7074   // Notice: any optimization or new instruction that go
7075   // into the code below should also be implemented in
7076   // the cost-model.
7077   //
7078   //===------------------------------------------------===//
7079 
7080   // 2. Copy and widen instructions from the old loop into the new loop.
7081   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
7082   VPlans.front()->execute(&State);
7083 
7084   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7085   //    predication, updating analyses.
7086   ILV.fixVectorizedLoop();
7087 }
7088 
7089 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7090     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7091   BasicBlock *Latch = OrigLoop->getLoopLatch();
7092 
7093   // We create new control-flow for the vectorized loop, so the original
7094   // condition will be dead after vectorization if it's only used by the
7095   // branch.
7096   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
7097   if (Cmp && Cmp->hasOneUse()) {
7098     DeadInstructions.insert(Cmp);
7099 
7100     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7101     for (Value *Op : Cmp->operands()) {
7102       if (isa<TruncInst>(Op) && Op->hasOneUse())
7103           DeadInstructions.insert(cast<Instruction>(Op));
7104     }
7105   }
7106 
7107   // We create new "steps" for induction variable updates to which the original
7108   // induction variables map. An original update instruction will be dead if
7109   // all its users except the induction variable are dead.
7110   for (auto &Induction : Legal->getInductionVars()) {
7111     PHINode *Ind = Induction.first;
7112     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7113     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7114           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7115         }))
7116       DeadInstructions.insert(IndUpdate);
7117 
7118     // We record as "Dead" also the type-casting instructions we had identified
7119     // during induction analysis. We don't need any handling for them in the
7120     // vectorized loop because we have proven that, under a proper runtime
7121     // test guarding the vectorized loop, the value of the phi, and the casted
7122     // value of the phi, are the same. The last instruction in this casting chain
7123     // will get its scalar/vector/widened def from the scalar/vector/widened def
7124     // of the respective phi node. Any other casts in the induction def-use chain
7125     // have no other uses outside the phi update chain, and will be ignored.
7126     InductionDescriptor &IndDes = Induction.second;
7127     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7128     DeadInstructions.insert(Casts.begin(), Casts.end());
7129   }
7130 }
7131 
7132 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7133 
7134 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7135 
7136 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7137                                         Instruction::BinaryOps BinOp) {
7138   // When unrolling and the VF is 1, we only need to add a simple scalar.
7139   Type *Ty = Val->getType();
7140   assert(!Ty->isVectorTy() && "Val must be a scalar");
7141 
7142   if (Ty->isFloatingPointTy()) {
7143     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7144 
7145     // Floating point operations had to be 'fast' to enable the unrolling.
7146     Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7147     return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7148   }
7149   Constant *C = ConstantInt::get(Ty, StartIdx);
7150   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7151 }
7152 
7153 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7154   SmallVector<Metadata *, 4> MDs;
7155   // Reserve first location for self reference to the LoopID metadata node.
7156   MDs.push_back(nullptr);
7157   bool IsUnrollMetadata = false;
7158   MDNode *LoopID = L->getLoopID();
7159   if (LoopID) {
7160     // First find existing loop unrolling disable metadata.
7161     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7162       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7163       if (MD) {
7164         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7165         IsUnrollMetadata =
7166             S && S->getString().startswith("llvm.loop.unroll.disable");
7167       }
7168       MDs.push_back(LoopID->getOperand(i));
7169     }
7170   }
7171 
7172   if (!IsUnrollMetadata) {
7173     // Add runtime unroll disable metadata.
7174     LLVMContext &Context = L->getHeader()->getContext();
7175     SmallVector<Metadata *, 1> DisableOperands;
7176     DisableOperands.push_back(
7177         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7178     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7179     MDs.push_back(DisableNode);
7180     MDNode *NewLoopID = MDNode::get(Context, MDs);
7181     // Set operand 0 to refer to the loop id itself.
7182     NewLoopID->replaceOperandWith(0, NewLoopID);
7183     L->setLoopID(NewLoopID);
7184   }
7185 }
7186 
7187 bool LoopVectorizationPlanner::getDecisionAndClampRange(
7188     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
7189   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
7190   bool PredicateAtRangeStart = Predicate(Range.Start);
7191 
7192   for (ElementCount TmpVF = Range.Start * 2;
7193        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
7194     if (Predicate(TmpVF) != PredicateAtRangeStart) {
7195       Range.End = TmpVF;
7196       break;
7197     }
7198 
7199   return PredicateAtRangeStart;
7200 }
7201 
7202 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
7203 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
7204 /// of VF's starting at a given VF and extending it as much as possible. Each
7205 /// vectorization decision can potentially shorten this sub-range during
7206 /// buildVPlan().
7207 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
7208                                            ElementCount MaxVF) {
7209   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
7210   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
7211     VFRange SubRange = {VF, MaxVFPlusOne};
7212     VPlans.push_back(buildVPlan(SubRange));
7213     VF = SubRange.End;
7214   }
7215 }
7216 
7217 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
7218                                          VPlanPtr &Plan) {
7219   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
7220 
7221   // Look for cached value.
7222   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7223   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
7224   if (ECEntryIt != EdgeMaskCache.end())
7225     return ECEntryIt->second;
7226 
7227   VPValue *SrcMask = createBlockInMask(Src, Plan);
7228 
7229   // The terminator has to be a branch inst!
7230   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
7231   assert(BI && "Unexpected terminator found");
7232 
7233   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
7234     return EdgeMaskCache[Edge] = SrcMask;
7235 
7236   VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
7237   assert(EdgeMask && "No Edge Mask found for condition");
7238 
7239   if (BI->getSuccessor(0) != Dst)
7240     EdgeMask = Builder.createNot(EdgeMask);
7241 
7242   if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
7243     EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
7244 
7245   return EdgeMaskCache[Edge] = EdgeMask;
7246 }
7247 
7248 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
7249   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
7250 
7251   // Look for cached value.
7252   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
7253   if (BCEntryIt != BlockMaskCache.end())
7254     return BCEntryIt->second;
7255 
7256   // All-one mask is modelled as no-mask following the convention for masked
7257   // load/store/gather/scatter. Initialize BlockMask to no-mask.
7258   VPValue *BlockMask = nullptr;
7259 
7260   if (OrigLoop->getHeader() == BB) {
7261     if (!CM.blockNeedsPredication(BB))
7262       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
7263 
7264     // Create the block in mask as the first non-phi instruction in the block.
7265     VPBuilder::InsertPointGuard Guard(Builder);
7266     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
7267     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
7268 
7269     // Introduce the early-exit compare IV <= BTC to form header block mask.
7270     // This is used instead of IV < TC because TC may wrap, unlike BTC.
7271     // Start by constructing the desired canonical IV.
7272     VPValue *IV = nullptr;
7273     if (Legal->getPrimaryInduction())
7274       IV = Plan->getVPValue(Legal->getPrimaryInduction());
7275     else {
7276       auto IVRecipe = new VPWidenCanonicalIVRecipe();
7277       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
7278       IV = IVRecipe->getVPValue();
7279     }
7280     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
7281     bool TailFolded = !CM.isScalarEpilogueAllowed();
7282 
7283     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
7284       // While ActiveLaneMask is a binary op that consumes the loop tripcount
7285       // as a second argument, we only pass the IV here and extract the
7286       // tripcount from the transform state where codegen of the VP instructions
7287       // happen.
7288       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
7289     } else {
7290       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
7291     }
7292     return BlockMaskCache[BB] = BlockMask;
7293   }
7294 
7295   // This is the block mask. We OR all incoming edges.
7296   for (auto *Predecessor : predecessors(BB)) {
7297     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
7298     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
7299       return BlockMaskCache[BB] = EdgeMask;
7300 
7301     if (!BlockMask) { // BlockMask has its initialized nullptr value.
7302       BlockMask = EdgeMask;
7303       continue;
7304     }
7305 
7306     BlockMask = Builder.createOr(BlockMask, EdgeMask);
7307   }
7308 
7309   return BlockMaskCache[BB] = BlockMask;
7310 }
7311 
7312 VPWidenMemoryInstructionRecipe *
7313 VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
7314                                   VPlanPtr &Plan) {
7315   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7316          "Must be called with either a load or store");
7317 
7318   auto willWiden = [&](ElementCount VF) -> bool {
7319     assert(!VF.isScalable() && "unexpected scalable ElementCount");
7320     if (VF.isScalar())
7321       return false;
7322     LoopVectorizationCostModel::InstWidening Decision =
7323         CM.getWideningDecision(I, VF);
7324     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
7325            "CM decision should be taken at this point.");
7326     if (Decision == LoopVectorizationCostModel::CM_Interleave)
7327       return true;
7328     if (CM.isScalarAfterVectorization(I, VF) ||
7329         CM.isProfitableToScalarize(I, VF))
7330       return false;
7331     return Decision != LoopVectorizationCostModel::CM_Scalarize;
7332   };
7333 
7334   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
7335     return nullptr;
7336 
7337   VPValue *Mask = nullptr;
7338   if (Legal->isMaskRequired(I))
7339     Mask = createBlockInMask(I->getParent(), Plan);
7340 
7341   VPValue *Addr = Plan->getOrAddVPValue(getLoadStorePointerOperand(I));
7342   if (LoadInst *Load = dyn_cast<LoadInst>(I))
7343     return new VPWidenMemoryInstructionRecipe(*Load, Addr, Mask);
7344 
7345   StoreInst *Store = cast<StoreInst>(I);
7346   VPValue *StoredValue = Plan->getOrAddVPValue(Store->getValueOperand());
7347   return new VPWidenMemoryInstructionRecipe(*Store, Addr, StoredValue, Mask);
7348 }
7349 
7350 VPWidenIntOrFpInductionRecipe *
7351 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi) const {
7352   // Check if this is an integer or fp induction. If so, build the recipe that
7353   // produces its scalar and vector values.
7354   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
7355   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
7356       II.getKind() == InductionDescriptor::IK_FpInduction)
7357     return new VPWidenIntOrFpInductionRecipe(Phi);
7358 
7359   return nullptr;
7360 }
7361 
7362 VPWidenIntOrFpInductionRecipe *
7363 VPRecipeBuilder::tryToOptimizeInductionTruncate(TruncInst *I,
7364                                                 VFRange &Range) const {
7365   // Optimize the special case where the source is a constant integer
7366   // induction variable. Notice that we can only optimize the 'trunc' case
7367   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7368   // (c) other casts depend on pointer size.
7369 
7370   // Determine whether \p K is a truncation based on an induction variable that
7371   // can be optimized.
7372   auto isOptimizableIVTruncate =
7373       [&](Instruction *K) -> std::function<bool(ElementCount)> {
7374     return [=](ElementCount VF) -> bool {
7375       return CM.isOptimizableIVTruncate(K, VF);
7376     };
7377   };
7378 
7379   if (LoopVectorizationPlanner::getDecisionAndClampRange(
7380           isOptimizableIVTruncate(I), Range))
7381     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
7382                                              I);
7383   return nullptr;
7384 }
7385 
7386 VPBlendRecipe *VPRecipeBuilder::tryToBlend(PHINode *Phi, VPlanPtr &Plan) {
7387   // We know that all PHIs in non-header blocks are converted into selects, so
7388   // we don't have to worry about the insertion order and we can just use the
7389   // builder. At this point we generate the predication tree. There may be
7390   // duplications since this is a simple recursive scan, but future
7391   // optimizations will clean it up.
7392 
7393   SmallVector<VPValue *, 2> Operands;
7394   unsigned NumIncoming = Phi->getNumIncomingValues();
7395   for (unsigned In = 0; In < NumIncoming; In++) {
7396     VPValue *EdgeMask =
7397       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
7398     assert((EdgeMask || NumIncoming == 1) &&
7399            "Multiple predecessors with one having a full mask");
7400     Operands.push_back(Plan->getOrAddVPValue(Phi->getIncomingValue(In)));
7401     if (EdgeMask)
7402       Operands.push_back(EdgeMask);
7403   }
7404   return new VPBlendRecipe(Phi, Operands);
7405 }
7406 
7407 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI, VFRange &Range,
7408                                                    VPlan &Plan) const {
7409 
7410   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
7411       [this, CI](ElementCount VF) {
7412         return CM.isScalarWithPredication(CI, VF);
7413       },
7414       Range);
7415 
7416   if (IsPredicated)
7417     return nullptr;
7418 
7419   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7420   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7421              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
7422     return nullptr;
7423 
7424   auto willWiden = [&](ElementCount VF) -> bool {
7425     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7426     // The following case may be scalarized depending on the VF.
7427     // The flag shows whether we use Intrinsic or a usual Call for vectorized
7428     // version of the instruction.
7429     // Is it beneficial to perform intrinsic call compared to lib call?
7430     bool NeedToScalarize = false;
7431     unsigned CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
7432     bool UseVectorIntrinsic =
7433         ID && CM.getVectorIntrinsicCost(CI, VF) <= CallCost;
7434     return UseVectorIntrinsic || !NeedToScalarize;
7435   };
7436 
7437   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
7438     return nullptr;
7439 
7440   return new VPWidenCallRecipe(*CI, Plan.mapToVPValues(CI->arg_operands()));
7441 }
7442 
7443 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
7444   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
7445          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
7446   // Instruction should be widened, unless it is scalar after vectorization,
7447   // scalarization is profitable or it is predicated.
7448   auto WillScalarize = [this, I](ElementCount VF) -> bool {
7449     return CM.isScalarAfterVectorization(I, VF) ||
7450            CM.isProfitableToScalarize(I, VF) ||
7451            CM.isScalarWithPredication(I, VF);
7452   };
7453   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
7454                                                              Range);
7455 }
7456 
7457 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I, VPlan &Plan) const {
7458   auto IsVectorizableOpcode = [](unsigned Opcode) {
7459     switch (Opcode) {
7460     case Instruction::Add:
7461     case Instruction::And:
7462     case Instruction::AShr:
7463     case Instruction::BitCast:
7464     case Instruction::FAdd:
7465     case Instruction::FCmp:
7466     case Instruction::FDiv:
7467     case Instruction::FMul:
7468     case Instruction::FNeg:
7469     case Instruction::FPExt:
7470     case Instruction::FPToSI:
7471     case Instruction::FPToUI:
7472     case Instruction::FPTrunc:
7473     case Instruction::FRem:
7474     case Instruction::FSub:
7475     case Instruction::ICmp:
7476     case Instruction::IntToPtr:
7477     case Instruction::LShr:
7478     case Instruction::Mul:
7479     case Instruction::Or:
7480     case Instruction::PtrToInt:
7481     case Instruction::SDiv:
7482     case Instruction::Select:
7483     case Instruction::SExt:
7484     case Instruction::Shl:
7485     case Instruction::SIToFP:
7486     case Instruction::SRem:
7487     case Instruction::Sub:
7488     case Instruction::Trunc:
7489     case Instruction::UDiv:
7490     case Instruction::UIToFP:
7491     case Instruction::URem:
7492     case Instruction::Xor:
7493     case Instruction::ZExt:
7494       return true;
7495     }
7496     return false;
7497   };
7498 
7499   if (!IsVectorizableOpcode(I->getOpcode()))
7500     return nullptr;
7501 
7502   // Success: widen this instruction.
7503   return new VPWidenRecipe(*I, Plan.mapToVPValues(I->operands()));
7504 }
7505 
7506 VPBasicBlock *VPRecipeBuilder::handleReplication(
7507     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
7508     DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
7509     VPlanPtr &Plan) {
7510   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
7511       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
7512       Range);
7513 
7514   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
7515       [&](ElementCount VF) { return CM.isScalarWithPredication(I, VF); },
7516       Range);
7517 
7518   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
7519                                        IsUniform, IsPredicated);
7520   setRecipe(I, Recipe);
7521 
7522   // Find if I uses a predicated instruction. If so, it will use its scalar
7523   // value. Avoid hoisting the insert-element which packs the scalar value into
7524   // a vector value, as that happens iff all users use the vector value.
7525   for (auto &Op : I->operands())
7526     if (auto *PredInst = dyn_cast<Instruction>(Op))
7527       if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
7528         PredInst2Recipe[PredInst]->setAlsoPack(false);
7529 
7530   // Finalize the recipe for Instr, first if it is not predicated.
7531   if (!IsPredicated) {
7532     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
7533     VPBB->appendRecipe(Recipe);
7534     return VPBB;
7535   }
7536   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
7537   assert(VPBB->getSuccessors().empty() &&
7538          "VPBB has successors when handling predicated replication.");
7539   // Record predicated instructions for above packing optimizations.
7540   PredInst2Recipe[I] = Recipe;
7541   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
7542   VPBlockUtils::insertBlockAfter(Region, VPBB);
7543   auto *RegSucc = new VPBasicBlock();
7544   VPBlockUtils::insertBlockAfter(RegSucc, Region);
7545   return RegSucc;
7546 }
7547 
7548 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
7549                                                       VPRecipeBase *PredRecipe,
7550                                                       VPlanPtr &Plan) {
7551   // Instructions marked for predication are replicated and placed under an
7552   // if-then construct to prevent side-effects.
7553 
7554   // Generate recipes to compute the block mask for this region.
7555   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
7556 
7557   // Build the triangular if-then region.
7558   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
7559   assert(Instr->getParent() && "Predicated instruction not in any basic block");
7560   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
7561   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
7562   auto *PHIRecipe =
7563       Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
7564   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
7565   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
7566   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
7567 
7568   // Note: first set Entry as region entry and then connect successors starting
7569   // from it in order, to propagate the "parent" of each VPBasicBlock.
7570   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
7571   VPBlockUtils::connectBlocks(Pred, Exit);
7572 
7573   return Region;
7574 }
7575 
7576 VPRecipeBase *VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
7577                                                       VFRange &Range,
7578                                                       VPlanPtr &Plan) {
7579   // First, check for specific widening recipes that deal with calls, memory
7580   // operations, inductions and Phi nodes.
7581   if (auto *CI = dyn_cast<CallInst>(Instr))
7582     return tryToWidenCall(CI, Range, *Plan);
7583 
7584   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
7585     return tryToWidenMemory(Instr, Range, Plan);
7586 
7587   VPRecipeBase *Recipe;
7588   if (auto Phi = dyn_cast<PHINode>(Instr)) {
7589     if (Phi->getParent() != OrigLoop->getHeader())
7590       return tryToBlend(Phi, Plan);
7591     if ((Recipe = tryToOptimizeInductionPHI(Phi)))
7592       return Recipe;
7593     return new VPWidenPHIRecipe(Phi);
7594   }
7595 
7596   if (isa<TruncInst>(Instr) &&
7597       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Range)))
7598     return Recipe;
7599 
7600   if (!shouldWiden(Instr, Range))
7601     return nullptr;
7602 
7603   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
7604     return new VPWidenGEPRecipe(GEP, Plan->mapToVPValues(GEP->operands()),
7605                                 OrigLoop);
7606 
7607   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
7608     bool InvariantCond =
7609         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
7610     return new VPWidenSelectRecipe(*SI, Plan->mapToVPValues(SI->operands()),
7611                                    InvariantCond);
7612   }
7613 
7614   return tryToWiden(Instr, *Plan);
7615 }
7616 
7617 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
7618                                                         ElementCount MaxVF) {
7619   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7620 
7621   // Collect conditions feeding internal conditional branches; they need to be
7622   // represented in VPlan for it to model masking.
7623   SmallPtrSet<Value *, 1> NeedDef;
7624 
7625   auto *Latch = OrigLoop->getLoopLatch();
7626   for (BasicBlock *BB : OrigLoop->blocks()) {
7627     if (BB == Latch)
7628       continue;
7629     BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
7630     if (Branch && Branch->isConditional())
7631       NeedDef.insert(Branch->getCondition());
7632   }
7633 
7634   // If the tail is to be folded by masking, the primary induction variable, if
7635   // exists needs to be represented in VPlan for it to model early-exit masking.
7636   // Also, both the Phi and the live-out instruction of each reduction are
7637   // required in order to introduce a select between them in VPlan.
7638   if (CM.foldTailByMasking()) {
7639     if (Legal->getPrimaryInduction())
7640       NeedDef.insert(Legal->getPrimaryInduction());
7641     for (auto &Reduction : Legal->getReductionVars()) {
7642       NeedDef.insert(Reduction.first);
7643       NeedDef.insert(Reduction.second.getLoopExitInstr());
7644     }
7645   }
7646 
7647   // Collect instructions from the original loop that will become trivially dead
7648   // in the vectorized loop. We don't need to vectorize these instructions. For
7649   // example, original induction update instructions can become dead because we
7650   // separately emit induction "steps" when generating code for the new loop.
7651   // Similarly, we create a new latch condition when setting up the structure
7652   // of the new loop, so the old one can become dead.
7653   SmallPtrSet<Instruction *, 4> DeadInstructions;
7654   collectTriviallyDeadInstructions(DeadInstructions);
7655 
7656   // Add assume instructions we need to drop to DeadInstructions, to prevent
7657   // them from being added to the VPlan.
7658   // TODO: We only need to drop assumes in blocks that get flattend. If the
7659   // control flow is preserved, we should keep them.
7660   auto &ConditionalAssumes = Legal->getConditionalAssumes();
7661   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
7662 
7663   DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
7664   // Dead instructions do not need sinking. Remove them from SinkAfter.
7665   for (Instruction *I : DeadInstructions)
7666     SinkAfter.erase(I);
7667 
7668   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
7669   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
7670     VFRange SubRange = {VF, MaxVFPlusOne};
7671     VPlans.push_back(buildVPlanWithVPRecipes(SubRange, NeedDef,
7672                                              DeadInstructions, SinkAfter));
7673     VF = SubRange.End;
7674   }
7675 }
7676 
7677 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
7678     VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef,
7679     SmallPtrSetImpl<Instruction *> &DeadInstructions,
7680     const DenseMap<Instruction *, Instruction *> &SinkAfter) {
7681 
7682   // Hold a mapping from predicated instructions to their recipes, in order to
7683   // fix their AlsoPack behavior if a user is determined to replicate and use a
7684   // scalar instead of vector value.
7685   DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
7686 
7687   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
7688 
7689   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
7690 
7691   // ---------------------------------------------------------------------------
7692   // Pre-construction: record ingredients whose recipes we'll need to further
7693   // process after constructing the initial VPlan.
7694   // ---------------------------------------------------------------------------
7695 
7696   // Mark instructions we'll need to sink later and their targets as
7697   // ingredients whose recipe we'll need to record.
7698   for (auto &Entry : SinkAfter) {
7699     RecipeBuilder.recordRecipeOf(Entry.first);
7700     RecipeBuilder.recordRecipeOf(Entry.second);
7701   }
7702   for (auto &Reduction : CM.getInLoopReductionChains()) {
7703     PHINode *Phi = Reduction.first;
7704     RecurrenceDescriptor::RecurrenceKind Kind =
7705         Legal->getReductionVars()[Phi].getRecurrenceKind();
7706     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
7707 
7708     RecipeBuilder.recordRecipeOf(Phi);
7709     for (auto &R : ReductionOperations) {
7710       RecipeBuilder.recordRecipeOf(R);
7711       // For min/max reducitons, where we have a pair of icmp/select, we also
7712       // need to record the ICmp recipe, so it can be removed later.
7713       if (Kind == RecurrenceDescriptor::RK_IntegerMinMax ||
7714           Kind == RecurrenceDescriptor::RK_FloatMinMax) {
7715         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
7716       }
7717     }
7718   }
7719 
7720   // For each interleave group which is relevant for this (possibly trimmed)
7721   // Range, add it to the set of groups to be later applied to the VPlan and add
7722   // placeholders for its members' Recipes which we'll be replacing with a
7723   // single VPInterleaveRecipe.
7724   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
7725     auto applyIG = [IG, this](ElementCount VF) -> bool {
7726       return (VF.isVector() && // Query is illegal for VF == 1
7727               CM.getWideningDecision(IG->getInsertPos(), VF) ==
7728                   LoopVectorizationCostModel::CM_Interleave);
7729     };
7730     if (!getDecisionAndClampRange(applyIG, Range))
7731       continue;
7732     InterleaveGroups.insert(IG);
7733     for (unsigned i = 0; i < IG->getFactor(); i++)
7734       if (Instruction *Member = IG->getMember(i))
7735         RecipeBuilder.recordRecipeOf(Member);
7736   };
7737 
7738   // ---------------------------------------------------------------------------
7739   // Build initial VPlan: Scan the body of the loop in a topological order to
7740   // visit each basic block after having visited its predecessor basic blocks.
7741   // ---------------------------------------------------------------------------
7742 
7743   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
7744   auto Plan = std::make_unique<VPlan>();
7745   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
7746   Plan->setEntry(VPBB);
7747 
7748   // Represent values that will have defs inside VPlan.
7749   for (Value *V : NeedDef)
7750     Plan->addVPValue(V);
7751 
7752   // Scan the body of the loop in a topological order to visit each basic block
7753   // after having visited its predecessor basic blocks.
7754   LoopBlocksDFS DFS(OrigLoop);
7755   DFS.perform(LI);
7756 
7757   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
7758     // Relevant instructions from basic block BB will be grouped into VPRecipe
7759     // ingredients and fill a new VPBasicBlock.
7760     unsigned VPBBsForBB = 0;
7761     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
7762     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
7763     VPBB = FirstVPBBForBB;
7764     Builder.setInsertPoint(VPBB);
7765 
7766     // Introduce each ingredient into VPlan.
7767     // TODO: Model and preserve debug instrinsics in VPlan.
7768     for (Instruction &I : BB->instructionsWithoutDebug()) {
7769       Instruction *Instr = &I;
7770 
7771       // First filter out irrelevant instructions, to ensure no recipes are
7772       // built for them.
7773       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
7774         continue;
7775 
7776       if (auto Recipe =
7777               RecipeBuilder.tryToCreateWidenRecipe(Instr, Range, Plan)) {
7778         // Check if the recipe can be converted to a VPValue. We need the extra
7779         // down-casting step until VPRecipeBase inherits from VPValue.
7780         VPValue *MaybeVPValue = Recipe->toVPValue();
7781         if (!Instr->getType()->isVoidTy() && MaybeVPValue) {
7782           if (NeedDef.contains(Instr))
7783             Plan->addOrReplaceVPValue(Instr, MaybeVPValue);
7784           else
7785             Plan->addVPValue(Instr, MaybeVPValue);
7786         }
7787 
7788         RecipeBuilder.setRecipe(Instr, Recipe);
7789         VPBB->appendRecipe(Recipe);
7790         continue;
7791       }
7792 
7793       // Otherwise, if all widening options failed, Instruction is to be
7794       // replicated. This may create a successor for VPBB.
7795       VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
7796           Instr, Range, VPBB, PredInst2Recipe, Plan);
7797       if (NextVPBB != VPBB) {
7798         VPBB = NextVPBB;
7799         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
7800                                     : "");
7801       }
7802     }
7803   }
7804 
7805   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
7806   // may also be empty, such as the last one VPBB, reflecting original
7807   // basic-blocks with no recipes.
7808   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
7809   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
7810   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
7811   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
7812   delete PreEntry;
7813 
7814   // ---------------------------------------------------------------------------
7815   // Transform initial VPlan: Apply previously taken decisions, in order, to
7816   // bring the VPlan to its final state.
7817   // ---------------------------------------------------------------------------
7818 
7819   // Apply Sink-After legal constraints.
7820   for (auto &Entry : SinkAfter) {
7821     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
7822     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
7823     Sink->moveAfter(Target);
7824   }
7825 
7826   // Interleave memory: for each Interleave Group we marked earlier as relevant
7827   // for this VPlan, replace the Recipes widening its memory instructions with a
7828   // single VPInterleaveRecipe at its insertion point.
7829   for (auto IG : InterleaveGroups) {
7830     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
7831         RecipeBuilder.getRecipe(IG->getInsertPos()));
7832     (new VPInterleaveRecipe(IG, Recipe->getAddr(), Recipe->getMask()))
7833         ->insertBefore(Recipe);
7834 
7835     for (unsigned i = 0; i < IG->getFactor(); ++i)
7836       if (Instruction *Member = IG->getMember(i)) {
7837         if (!Member->getType()->isVoidTy()) {
7838           VPValue *OriginalV = Plan->getVPValue(Member);
7839           Plan->removeVPValueFor(Member);
7840           OriginalV->replaceAllUsesWith(Plan->getOrAddVPValue(Member));
7841         }
7842         RecipeBuilder.getRecipe(Member)->eraseFromParent();
7843       }
7844   }
7845 
7846   // Adjust the recipes for any inloop reductions.
7847   if (Range.Start.isVector())
7848     adjustRecipesForInLoopReductions(Plan, RecipeBuilder);
7849 
7850   // Finally, if tail is folded by masking, introduce selects between the phi
7851   // and the live-out instruction of each reduction, at the end of the latch.
7852   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
7853     Builder.setInsertPoint(VPBB);
7854     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
7855     for (auto &Reduction : Legal->getReductionVars()) {
7856       if (CM.isInLoopReduction(Reduction.first))
7857         continue;
7858       VPValue *Phi = Plan->getVPValue(Reduction.first);
7859       VPValue *Red = Plan->getVPValue(Reduction.second.getLoopExitInstr());
7860       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
7861     }
7862   }
7863 
7864   std::string PlanName;
7865   raw_string_ostream RSO(PlanName);
7866   ElementCount VF = Range.Start;
7867   Plan->addVF(VF);
7868   RSO << "Initial VPlan for VF={" << VF;
7869   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
7870     Plan->addVF(VF);
7871     RSO << "," << VF;
7872   }
7873   RSO << "},UF>=1";
7874   RSO.flush();
7875   Plan->setName(PlanName);
7876 
7877   return Plan;
7878 }
7879 
7880 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
7881   // Outer loop handling: They may require CFG and instruction level
7882   // transformations before even evaluating whether vectorization is profitable.
7883   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7884   // the vectorization pipeline.
7885   assert(!OrigLoop->isInnermost());
7886   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7887 
7888   // Create new empty VPlan
7889   auto Plan = std::make_unique<VPlan>();
7890 
7891   // Build hierarchical CFG
7892   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
7893   HCFGBuilder.buildHierarchicalCFG();
7894 
7895   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
7896        VF *= 2)
7897     Plan->addVF(VF);
7898 
7899   if (EnableVPlanPredication) {
7900     VPlanPredicator VPP(*Plan);
7901     VPP.predicate();
7902 
7903     // Avoid running transformation to recipes until masked code generation in
7904     // VPlan-native path is in place.
7905     return Plan;
7906   }
7907 
7908   SmallPtrSet<Instruction *, 1> DeadInstructions;
7909   VPlanTransforms::VPInstructionsToVPRecipes(
7910       OrigLoop, Plan, Legal->getInductionVars(), DeadInstructions);
7911   return Plan;
7912 }
7913 
7914 // Adjust the recipes for any inloop reductions. The chain of instructions
7915 // leading from the loop exit instr to the phi need to be converted to
7916 // reductions, with one operand being vector and the other being the scalar
7917 // reduction chain.
7918 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
7919     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder) {
7920   for (auto &Reduction : CM.getInLoopReductionChains()) {
7921     PHINode *Phi = Reduction.first;
7922     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
7923     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
7924 
7925     // ReductionOperations are orders top-down from the phi's use to the
7926     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
7927     // which of the two operands will remain scalar and which will be reduced.
7928     // For minmax the chain will be the select instructions.
7929     Instruction *Chain = Phi;
7930     for (Instruction *R : ReductionOperations) {
7931       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
7932       RecurrenceDescriptor::RecurrenceKind Kind = RdxDesc.getRecurrenceKind();
7933 
7934       VPValue *ChainOp = Plan->getVPValue(Chain);
7935       unsigned FirstOpId;
7936       if (Kind == RecurrenceDescriptor::RK_IntegerMinMax ||
7937           Kind == RecurrenceDescriptor::RK_FloatMinMax) {
7938         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
7939                "Expected to replace a VPWidenSelectSC");
7940         FirstOpId = 1;
7941       } else {
7942         assert(isa<VPWidenRecipe>(WidenRecipe) &&
7943                "Expected to replace a VPWidenSC");
7944         FirstOpId = 0;
7945       }
7946       unsigned VecOpId =
7947           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
7948       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
7949 
7950       auto *CondOp = CM.foldTailByMasking()
7951                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
7952                          : nullptr;
7953       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
7954           &RdxDesc, R, ChainOp, VecOp, CondOp, Legal->hasFunNoNaNAttr(), TTI);
7955       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
7956       WidenRecipe->eraseFromParent();
7957 
7958       if (Kind == RecurrenceDescriptor::RK_IntegerMinMax ||
7959           Kind == RecurrenceDescriptor::RK_FloatMinMax) {
7960         VPRecipeBase *CompareRecipe =
7961             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
7962         assert(isa<VPWidenRecipe>(CompareRecipe) &&
7963                "Expected to replace a VPWidenSC");
7964         CompareRecipe->eraseFromParent();
7965       }
7966       Chain = R;
7967     }
7968   }
7969 }
7970 
7971 Value* LoopVectorizationPlanner::VPCallbackILV::
7972 getOrCreateVectorValues(Value *V, unsigned Part) {
7973       return ILV.getOrCreateVectorValue(V, Part);
7974 }
7975 
7976 Value *LoopVectorizationPlanner::VPCallbackILV::getOrCreateScalarValue(
7977     Value *V, const VPIteration &Instance) {
7978   return ILV.getOrCreateScalarValue(V, Instance);
7979 }
7980 
7981 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
7982                                VPSlotTracker &SlotTracker) const {
7983   O << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
7984   IG->getInsertPos()->printAsOperand(O, false);
7985   O << ", ";
7986   getAddr()->printAsOperand(O, SlotTracker);
7987   VPValue *Mask = getMask();
7988   if (Mask) {
7989     O << ", ";
7990     Mask->printAsOperand(O, SlotTracker);
7991   }
7992   for (unsigned i = 0; i < IG->getFactor(); ++i)
7993     if (Instruction *I = IG->getMember(i))
7994       O << "\\l\" +\n" << Indent << "\"  " << VPlanIngredient(I) << " " << i;
7995 }
7996 
7997 void VPWidenCallRecipe::execute(VPTransformState &State) {
7998   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
7999                                   *this, State);
8000 }
8001 
8002 void VPWidenSelectRecipe::execute(VPTransformState &State) {
8003   State.ILV->widenSelectInstruction(Ingredient, *this, InvariantCond, State);
8004 }
8005 
8006 void VPWidenRecipe::execute(VPTransformState &State) {
8007   State.ILV->widenInstruction(Ingredient, *this, State);
8008 }
8009 
8010 void VPWidenGEPRecipe::execute(VPTransformState &State) {
8011   State.ILV->widenGEP(GEP, *this, State.UF, State.VF, IsPtrLoopInvariant,
8012                       IsIndexLoopInvariant, State);
8013 }
8014 
8015 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
8016   assert(!State.Instance && "Int or FP induction being replicated.");
8017   State.ILV->widenIntOrFpInduction(IV, Trunc);
8018 }
8019 
8020 void VPWidenPHIRecipe::execute(VPTransformState &State) {
8021   State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
8022 }
8023 
8024 void VPBlendRecipe::execute(VPTransformState &State) {
8025   State.ILV->setDebugLocFromInst(State.Builder, Phi);
8026   // We know that all PHIs in non-header blocks are converted into
8027   // selects, so we don't have to worry about the insertion order and we
8028   // can just use the builder.
8029   // At this point we generate the predication tree. There may be
8030   // duplications since this is a simple recursive scan, but future
8031   // optimizations will clean it up.
8032 
8033   unsigned NumIncoming = getNumIncomingValues();
8034 
8035   // Generate a sequence of selects of the form:
8036   // SELECT(Mask3, In3,
8037   //        SELECT(Mask2, In2,
8038   //               SELECT(Mask1, In1,
8039   //                      In0)))
8040   // Note that Mask0 is never used: lanes for which no path reaches this phi and
8041   // are essentially undef are taken from In0.
8042   InnerLoopVectorizer::VectorParts Entry(State.UF);
8043   for (unsigned In = 0; In < NumIncoming; ++In) {
8044     for (unsigned Part = 0; Part < State.UF; ++Part) {
8045       // We might have single edge PHIs (blocks) - use an identity
8046       // 'select' for the first PHI operand.
8047       Value *In0 = State.get(getIncomingValue(In), Part);
8048       if (In == 0)
8049         Entry[Part] = In0; // Initialize with the first incoming value.
8050       else {
8051         // Select between the current value and the previous incoming edge
8052         // based on the incoming mask.
8053         Value *Cond = State.get(getMask(In), Part);
8054         Entry[Part] =
8055             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
8056       }
8057     }
8058   }
8059   for (unsigned Part = 0; Part < State.UF; ++Part)
8060     State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
8061 }
8062 
8063 void VPInterleaveRecipe::execute(VPTransformState &State) {
8064   assert(!State.Instance && "Interleave group being replicated.");
8065   State.ILV->vectorizeInterleaveGroup(IG, State, getAddr(), getMask());
8066 }
8067 
8068 void VPReductionRecipe::execute(VPTransformState &State) {
8069   assert(!State.Instance && "Reduction being replicated.");
8070   for (unsigned Part = 0; Part < State.UF; ++Part) {
8071     RecurrenceDescriptor::RecurrenceKind Kind = RdxDesc->getRecurrenceKind();
8072     Value *NewVecOp = State.get(VecOp, Part);
8073     if (CondOp) {
8074       Value *NewCond = State.get(CondOp, Part);
8075       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
8076       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
8077           Kind, RdxDesc->getMinMaxRecurrenceKind(), VecTy->getElementType());
8078       Constant *IdenVec =
8079           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
8080       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
8081       NewVecOp = Select;
8082     }
8083     Value *NewRed =
8084         createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp, NoNaN);
8085     Value *PrevInChain = State.get(ChainOp, Part);
8086     Value *NextInChain;
8087     if (Kind == RecurrenceDescriptor::RK_IntegerMinMax ||
8088         Kind == RecurrenceDescriptor::RK_FloatMinMax) {
8089       NextInChain =
8090           createMinMaxOp(State.Builder, RdxDesc->getMinMaxRecurrenceKind(),
8091                          NewRed, PrevInChain);
8092     } else {
8093       NextInChain = State.Builder.CreateBinOp(
8094           (Instruction::BinaryOps)I->getOpcode(), NewRed, PrevInChain);
8095     }
8096     State.ValueMap.setVectorValue(I, Part, NextInChain);
8097   }
8098 }
8099 
8100 void VPReplicateRecipe::execute(VPTransformState &State) {
8101   if (State.Instance) { // Generate a single instance.
8102     State.ILV->scalarizeInstruction(Ingredient, *this, *State.Instance,
8103                                     IsPredicated, State);
8104     // Insert scalar instance packing it into a vector.
8105     if (AlsoPack && State.VF.isVector()) {
8106       // If we're constructing lane 0, initialize to start from undef.
8107       if (State.Instance->Lane == 0) {
8108         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
8109         Value *Undef =
8110             UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
8111         State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
8112       }
8113       State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
8114     }
8115     return;
8116   }
8117 
8118   // Generate scalar instances for all VF lanes of all UF parts, unless the
8119   // instruction is uniform inwhich case generate only the first lane for each
8120   // of the UF parts.
8121   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
8122   for (unsigned Part = 0; Part < State.UF; ++Part)
8123     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
8124       State.ILV->scalarizeInstruction(Ingredient, *this, {Part, Lane},
8125                                       IsPredicated, State);
8126 }
8127 
8128 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
8129   assert(State.Instance && "Branch on Mask works only on single instance.");
8130 
8131   unsigned Part = State.Instance->Part;
8132   unsigned Lane = State.Instance->Lane;
8133 
8134   Value *ConditionBit = nullptr;
8135   VPValue *BlockInMask = getMask();
8136   if (BlockInMask) {
8137     ConditionBit = State.get(BlockInMask, Part);
8138     if (ConditionBit->getType()->isVectorTy())
8139       ConditionBit = State.Builder.CreateExtractElement(
8140           ConditionBit, State.Builder.getInt32(Lane));
8141   } else // Block in mask is all-one.
8142     ConditionBit = State.Builder.getTrue();
8143 
8144   // Replace the temporary unreachable terminator with a new conditional branch,
8145   // whose two destinations will be set later when they are created.
8146   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
8147   assert(isa<UnreachableInst>(CurrentTerminator) &&
8148          "Expected to replace unreachable terminator with conditional branch.");
8149   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
8150   CondBr->setSuccessor(0, nullptr);
8151   ReplaceInstWithInst(CurrentTerminator, CondBr);
8152 }
8153 
8154 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
8155   assert(State.Instance && "Predicated instruction PHI works per instance.");
8156   Instruction *ScalarPredInst = cast<Instruction>(
8157       State.ValueMap.getScalarValue(PredInst, *State.Instance));
8158   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
8159   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
8160   assert(PredicatingBB && "Predicated block has no single predecessor.");
8161 
8162   // By current pack/unpack logic we need to generate only a single phi node: if
8163   // a vector value for the predicated instruction exists at this point it means
8164   // the instruction has vector users only, and a phi for the vector value is
8165   // needed. In this case the recipe of the predicated instruction is marked to
8166   // also do that packing, thereby "hoisting" the insert-element sequence.
8167   // Otherwise, a phi node for the scalar value is needed.
8168   unsigned Part = State.Instance->Part;
8169   if (State.ValueMap.hasVectorValue(PredInst, Part)) {
8170     Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
8171     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
8172     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
8173     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
8174     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
8175     State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
8176   } else {
8177     Type *PredInstType = PredInst->getType();
8178     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
8179     Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
8180     Phi->addIncoming(ScalarPredInst, PredicatedBB);
8181     State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
8182   }
8183 }
8184 
8185 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
8186   Instruction *Instr = getUnderlyingInstr();
8187   VPValue *StoredValue = isa<StoreInst>(Instr) ? getStoredValue() : nullptr;
8188   State.ILV->vectorizeMemoryInstruction(Instr, State,
8189                                         StoredValue ? nullptr : this, getAddr(),
8190                                         StoredValue, getMask());
8191 }
8192 
8193 // Determine how to lower the scalar epilogue, which depends on 1) optimising
8194 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
8195 // predication, and 4) a TTI hook that analyses whether the loop is suitable
8196 // for predication.
8197 static ScalarEpilogueLowering getScalarEpilogueLowering(
8198     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
8199     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
8200     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
8201     LoopVectorizationLegality &LVL) {
8202   // 1) OptSize takes precedence over all other options, i.e. if this is set,
8203   // don't look at hints or options, and don't request a scalar epilogue.
8204   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
8205   // LoopAccessInfo (due to code dependency and not being able to reliably get
8206   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
8207   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
8208   // versioning when the vectorization is forced, unlike hasOptSize. So revert
8209   // back to the old way and vectorize with versioning when forced. See D81345.)
8210   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
8211                                                       PGSOQueryType::IRPass) &&
8212                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
8213     return CM_ScalarEpilogueNotAllowedOptSize;
8214 
8215   bool PredicateOptDisabled = PreferPredicateOverEpilogue.getNumOccurrences() &&
8216                               !PreferPredicateOverEpilogue;
8217 
8218   // 2) Next, if disabling predication is requested on the command line, honour
8219   // this and request a scalar epilogue.
8220   if (PredicateOptDisabled)
8221     return CM_ScalarEpilogueAllowed;
8222 
8223   // 3) and 4) look if enabling predication is requested on the command line,
8224   // with a loop hint, or if the TTI hook indicates this is profitable, request
8225   // predication.
8226   if (PreferPredicateOverEpilogue ||
8227       Hints.getPredicate() == LoopVectorizeHints::FK_Enabled ||
8228       (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
8229                                         LVL.getLAI()) &&
8230        Hints.getPredicate() != LoopVectorizeHints::FK_Disabled))
8231     return CM_ScalarEpilogueNotNeededUsePredicate;
8232 
8233   return CM_ScalarEpilogueAllowed;
8234 }
8235 
8236 void VPTransformState::set(VPValue *Def, Value *IRDef, Value *V,
8237                            unsigned Part) {
8238   set(Def, V, Part);
8239   ILV->setVectorValue(IRDef, Part, V);
8240 }
8241 
8242 // Process the loop in the VPlan-native vectorization path. This path builds
8243 // VPlan upfront in the vectorization pipeline, which allows to apply
8244 // VPlan-to-VPlan transformations from the very beginning without modifying the
8245 // input LLVM IR.
8246 static bool processLoopInVPlanNativePath(
8247     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
8248     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
8249     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
8250     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
8251     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints) {
8252 
8253   if (PSE.getBackedgeTakenCount() == PSE.getSE()->getCouldNotCompute()) {
8254     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
8255     return false;
8256   }
8257   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
8258   Function *F = L->getHeader()->getParent();
8259   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
8260 
8261   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
8262       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
8263 
8264   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
8265                                 &Hints, IAI);
8266   // Use the planner for outer loop vectorization.
8267   // TODO: CM is not used at this point inside the planner. Turn CM into an
8268   // optional argument if we don't need it in the future.
8269   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE);
8270 
8271   // Get user vectorization factor.
8272   const unsigned UserVF = Hints.getWidth();
8273 
8274   // Plan how to best vectorize, return the best VF and its cost.
8275   const VectorizationFactor VF =
8276       LVP.planInVPlanNativePath(ElementCount::getFixed(UserVF));
8277 
8278   // If we are stress testing VPlan builds, do not attempt to generate vector
8279   // code. Masked vector code generation support will follow soon.
8280   // Also, do not attempt to vectorize if no vector code will be produced.
8281   if (VPlanBuildStressTest || EnableVPlanPredication ||
8282       VectorizationFactor::Disabled() == VF)
8283     return false;
8284 
8285   LVP.setBestPlan(VF.Width, 1);
8286 
8287   InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
8288                          &CM, BFI, PSI);
8289   LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
8290                     << L->getHeader()->getParent()->getName() << "\"\n");
8291   LVP.executePlan(LB, DT);
8292 
8293   // Mark the loop as already vectorized to avoid vectorizing again.
8294   Hints.setAlreadyVectorized();
8295 
8296   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
8297   return true;
8298 }
8299 
8300 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
8301     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
8302                                !EnableLoopInterleaving),
8303       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
8304                               !EnableLoopVectorization) {}
8305 
8306 bool LoopVectorizePass::processLoop(Loop *L) {
8307   assert((EnableVPlanNativePath || L->isInnermost()) &&
8308          "VPlan-native path is not enabled. Only process inner loops.");
8309 
8310 #ifndef NDEBUG
8311   const std::string DebugLocStr = getDebugLocString(L);
8312 #endif /* NDEBUG */
8313 
8314   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
8315                     << L->getHeader()->getParent()->getName() << "\" from "
8316                     << DebugLocStr << "\n");
8317 
8318   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
8319 
8320   LLVM_DEBUG(
8321       dbgs() << "LV: Loop hints:"
8322              << " force="
8323              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
8324                      ? "disabled"
8325                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
8326                             ? "enabled"
8327                             : "?"))
8328              << " width=" << Hints.getWidth()
8329              << " unroll=" << Hints.getInterleave() << "\n");
8330 
8331   // Function containing loop
8332   Function *F = L->getHeader()->getParent();
8333 
8334   // Looking at the diagnostic output is the only way to determine if a loop
8335   // was vectorized (other than looking at the IR or machine code), so it
8336   // is important to generate an optimization remark for each loop. Most of
8337   // these messages are generated as OptimizationRemarkAnalysis. Remarks
8338   // generated as OptimizationRemark and OptimizationRemarkMissed are
8339   // less verbose reporting vectorized loops and unvectorized loops that may
8340   // benefit from vectorization, respectively.
8341 
8342   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
8343     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
8344     return false;
8345   }
8346 
8347   PredicatedScalarEvolution PSE(*SE, *L);
8348 
8349   // Check if it is legal to vectorize the loop.
8350   LoopVectorizationRequirements Requirements(*ORE);
8351   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
8352                                 &Requirements, &Hints, DB, AC, BFI, PSI);
8353   if (!LVL.canVectorize(EnableVPlanNativePath)) {
8354     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
8355     Hints.emitRemarkWithHints();
8356     return false;
8357   }
8358 
8359   // Check the function attributes and profiles to find out if this function
8360   // should be optimized for size.
8361   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
8362       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
8363 
8364   // Entrance to the VPlan-native vectorization path. Outer loops are processed
8365   // here. They may require CFG and instruction level transformations before
8366   // even evaluating whether vectorization is profitable. Since we cannot modify
8367   // the incoming IR, we need to build VPlan upfront in the vectorization
8368   // pipeline.
8369   if (!L->isInnermost())
8370     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
8371                                         ORE, BFI, PSI, Hints);
8372 
8373   assert(L->isInnermost() && "Inner loop expected.");
8374 
8375   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
8376   // count by optimizing for size, to minimize overheads.
8377   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
8378   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
8379     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
8380                       << "This loop is worth vectorizing only if no scalar "
8381                       << "iteration overheads are incurred.");
8382     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
8383       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
8384     else {
8385       LLVM_DEBUG(dbgs() << "\n");
8386       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
8387     }
8388   }
8389 
8390   // Check the function attributes to see if implicit floats are allowed.
8391   // FIXME: This check doesn't seem possibly correct -- what if the loop is
8392   // an integer loop and the vector instructions selected are purely integer
8393   // vector instructions?
8394   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
8395     reportVectorizationFailure(
8396         "Can't vectorize when the NoImplicitFloat attribute is used",
8397         "loop not vectorized due to NoImplicitFloat attribute",
8398         "NoImplicitFloat", ORE, L);
8399     Hints.emitRemarkWithHints();
8400     return false;
8401   }
8402 
8403   // Check if the target supports potentially unsafe FP vectorization.
8404   // FIXME: Add a check for the type of safety issue (denormal, signaling)
8405   // for the target we're vectorizing for, to make sure none of the
8406   // additional fp-math flags can help.
8407   if (Hints.isPotentiallyUnsafe() &&
8408       TTI->isFPVectorizationPotentiallyUnsafe()) {
8409     reportVectorizationFailure(
8410         "Potentially unsafe FP op prevents vectorization",
8411         "loop not vectorized due to unsafe FP support.",
8412         "UnsafeFP", ORE, L);
8413     Hints.emitRemarkWithHints();
8414     return false;
8415   }
8416 
8417   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
8418   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
8419 
8420   // If an override option has been passed in for interleaved accesses, use it.
8421   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
8422     UseInterleaved = EnableInterleavedMemAccesses;
8423 
8424   // Analyze interleaved memory accesses.
8425   if (UseInterleaved) {
8426     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
8427   }
8428 
8429   // Use the cost model.
8430   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
8431                                 F, &Hints, IAI);
8432   CM.collectValuesToIgnore();
8433 
8434   // Use the planner for vectorization.
8435   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE);
8436 
8437   // Get user vectorization factor and interleave count.
8438   unsigned UserVF = Hints.getWidth();
8439   unsigned UserIC = Hints.getInterleave();
8440 
8441   // Plan how to best vectorize, return the best VF and its cost.
8442   Optional<VectorizationFactor> MaybeVF =
8443       LVP.plan(ElementCount::getFixed(UserVF), UserIC);
8444 
8445   VectorizationFactor VF = VectorizationFactor::Disabled();
8446   unsigned IC = 1;
8447 
8448   if (MaybeVF) {
8449     VF = *MaybeVF;
8450     // Select the interleave count.
8451     IC = CM.selectInterleaveCount(VF.Width, VF.Cost);
8452   }
8453 
8454   // Identify the diagnostic messages that should be produced.
8455   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
8456   bool VectorizeLoop = true, InterleaveLoop = true;
8457   if (Requirements.doesNotMeet(F, L, Hints)) {
8458     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
8459                          "requirements.\n");
8460     Hints.emitRemarkWithHints();
8461     return false;
8462   }
8463 
8464   if (VF.Width.isScalar()) {
8465     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
8466     VecDiagMsg = std::make_pair(
8467         "VectorizationNotBeneficial",
8468         "the cost-model indicates that vectorization is not beneficial");
8469     VectorizeLoop = false;
8470   }
8471 
8472   if (!MaybeVF && UserIC > 1) {
8473     // Tell the user interleaving was avoided up-front, despite being explicitly
8474     // requested.
8475     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
8476                          "interleaving should be avoided up front\n");
8477     IntDiagMsg = std::make_pair(
8478         "InterleavingAvoided",
8479         "Ignoring UserIC, because interleaving was avoided up front");
8480     InterleaveLoop = false;
8481   } else if (IC == 1 && UserIC <= 1) {
8482     // Tell the user interleaving is not beneficial.
8483     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
8484     IntDiagMsg = std::make_pair(
8485         "InterleavingNotBeneficial",
8486         "the cost-model indicates that interleaving is not beneficial");
8487     InterleaveLoop = false;
8488     if (UserIC == 1) {
8489       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
8490       IntDiagMsg.second +=
8491           " and is explicitly disabled or interleave count is set to 1";
8492     }
8493   } else if (IC > 1 && UserIC == 1) {
8494     // Tell the user interleaving is beneficial, but it explicitly disabled.
8495     LLVM_DEBUG(
8496         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
8497     IntDiagMsg = std::make_pair(
8498         "InterleavingBeneficialButDisabled",
8499         "the cost-model indicates that interleaving is beneficial "
8500         "but is explicitly disabled or interleave count is set to 1");
8501     InterleaveLoop = false;
8502   }
8503 
8504   // Override IC if user provided an interleave count.
8505   IC = UserIC > 0 ? UserIC : IC;
8506 
8507   // Emit diagnostic messages, if any.
8508   const char *VAPassName = Hints.vectorizeAnalysisPassName();
8509   if (!VectorizeLoop && !InterleaveLoop) {
8510     // Do not vectorize or interleaving the loop.
8511     ORE->emit([&]() {
8512       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
8513                                       L->getStartLoc(), L->getHeader())
8514              << VecDiagMsg.second;
8515     });
8516     ORE->emit([&]() {
8517       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
8518                                       L->getStartLoc(), L->getHeader())
8519              << IntDiagMsg.second;
8520     });
8521     return false;
8522   } else if (!VectorizeLoop && InterleaveLoop) {
8523     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8524     ORE->emit([&]() {
8525       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
8526                                         L->getStartLoc(), L->getHeader())
8527              << VecDiagMsg.second;
8528     });
8529   } else if (VectorizeLoop && !InterleaveLoop) {
8530     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
8531                       << ") in " << DebugLocStr << '\n');
8532     ORE->emit([&]() {
8533       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
8534                                         L->getStartLoc(), L->getHeader())
8535              << IntDiagMsg.second;
8536     });
8537   } else if (VectorizeLoop && InterleaveLoop) {
8538     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
8539                       << ") in " << DebugLocStr << '\n');
8540     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
8541   }
8542 
8543   LVP.setBestPlan(VF.Width, IC);
8544 
8545   using namespace ore;
8546   bool DisableRuntimeUnroll = false;
8547   MDNode *OrigLoopID = L->getLoopID();
8548 
8549   if (!VectorizeLoop) {
8550     assert(IC > 1 && "interleave count should not be 1 or 0");
8551     // If we decided that it is not legal to vectorize the loop, then
8552     // interleave it.
8553     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, &CM,
8554                                BFI, PSI);
8555     LVP.executePlan(Unroller, DT);
8556 
8557     ORE->emit([&]() {
8558       return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
8559                                 L->getHeader())
8560              << "interleaved loop (interleaved count: "
8561              << NV("InterleaveCount", IC) << ")";
8562     });
8563   } else {
8564     // If we decided that it is *legal* to vectorize the loop, then do it.
8565     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
8566                            &LVL, &CM, BFI, PSI);
8567     LVP.executePlan(LB, DT);
8568     ++LoopsVectorized;
8569 
8570     // Add metadata to disable runtime unrolling a scalar loop when there are
8571     // no runtime checks about strides and memory. A scalar loop that is
8572     // rarely used is not worth unrolling.
8573     if (!LB.areSafetyChecksAdded())
8574       DisableRuntimeUnroll = true;
8575 
8576     // Report the vectorization decision.
8577     ORE->emit([&]() {
8578       return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
8579                                 L->getHeader())
8580              << "vectorized loop (vectorization width: "
8581              << NV("VectorizationFactor", VF.Width)
8582              << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
8583     });
8584   }
8585 
8586   Optional<MDNode *> RemainderLoopID =
8587       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
8588                                       LLVMLoopVectorizeFollowupEpilogue});
8589   if (RemainderLoopID.hasValue()) {
8590     L->setLoopID(RemainderLoopID.getValue());
8591   } else {
8592     if (DisableRuntimeUnroll)
8593       AddRuntimeUnrollDisableMetaData(L);
8594 
8595     // Mark the loop as already vectorized to avoid vectorizing again.
8596     Hints.setAlreadyVectorized();
8597   }
8598 
8599   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
8600   return true;
8601 }
8602 
8603 LoopVectorizeResult LoopVectorizePass::runImpl(
8604     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
8605     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
8606     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
8607     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
8608     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
8609   SE = &SE_;
8610   LI = &LI_;
8611   TTI = &TTI_;
8612   DT = &DT_;
8613   BFI = &BFI_;
8614   TLI = TLI_;
8615   AA = &AA_;
8616   AC = &AC_;
8617   GetLAA = &GetLAA_;
8618   DB = &DB_;
8619   ORE = &ORE_;
8620   PSI = PSI_;
8621 
8622   // Don't attempt if
8623   // 1. the target claims to have no vector registers, and
8624   // 2. interleaving won't help ILP.
8625   //
8626   // The second condition is necessary because, even if the target has no
8627   // vector registers, loop vectorization may still enable scalar
8628   // interleaving.
8629   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
8630       TTI->getMaxInterleaveFactor(1) < 2)
8631     return LoopVectorizeResult(false, false);
8632 
8633   bool Changed = false, CFGChanged = false;
8634 
8635   // The vectorizer requires loops to be in simplified form.
8636   // Since simplification may add new inner loops, it has to run before the
8637   // legality and profitability checks. This means running the loop vectorizer
8638   // will simplify all loops, regardless of whether anything end up being
8639   // vectorized.
8640   for (auto &L : *LI)
8641     Changed |= CFGChanged |=
8642         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
8643 
8644   // Build up a worklist of inner-loops to vectorize. This is necessary as
8645   // the act of vectorizing or partially unrolling a loop creates new loops
8646   // and can invalidate iterators across the loops.
8647   SmallVector<Loop *, 8> Worklist;
8648 
8649   for (Loop *L : *LI)
8650     collectSupportedLoops(*L, LI, ORE, Worklist);
8651 
8652   LoopsAnalyzed += Worklist.size();
8653 
8654   // Now walk the identified inner loops.
8655   while (!Worklist.empty()) {
8656     Loop *L = Worklist.pop_back_val();
8657 
8658     // For the inner loops we actually process, form LCSSA to simplify the
8659     // transform.
8660     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8661 
8662     Changed |= CFGChanged |= processLoop(L);
8663   }
8664 
8665   // Process each loop nest in the function.
8666   return LoopVectorizeResult(Changed, CFGChanged);
8667 }
8668 
8669 PreservedAnalyses LoopVectorizePass::run(Function &F,
8670                                          FunctionAnalysisManager &AM) {
8671     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
8672     auto &LI = AM.getResult<LoopAnalysis>(F);
8673     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
8674     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
8675     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
8676     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
8677     auto &AA = AM.getResult<AAManager>(F);
8678     auto &AC = AM.getResult<AssumptionAnalysis>(F);
8679     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
8680     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8681     MemorySSA *MSSA = EnableMSSALoopDependency
8682                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
8683                           : nullptr;
8684 
8685     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
8686     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
8687         [&](Loop &L) -> const LoopAccessInfo & {
8688       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
8689                                         TLI, TTI, nullptr, MSSA};
8690       return LAM.getResult<LoopAccessAnalysis>(L, AR);
8691     };
8692     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
8693     ProfileSummaryInfo *PSI =
8694         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
8695     LoopVectorizeResult Result =
8696         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
8697     if (!Result.MadeAnyChange)
8698       return PreservedAnalyses::all();
8699     PreservedAnalyses PA;
8700 
8701     // We currently do not preserve loopinfo/dominator analyses with outer loop
8702     // vectorization. Until this is addressed, mark these analyses as preserved
8703     // only for non-VPlan-native path.
8704     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
8705     if (!EnableVPlanNativePath) {
8706       PA.preserve<LoopAnalysis>();
8707       PA.preserve<DominatorTreeAnalysis>();
8708     }
8709     PA.preserve<BasicAA>();
8710     PA.preserve<GlobalsAA>();
8711     if (!Result.MadeCFGChange)
8712       PA.preserveSet<CFGAnalyses>();
8713     return PA;
8714 }
8715