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