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/SmallPtrSet.h"
73 #include "llvm/ADT/SmallSet.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/OptimizationRemarkEmitter.h"
91 #include "llvm/Analysis/ProfileSummaryInfo.h"
92 #include "llvm/Analysis/ScalarEvolution.h"
93 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
94 #include "llvm/Analysis/TargetLibraryInfo.h"
95 #include "llvm/Analysis/TargetTransformInfo.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/LLVMContext.h"
116 #include "llvm/IR/Metadata.h"
117 #include "llvm/IR/Module.h"
118 #include "llvm/IR/Operator.h"
119 #include "llvm/IR/PatternMatch.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/InstructionCost.h"
134 #include "llvm/Support/MathExtras.h"
135 #include "llvm/Support/raw_ostream.h"
136 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
137 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
138 #include "llvm/Transforms/Utils/LoopSimplify.h"
139 #include "llvm/Transforms/Utils/LoopUtils.h"
140 #include "llvm/Transforms/Utils/LoopVersioning.h"
141 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
142 #include "llvm/Transforms/Utils/SizeOpts.h"
143 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
144 #include <algorithm>
145 #include <cassert>
146 #include <cstdint>
147 #include <cstdlib>
148 #include <functional>
149 #include <iterator>
150 #include <limits>
151 #include <memory>
152 #include <string>
153 #include <tuple>
154 #include <utility>
155 
156 using namespace llvm;
157 
158 #define LV_NAME "loop-vectorize"
159 #define DEBUG_TYPE LV_NAME
160 
161 #ifndef NDEBUG
162 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
163 #endif
164 
165 /// @{
166 /// Metadata attribute names
167 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
168 const char LLVMLoopVectorizeFollowupVectorized[] =
169     "llvm.loop.vectorize.followup_vectorized";
170 const char LLVMLoopVectorizeFollowupEpilogue[] =
171     "llvm.loop.vectorize.followup_epilogue";
172 /// @}
173 
174 STATISTIC(LoopsVectorized, "Number of loops vectorized");
175 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
176 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
177 
178 static cl::opt<bool> EnableEpilogueVectorization(
179     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180     cl::desc("Enable vectorization of epilogue loops."));
181 
182 static cl::opt<unsigned> EpilogueVectorizationForceVF(
183     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
184     cl::desc("When epilogue vectorization is enabled, and a value greater than "
185              "1 is specified, forces the given VF for all applicable epilogue "
186              "loops."));
187 
188 static cl::opt<unsigned> EpilogueVectorizationMinVF(
189     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
190     cl::desc("Only loops with vectorization factor equal to or larger than "
191              "the specified value are considered for epilogue vectorization."));
192 
193 /// Loops with a known constant trip count below this number are vectorized only
194 /// if no scalar iteration overheads are incurred.
195 static cl::opt<unsigned> TinyTripCountVectorThreshold(
196     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197     cl::desc("Loops with a constant trip count that is smaller than this "
198              "value are vectorized only if no scalar iteration overheads "
199              "are incurred."));
200 
201 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
202     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
203     cl::desc("The maximum allowed number of runtime memory checks with a "
204              "vectorize(enable) pragma."));
205 
206 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
207 // that predication is preferred, and this lists all options. I.e., the
208 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
209 // and predicate the instructions accordingly. If tail-folding fails, there are
210 // different fallback strategies depending on these values:
211 namespace PreferPredicateTy {
212   enum Option {
213     ScalarEpilogue = 0,
214     PredicateElseScalarEpilogue,
215     PredicateOrDontVectorize
216   };
217 } // namespace PreferPredicateTy
218 
219 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
220     "prefer-predicate-over-epilogue",
221     cl::init(PreferPredicateTy::ScalarEpilogue),
222     cl::Hidden,
223     cl::desc("Tail-folding and predication preferences over creating a scalar "
224              "epilogue loop."),
225     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
226                          "scalar-epilogue",
227                          "Don't tail-predicate loops, create scalar epilogue"),
228               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
229                          "predicate-else-scalar-epilogue",
230                          "prefer tail-folding, create scalar epilogue if tail "
231                          "folding fails."),
232               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
233                          "predicate-dont-vectorize",
234                          "prefers tail-folding, don't attempt vectorization if "
235                          "tail-folding fails.")));
236 
237 static cl::opt<bool> MaximizeBandwidth(
238     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
239     cl::desc("Maximize bandwidth when selecting vectorization factor which "
240              "will be determined by the smallest type in loop."));
241 
242 static cl::opt<bool> EnableInterleavedMemAccesses(
243     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
244     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
245 
246 /// An interleave-group may need masking if it resides in a block that needs
247 /// predication, or in order to mask away gaps.
248 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
249     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
250     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
251 
252 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
253     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
254     cl::desc("We don't interleave loops with a estimated constant trip count "
255              "below this number"));
256 
257 static cl::opt<unsigned> ForceTargetNumScalarRegs(
258     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
259     cl::desc("A flag that overrides the target's number of scalar registers."));
260 
261 static cl::opt<unsigned> ForceTargetNumVectorRegs(
262     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
263     cl::desc("A flag that overrides the target's number of vector registers."));
264 
265 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
266     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
267     cl::desc("A flag that overrides the target's max interleave factor for "
268              "scalar loops."));
269 
270 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
271     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
272     cl::desc("A flag that overrides the target's max interleave factor for "
273              "vectorized loops."));
274 
275 static cl::opt<unsigned> ForceTargetInstructionCost(
276     "force-target-instruction-cost", cl::init(0), cl::Hidden,
277     cl::desc("A flag that overrides the target's expected cost for "
278              "an instruction to a single constant value. Mostly "
279              "useful for getting consistent testing."));
280 
281 static cl::opt<bool> ForceTargetSupportsScalableVectors(
282     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
283     cl::desc(
284         "Pretend that scalable vectors are supported, even if the target does "
285         "not support them. This flag should only be used for testing."));
286 
287 static cl::opt<unsigned> SmallLoopCost(
288     "small-loop-cost", cl::init(20), cl::Hidden,
289     cl::desc(
290         "The cost of a loop that is considered 'small' by the interleaver."));
291 
292 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
293     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
294     cl::desc("Enable the use of the block frequency analysis to access PGO "
295              "heuristics minimizing code growth in cold regions and being more "
296              "aggressive in hot regions."));
297 
298 // Runtime interleave loops for load/store throughput.
299 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
300     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
301     cl::desc(
302         "Enable runtime interleaving until load/store ports are saturated"));
303 
304 /// Interleave small loops with scalar reductions.
305 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
306     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
307     cl::desc("Enable interleaving for loops with small iteration counts that "
308              "contain scalar reductions to expose ILP."));
309 
310 /// The number of stores in a loop that are allowed to need predication.
311 static cl::opt<unsigned> NumberOfStoresToPredicate(
312     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
313     cl::desc("Max number of stores to be predicated behind an if."));
314 
315 static cl::opt<bool> EnableIndVarRegisterHeur(
316     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
317     cl::desc("Count the induction variable only once when interleaving"));
318 
319 static cl::opt<bool> EnableCondStoresVectorization(
320     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
321     cl::desc("Enable if predication of stores during vectorization."));
322 
323 static cl::opt<unsigned> MaxNestedScalarReductionIC(
324     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
325     cl::desc("The maximum interleave count to use when interleaving a scalar "
326              "reduction in a nested loop."));
327 
328 static cl::opt<bool>
329     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
330                            cl::Hidden,
331                            cl::desc("Prefer in-loop vector reductions, "
332                                     "overriding the targets preference."));
333 
334 static cl::opt<bool> ForceOrderedReductions(
335     "force-ordered-reductions", cl::init(false), cl::Hidden,
336     cl::desc("Enable the vectorisation of loops with in-order (strict) "
337              "FP reductions"));
338 
339 static cl::opt<bool> PreferPredicatedReductionSelect(
340     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
341     cl::desc(
342         "Prefer predicating a reduction operation over an after loop select."));
343 
344 cl::opt<bool> EnableVPlanNativePath(
345     "enable-vplan-native-path", cl::init(false), cl::Hidden,
346     cl::desc("Enable VPlan-native vectorization path with "
347              "support for outer loop vectorization."));
348 
349 // FIXME: Remove this switch once we have divergence analysis. Currently we
350 // assume divergent non-backedge branches when this switch is true.
351 cl::opt<bool> EnableVPlanPredication(
352     "enable-vplan-predication", cl::init(false), cl::Hidden,
353     cl::desc("Enable VPlan-native vectorization path predicator with "
354              "support for outer loop vectorization."));
355 
356 // This flag enables the stress testing of the VPlan H-CFG construction in the
357 // VPlan-native vectorization path. It must be used in conjuction with
358 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
359 // verification of the H-CFGs built.
360 static cl::opt<bool> VPlanBuildStressTest(
361     "vplan-build-stress-test", cl::init(false), cl::Hidden,
362     cl::desc(
363         "Build VPlan for every supported loop nest in the function and bail "
364         "out right after the build (stress test the VPlan H-CFG construction "
365         "in the VPlan-native vectorization path)."));
366 
367 cl::opt<bool> llvm::EnableLoopInterleaving(
368     "interleave-loops", cl::init(true), cl::Hidden,
369     cl::desc("Enable loop interleaving in Loop vectorization passes"));
370 cl::opt<bool> llvm::EnableLoopVectorization(
371     "vectorize-loops", cl::init(true), cl::Hidden,
372     cl::desc("Run the Loop vectorization passes"));
373 
374 cl::opt<bool> PrintVPlansInDotFormat(
375     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
376     cl::desc("Use dot format instead of plain text when dumping VPlans"));
377 
378 /// A helper function that returns true if the given type is irregular. The
379 /// type is irregular if its allocated size doesn't equal the store size of an
380 /// element of the corresponding vector type.
381 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
382   // Determine if an array of N elements of type Ty is "bitcast compatible"
383   // with a <N x Ty> vector.
384   // This is only true if there is no padding between the array elements.
385   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
386 }
387 
388 /// A helper function that returns the reciprocal of the block probability of
389 /// predicated blocks. If we return X, we are assuming the predicated block
390 /// will execute once for every X iterations of the loop header.
391 ///
392 /// TODO: We should use actual block probability here, if available. Currently,
393 ///       we always assume predicated blocks have a 50% chance of executing.
394 static unsigned getReciprocalPredBlockProb() { return 2; }
395 
396 /// A helper function that returns an integer or floating-point constant with
397 /// value C.
398 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
399   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
400                            : ConstantFP::get(Ty, C);
401 }
402 
403 /// Returns "best known" trip count for the specified loop \p L as defined by
404 /// the following procedure:
405 ///   1) Returns exact trip count if it is known.
406 ///   2) Returns expected trip count according to profile data if any.
407 ///   3) Returns upper bound estimate if it is known.
408 ///   4) Returns None if all of the above failed.
409 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
410   // Check if exact trip count is known.
411   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
412     return ExpectedTC;
413 
414   // Check if there is an expected trip count available from profile data.
415   if (LoopVectorizeWithBlockFrequency)
416     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
417       return EstimatedTC;
418 
419   // Check if upper bound estimate is known.
420   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
421     return ExpectedTC;
422 
423   return None;
424 }
425 
426 // Forward declare GeneratedRTChecks.
427 class GeneratedRTChecks;
428 
429 namespace llvm {
430 
431 /// InnerLoopVectorizer vectorizes loops which contain only one basic
432 /// block to a specified vectorization factor (VF).
433 /// This class performs the widening of scalars into vectors, or multiple
434 /// scalars. This class also implements the following features:
435 /// * It inserts an epilogue loop for handling loops that don't have iteration
436 ///   counts that are known to be a multiple of the vectorization factor.
437 /// * It handles the code generation for reduction variables.
438 /// * Scalarization (implementation using scalars) of un-vectorizable
439 ///   instructions.
440 /// InnerLoopVectorizer does not perform any vectorization-legality
441 /// checks, and relies on the caller to check for the different legality
442 /// aspects. The InnerLoopVectorizer relies on the
443 /// LoopVectorizationLegality class to provide information about the induction
444 /// and reduction variables that were found to a given vectorization factor.
445 class InnerLoopVectorizer {
446 public:
447   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
448                       LoopInfo *LI, DominatorTree *DT,
449                       const TargetLibraryInfo *TLI,
450                       const TargetTransformInfo *TTI, AssumptionCache *AC,
451                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
452                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
453                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
454                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
455       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
456         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
457         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
458         PSI(PSI), RTChecks(RTChecks) {
459     // Query this against the original loop and save it here because the profile
460     // of the original loop header may change as the transformation happens.
461     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
462         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
463   }
464 
465   virtual ~InnerLoopVectorizer() = default;
466 
467   /// Create a new empty loop that will contain vectorized instructions later
468   /// on, while the old loop will be used as the scalar remainder. Control flow
469   /// is generated around the vectorized (and scalar epilogue) loops consisting
470   /// of various checks and bypasses. Return the pre-header block of the new
471   /// loop.
472   /// In the case of epilogue vectorization, this function is overriden to
473   /// handle the more complex control flow around the loops.
474   virtual BasicBlock *createVectorizedLoopSkeleton();
475 
476   /// Widen a single instruction within the innermost loop.
477   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
478                         VPTransformState &State);
479 
480   /// Widen a single call instruction within the innermost loop.
481   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
482                             VPTransformState &State);
483 
484   /// Widen a single select instruction within the innermost loop.
485   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
486                               bool InvariantCond, VPTransformState &State);
487 
488   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
489   void fixVectorizedLoop(VPTransformState &State);
490 
491   // Return true if any runtime check is added.
492   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
493 
494   /// A type for vectorized values in the new loop. Each value from the
495   /// original loop, when vectorized, is represented by UF vector values in the
496   /// new unrolled loop, where UF is the unroll factor.
497   using VectorParts = SmallVector<Value *, 2>;
498 
499   /// Vectorize a single GetElementPtrInst based on information gathered and
500   /// decisions taken during planning.
501   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
502                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
503                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
504 
505   /// Vectorize a single first-order recurrence or pointer induction PHINode in
506   /// a block. This method handles the induction variable canonicalization. It
507   /// supports both VF = 1 for unrolled loops and arbitrary length vectors.
508   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
509                            VPTransformState &State);
510 
511   /// A helper function to scalarize a single Instruction in the innermost loop.
512   /// Generates a sequence of scalar instances for each lane between \p MinLane
513   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
514   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
515   /// Instr's operands.
516   void scalarizeInstruction(Instruction *Instr, VPValue *Def, VPUser &Operands,
517                             const VPIteration &Instance, bool IfPredicateInstr,
518                             VPTransformState &State);
519 
520   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
521   /// is provided, the integer induction variable will first be truncated to
522   /// the corresponding type.
523   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
524                              VPValue *Def, VPValue *CastDef,
525                              VPTransformState &State);
526 
527   /// Construct the vector value of a scalarized value \p V one lane at a time.
528   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
529                                  VPTransformState &State);
530 
531   /// Try to vectorize interleaved access group \p Group with the base address
532   /// given in \p Addr, optionally masking the vector operations if \p
533   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
534   /// values in the vectorized loop.
535   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
536                                 ArrayRef<VPValue *> VPDefs,
537                                 VPTransformState &State, VPValue *Addr,
538                                 ArrayRef<VPValue *> StoredValues,
539                                 VPValue *BlockInMask = nullptr);
540 
541   /// Vectorize Load and Store instructions with the base address given in \p
542   /// Addr, optionally masking the vector operations if \p BlockInMask is
543   /// non-null. Use \p State to translate given VPValues to IR values in the
544   /// vectorized loop.
545   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
546                                   VPValue *Def, VPValue *Addr,
547                                   VPValue *StoredValue, VPValue *BlockInMask);
548 
549   /// Set the debug location in the builder \p Ptr using the debug location in
550   /// \p V. If \p Ptr is None then it uses the class member's Builder.
551   void setDebugLocFromInst(const Value *V,
552                            Optional<IRBuilder<> *> CustomBuilder = None);
553 
554   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
555   void fixNonInductionPHIs(VPTransformState &State);
556 
557   /// Returns true if the reordering of FP operations is not allowed, but we are
558   /// able to vectorize with strict in-order reductions for the given RdxDesc.
559   bool useOrderedReductions(RecurrenceDescriptor &RdxDesc);
560 
561   /// Create a broadcast instruction. This method generates a broadcast
562   /// instruction (shuffle) for loop invariant values and for the induction
563   /// value. If this is the induction variable then we extend it to N, N+1, ...
564   /// this is needed because each iteration in the loop corresponds to a SIMD
565   /// element.
566   virtual Value *getBroadcastInstrs(Value *V);
567 
568 protected:
569   friend class LoopVectorizationPlanner;
570 
571   /// A small list of PHINodes.
572   using PhiVector = SmallVector<PHINode *, 4>;
573 
574   /// A type for scalarized values in the new loop. Each value from the
575   /// original loop, when scalarized, is represented by UF x VF scalar values
576   /// in the new unrolled loop, where UF is the unroll factor and VF is the
577   /// vectorization factor.
578   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
579 
580   /// Set up the values of the IVs correctly when exiting the vector loop.
581   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
582                     Value *CountRoundDown, Value *EndValue,
583                     BasicBlock *MiddleBlock);
584 
585   /// Create a new induction variable inside L.
586   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
587                                    Value *Step, Instruction *DL);
588 
589   /// Handle all cross-iteration phis in the header.
590   void fixCrossIterationPHIs(VPTransformState &State);
591 
592   /// Create the exit value of first order recurrences in the middle block and
593   /// update their users.
594   void fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR, VPTransformState &State);
595 
596   /// Create code for the loop exit value of the reduction.
597   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
598 
599   /// Clear NSW/NUW flags from reduction instructions if necessary.
600   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
601                                VPTransformState &State);
602 
603   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
604   /// means we need to add the appropriate incoming value from the middle
605   /// block as exiting edges from the scalar epilogue loop (if present) are
606   /// already in place, and we exit the vector loop exclusively to the middle
607   /// block.
608   void fixLCSSAPHIs(VPTransformState &State);
609 
610   /// Iteratively sink the scalarized operands of a predicated instruction into
611   /// the block that was created for it.
612   void sinkScalarOperands(Instruction *PredInst);
613 
614   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
615   /// represented as.
616   void truncateToMinimalBitwidths(VPTransformState &State);
617 
618   /// This function adds
619   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
620   /// to each vector element of Val. The sequence starts at StartIndex.
621   /// \p Opcode is relevant for FP induction variable.
622   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
623                                Instruction::BinaryOps Opcode =
624                                Instruction::BinaryOpsEnd);
625 
626   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
627   /// variable on which to base the steps, \p Step is the size of the step, and
628   /// \p EntryVal is the value from the original loop that maps to the steps.
629   /// Note that \p EntryVal doesn't have to be an induction variable - it
630   /// can also be a truncate instruction.
631   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
632                         const InductionDescriptor &ID, VPValue *Def,
633                         VPValue *CastDef, VPTransformState &State);
634 
635   /// Create a vector induction phi node based on an existing scalar one. \p
636   /// EntryVal is the value from the original loop that maps to the vector phi
637   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
638   /// truncate instruction, instead of widening the original IV, we widen a
639   /// version of the IV truncated to \p EntryVal's type.
640   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
641                                        Value *Step, Value *Start,
642                                        Instruction *EntryVal, VPValue *Def,
643                                        VPValue *CastDef,
644                                        VPTransformState &State);
645 
646   /// Returns true if an instruction \p I should be scalarized instead of
647   /// vectorized for the chosen vectorization factor.
648   bool shouldScalarizeInstruction(Instruction *I) const;
649 
650   /// Returns true if we should generate a scalar version of \p IV.
651   bool needsScalarInduction(Instruction *IV) const;
652 
653   /// If there is a cast involved in the induction variable \p ID, which should
654   /// be ignored in the vectorized loop body, this function records the
655   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
656   /// cast. We had already proved that the casted Phi is equal to the uncasted
657   /// Phi in the vectorized loop (under a runtime guard), and therefore
658   /// there is no need to vectorize the cast - the same value can be used in the
659   /// vector loop for both the Phi and the cast.
660   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
661   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
662   ///
663   /// \p EntryVal is the value from the original loop that maps to the vector
664   /// phi node and is used to distinguish what is the IV currently being
665   /// processed - original one (if \p EntryVal is a phi corresponding to the
666   /// original IV) or the "newly-created" one based on the proof mentioned above
667   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
668   /// latter case \p EntryVal is a TruncInst and we must not record anything for
669   /// that IV, but it's error-prone to expect callers of this routine to care
670   /// about that, hence this explicit parameter.
671   void recordVectorLoopValueForInductionCast(
672       const InductionDescriptor &ID, const Instruction *EntryVal,
673       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
674       unsigned Part, unsigned Lane = UINT_MAX);
675 
676   /// Generate a shuffle sequence that will reverse the vector Vec.
677   virtual Value *reverseVector(Value *Vec);
678 
679   /// Returns (and creates if needed) the original loop trip count.
680   Value *getOrCreateTripCount(Loop *NewLoop);
681 
682   /// Returns (and creates if needed) the trip count of the widened loop.
683   Value *getOrCreateVectorTripCount(Loop *NewLoop);
684 
685   /// Returns a bitcasted value to the requested vector type.
686   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
687   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
688                                 const DataLayout &DL);
689 
690   /// Emit a bypass check to see if the vector trip count is zero, including if
691   /// it overflows.
692   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
693 
694   /// Emit a bypass check to see if all of the SCEV assumptions we've
695   /// had to make are correct. Returns the block containing the checks or
696   /// nullptr if no checks have been added.
697   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
698 
699   /// Emit bypass checks to check any memory assumptions we may have made.
700   /// Returns the block containing the checks or nullptr if no checks have been
701   /// added.
702   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
703 
704   /// Compute the transformed value of Index at offset StartValue using step
705   /// StepValue.
706   /// For integer induction, returns StartValue + Index * StepValue.
707   /// For pointer induction, returns StartValue[Index * StepValue].
708   /// FIXME: The newly created binary instructions should contain nsw/nuw
709   /// flags, which can be found from the original scalar operations.
710   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
711                               const DataLayout &DL,
712                               const InductionDescriptor &ID) const;
713 
714   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
715   /// vector loop preheader, middle block and scalar preheader. Also
716   /// allocate a loop object for the new vector loop and return it.
717   Loop *createVectorLoopSkeleton(StringRef Prefix);
718 
719   /// Create new phi nodes for the induction variables to resume iteration count
720   /// in the scalar epilogue, from where the vectorized loop left off (given by
721   /// \p VectorTripCount).
722   /// In cases where the loop skeleton is more complicated (eg. epilogue
723   /// vectorization) and the resume values can come from an additional bypass
724   /// block, the \p AdditionalBypass pair provides information about the bypass
725   /// block and the end value on the edge from bypass to this loop.
726   void createInductionResumeValues(
727       Loop *L, Value *VectorTripCount,
728       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
729 
730   /// Complete the loop skeleton by adding debug MDs, creating appropriate
731   /// conditional branches in the middle block, preparing the builder and
732   /// running the verifier. Take in the vector loop \p L as argument, and return
733   /// the preheader of the completed vector loop.
734   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
735 
736   /// Add additional metadata to \p To that was not present on \p Orig.
737   ///
738   /// Currently this is used to add the noalias annotations based on the
739   /// inserted memchecks.  Use this for instructions that are *cloned* into the
740   /// vector loop.
741   void addNewMetadata(Instruction *To, const Instruction *Orig);
742 
743   /// Add metadata from one instruction to another.
744   ///
745   /// This includes both the original MDs from \p From and additional ones (\see
746   /// addNewMetadata).  Use this for *newly created* instructions in the vector
747   /// loop.
748   void addMetadata(Instruction *To, Instruction *From);
749 
750   /// Similar to the previous function but it adds the metadata to a
751   /// vector of instructions.
752   void addMetadata(ArrayRef<Value *> To, Instruction *From);
753 
754   /// Allow subclasses to override and print debug traces before/after vplan
755   /// execution, when trace information is requested.
756   virtual void printDebugTracesAtStart(){};
757   virtual void printDebugTracesAtEnd(){};
758 
759   /// The original loop.
760   Loop *OrigLoop;
761 
762   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
763   /// dynamic knowledge to simplify SCEV expressions and converts them to a
764   /// more usable form.
765   PredicatedScalarEvolution &PSE;
766 
767   /// Loop Info.
768   LoopInfo *LI;
769 
770   /// Dominator Tree.
771   DominatorTree *DT;
772 
773   /// Alias Analysis.
774   AAResults *AA;
775 
776   /// Target Library Info.
777   const TargetLibraryInfo *TLI;
778 
779   /// Target Transform Info.
780   const TargetTransformInfo *TTI;
781 
782   /// Assumption Cache.
783   AssumptionCache *AC;
784 
785   /// Interface to emit optimization remarks.
786   OptimizationRemarkEmitter *ORE;
787 
788   /// LoopVersioning.  It's only set up (non-null) if memchecks were
789   /// used.
790   ///
791   /// This is currently only used to add no-alias metadata based on the
792   /// memchecks.  The actually versioning is performed manually.
793   std::unique_ptr<LoopVersioning> LVer;
794 
795   /// The vectorization SIMD factor to use. Each vector will have this many
796   /// vector elements.
797   ElementCount VF;
798 
799   /// The vectorization unroll factor to use. Each scalar is vectorized to this
800   /// many different vector instructions.
801   unsigned UF;
802 
803   /// The builder that we use
804   IRBuilder<> Builder;
805 
806   // --- Vectorization state ---
807 
808   /// The vector-loop preheader.
809   BasicBlock *LoopVectorPreHeader;
810 
811   /// The scalar-loop preheader.
812   BasicBlock *LoopScalarPreHeader;
813 
814   /// Middle Block between the vector and the scalar.
815   BasicBlock *LoopMiddleBlock;
816 
817   /// The unique ExitBlock of the scalar loop if one exists.  Note that
818   /// there can be multiple exiting edges reaching this block.
819   BasicBlock *LoopExitBlock;
820 
821   /// The vector loop body.
822   BasicBlock *LoopVectorBody;
823 
824   /// The scalar loop body.
825   BasicBlock *LoopScalarBody;
826 
827   /// A list of all bypass blocks. The first block is the entry of the loop.
828   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
829 
830   /// The new Induction variable which was added to the new block.
831   PHINode *Induction = nullptr;
832 
833   /// The induction variable of the old basic block.
834   PHINode *OldInduction = nullptr;
835 
836   /// Store instructions that were predicated.
837   SmallVector<Instruction *, 4> PredicatedInstructions;
838 
839   /// Trip count of the original loop.
840   Value *TripCount = nullptr;
841 
842   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
843   Value *VectorTripCount = nullptr;
844 
845   /// The legality analysis.
846   LoopVectorizationLegality *Legal;
847 
848   /// The profitablity analysis.
849   LoopVectorizationCostModel *Cost;
850 
851   // Record whether runtime checks are added.
852   bool AddedSafetyChecks = false;
853 
854   // Holds the end values for each induction variable. We save the end values
855   // so we can later fix-up the external users of the induction variables.
856   DenseMap<PHINode *, Value *> IVEndValues;
857 
858   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
859   // fixed up at the end of vector code generation.
860   SmallVector<PHINode *, 8> OrigPHIsToFix;
861 
862   /// BFI and PSI are used to check for profile guided size optimizations.
863   BlockFrequencyInfo *BFI;
864   ProfileSummaryInfo *PSI;
865 
866   // Whether this loop should be optimized for size based on profile guided size
867   // optimizatios.
868   bool OptForSizeBasedOnProfile;
869 
870   /// Structure to hold information about generated runtime checks, responsible
871   /// for cleaning the checks, if vectorization turns out unprofitable.
872   GeneratedRTChecks &RTChecks;
873 };
874 
875 class InnerLoopUnroller : public InnerLoopVectorizer {
876 public:
877   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
878                     LoopInfo *LI, DominatorTree *DT,
879                     const TargetLibraryInfo *TLI,
880                     const TargetTransformInfo *TTI, AssumptionCache *AC,
881                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
882                     LoopVectorizationLegality *LVL,
883                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
884                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
885       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
886                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
887                             BFI, PSI, Check) {}
888 
889 private:
890   Value *getBroadcastInstrs(Value *V) override;
891   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
892                        Instruction::BinaryOps Opcode =
893                        Instruction::BinaryOpsEnd) override;
894   Value *reverseVector(Value *Vec) override;
895 };
896 
897 /// Encapsulate information regarding vectorization of a loop and its epilogue.
898 /// This information is meant to be updated and used across two stages of
899 /// epilogue vectorization.
900 struct EpilogueLoopVectorizationInfo {
901   ElementCount MainLoopVF = ElementCount::getFixed(0);
902   unsigned MainLoopUF = 0;
903   ElementCount EpilogueVF = ElementCount::getFixed(0);
904   unsigned EpilogueUF = 0;
905   BasicBlock *MainLoopIterationCountCheck = nullptr;
906   BasicBlock *EpilogueIterationCountCheck = nullptr;
907   BasicBlock *SCEVSafetyCheck = nullptr;
908   BasicBlock *MemSafetyCheck = nullptr;
909   Value *TripCount = nullptr;
910   Value *VectorTripCount = nullptr;
911 
912   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
913                                 ElementCount EVF, unsigned EUF)
914       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
915     assert(EUF == 1 &&
916            "A high UF for the epilogue loop is likely not beneficial.");
917   }
918 };
919 
920 /// An extension of the inner loop vectorizer that creates a skeleton for a
921 /// vectorized loop that has its epilogue (residual) also vectorized.
922 /// The idea is to run the vplan on a given loop twice, firstly to setup the
923 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
924 /// from the first step and vectorize the epilogue.  This is achieved by
925 /// deriving two concrete strategy classes from this base class and invoking
926 /// them in succession from the loop vectorizer planner.
927 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
928 public:
929   InnerLoopAndEpilogueVectorizer(
930       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
931       DominatorTree *DT, const TargetLibraryInfo *TLI,
932       const TargetTransformInfo *TTI, AssumptionCache *AC,
933       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
934       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
935       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
936       GeneratedRTChecks &Checks)
937       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
938                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
939                             Checks),
940         EPI(EPI) {}
941 
942   // Override this function to handle the more complex control flow around the
943   // three loops.
944   BasicBlock *createVectorizedLoopSkeleton() final override {
945     return createEpilogueVectorizedLoopSkeleton();
946   }
947 
948   /// The interface for creating a vectorized skeleton using one of two
949   /// different strategies, each corresponding to one execution of the vplan
950   /// as described above.
951   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
952 
953   /// Holds and updates state information required to vectorize the main loop
954   /// and its epilogue in two separate passes. This setup helps us avoid
955   /// regenerating and recomputing runtime safety checks. It also helps us to
956   /// shorten the iteration-count-check path length for the cases where the
957   /// iteration count of the loop is so small that the main vector loop is
958   /// completely skipped.
959   EpilogueLoopVectorizationInfo &EPI;
960 };
961 
962 /// A specialized derived class of inner loop vectorizer that performs
963 /// vectorization of *main* loops in the process of vectorizing loops and their
964 /// epilogues.
965 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
966 public:
967   EpilogueVectorizerMainLoop(
968       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
969       DominatorTree *DT, const TargetLibraryInfo *TLI,
970       const TargetTransformInfo *TTI, AssumptionCache *AC,
971       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
972       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
973       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
974       GeneratedRTChecks &Check)
975       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
976                                        EPI, LVL, CM, BFI, PSI, Check) {}
977   /// Implements the interface for creating a vectorized skeleton using the
978   /// *main loop* strategy (ie the first pass of vplan execution).
979   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
980 
981 protected:
982   /// Emits an iteration count bypass check once for the main loop (when \p
983   /// ForEpilogue is false) and once for the epilogue loop (when \p
984   /// ForEpilogue is true).
985   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
986                                              bool ForEpilogue);
987   void printDebugTracesAtStart() override;
988   void printDebugTracesAtEnd() override;
989 };
990 
991 // A specialized derived class of inner loop vectorizer that performs
992 // vectorization of *epilogue* loops in the process of vectorizing loops and
993 // their epilogues.
994 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
995 public:
996   EpilogueVectorizerEpilogueLoop(
997       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
998       DominatorTree *DT, const TargetLibraryInfo *TLI,
999       const TargetTransformInfo *TTI, AssumptionCache *AC,
1000       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1001       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1002       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1003       GeneratedRTChecks &Checks)
1004       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1005                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1006   /// Implements the interface for creating a vectorized skeleton using the
1007   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1008   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1009 
1010 protected:
1011   /// Emits an iteration count bypass check after the main vector loop has
1012   /// finished to see if there are any iterations left to execute by either
1013   /// the vector epilogue or the scalar epilogue.
1014   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1015                                                       BasicBlock *Bypass,
1016                                                       BasicBlock *Insert);
1017   void printDebugTracesAtStart() override;
1018   void printDebugTracesAtEnd() override;
1019 };
1020 } // end namespace llvm
1021 
1022 /// Look for a meaningful debug location on the instruction or it's
1023 /// operands.
1024 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1025   if (!I)
1026     return I;
1027 
1028   DebugLoc Empty;
1029   if (I->getDebugLoc() != Empty)
1030     return I;
1031 
1032   for (Use &Op : I->operands()) {
1033     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1034       if (OpInst->getDebugLoc() != Empty)
1035         return OpInst;
1036   }
1037 
1038   return I;
1039 }
1040 
1041 void InnerLoopVectorizer::setDebugLocFromInst(
1042     const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
1043   IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
1044   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
1045     const DILocation *DIL = Inst->getDebugLoc();
1046 
1047     // When a FSDiscriminator is enabled, we don't need to add the multiply
1048     // factors to the discriminators.
1049     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1050         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1051       // FIXME: For scalable vectors, assume vscale=1.
1052       auto NewDIL =
1053           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1054       if (NewDIL)
1055         B->SetCurrentDebugLocation(NewDIL.getValue());
1056       else
1057         LLVM_DEBUG(dbgs()
1058                    << "Failed to create new discriminator: "
1059                    << DIL->getFilename() << " Line: " << DIL->getLine());
1060     } else
1061       B->SetCurrentDebugLocation(DIL);
1062   } else
1063     B->SetCurrentDebugLocation(DebugLoc());
1064 }
1065 
1066 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1067 /// is passed, the message relates to that particular instruction.
1068 #ifndef NDEBUG
1069 static void debugVectorizationMessage(const StringRef Prefix,
1070                                       const StringRef DebugMsg,
1071                                       Instruction *I) {
1072   dbgs() << "LV: " << Prefix << DebugMsg;
1073   if (I != nullptr)
1074     dbgs() << " " << *I;
1075   else
1076     dbgs() << '.';
1077   dbgs() << '\n';
1078 }
1079 #endif
1080 
1081 /// Create an analysis remark that explains why vectorization failed
1082 ///
1083 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1084 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1085 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1086 /// the location of the remark.  \return the remark object that can be
1087 /// streamed to.
1088 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1089     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1090   Value *CodeRegion = TheLoop->getHeader();
1091   DebugLoc DL = TheLoop->getStartLoc();
1092 
1093   if (I) {
1094     CodeRegion = I->getParent();
1095     // If there is no debug location attached to the instruction, revert back to
1096     // using the loop's.
1097     if (I->getDebugLoc())
1098       DL = I->getDebugLoc();
1099   }
1100 
1101   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1102 }
1103 
1104 /// Return a value for Step multiplied by VF.
1105 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1106   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1107   Constant *StepVal = ConstantInt::get(
1108       Step->getType(),
1109       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1110   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1111 }
1112 
1113 namespace llvm {
1114 
1115 /// Return the runtime value for VF.
1116 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1117   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1118   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1119 }
1120 
1121 void reportVectorizationFailure(const StringRef DebugMsg,
1122                                 const StringRef OREMsg, const StringRef ORETag,
1123                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1124                                 Instruction *I) {
1125   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1126   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1127   ORE->emit(
1128       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1129       << "loop not vectorized: " << OREMsg);
1130 }
1131 
1132 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1133                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1134                              Instruction *I) {
1135   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1136   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1137   ORE->emit(
1138       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1139       << Msg);
1140 }
1141 
1142 } // end namespace llvm
1143 
1144 #ifndef NDEBUG
1145 /// \return string containing a file name and a line # for the given loop.
1146 static std::string getDebugLocString(const Loop *L) {
1147   std::string Result;
1148   if (L) {
1149     raw_string_ostream OS(Result);
1150     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1151       LoopDbgLoc.print(OS);
1152     else
1153       // Just print the module name.
1154       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1155     OS.flush();
1156   }
1157   return Result;
1158 }
1159 #endif
1160 
1161 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1162                                          const Instruction *Orig) {
1163   // If the loop was versioned with memchecks, add the corresponding no-alias
1164   // metadata.
1165   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1166     LVer->annotateInstWithNoAlias(To, Orig);
1167 }
1168 
1169 void InnerLoopVectorizer::addMetadata(Instruction *To,
1170                                       Instruction *From) {
1171   propagateMetadata(To, From);
1172   addNewMetadata(To, From);
1173 }
1174 
1175 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1176                                       Instruction *From) {
1177   for (Value *V : To) {
1178     if (Instruction *I = dyn_cast<Instruction>(V))
1179       addMetadata(I, From);
1180   }
1181 }
1182 
1183 namespace llvm {
1184 
1185 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1186 // lowered.
1187 enum ScalarEpilogueLowering {
1188 
1189   // The default: allowing scalar epilogues.
1190   CM_ScalarEpilogueAllowed,
1191 
1192   // Vectorization with OptForSize: don't allow epilogues.
1193   CM_ScalarEpilogueNotAllowedOptSize,
1194 
1195   // A special case of vectorisation with OptForSize: loops with a very small
1196   // trip count are considered for vectorization under OptForSize, thereby
1197   // making sure the cost of their loop body is dominant, free of runtime
1198   // guards and scalar iteration overheads.
1199   CM_ScalarEpilogueNotAllowedLowTripLoop,
1200 
1201   // Loop hint predicate indicating an epilogue is undesired.
1202   CM_ScalarEpilogueNotNeededUsePredicate,
1203 
1204   // Directive indicating we must either tail fold or not vectorize
1205   CM_ScalarEpilogueNotAllowedUsePredicate
1206 };
1207 
1208 /// ElementCountComparator creates a total ordering for ElementCount
1209 /// for the purposes of using it in a set structure.
1210 struct ElementCountComparator {
1211   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1212     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1213            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1214   }
1215 };
1216 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1217 
1218 /// LoopVectorizationCostModel - estimates the expected speedups due to
1219 /// vectorization.
1220 /// In many cases vectorization is not profitable. This can happen because of
1221 /// a number of reasons. In this class we mainly attempt to predict the
1222 /// expected speedup/slowdowns due to the supported instruction set. We use the
1223 /// TargetTransformInfo to query the different backends for the cost of
1224 /// different operations.
1225 class LoopVectorizationCostModel {
1226 public:
1227   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1228                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1229                              LoopVectorizationLegality *Legal,
1230                              const TargetTransformInfo &TTI,
1231                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1232                              AssumptionCache *AC,
1233                              OptimizationRemarkEmitter *ORE, const Function *F,
1234                              const LoopVectorizeHints *Hints,
1235                              InterleavedAccessInfo &IAI)
1236       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1237         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1238         Hints(Hints), InterleaveInfo(IAI) {}
1239 
1240   /// \return An upper bound for the vectorization factors (both fixed and
1241   /// scalable). If the factors are 0, vectorization and interleaving should be
1242   /// avoided up front.
1243   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1244 
1245   /// \return True if runtime checks are required for vectorization, and false
1246   /// otherwise.
1247   bool runtimeChecksRequired();
1248 
1249   /// \return The most profitable vectorization factor and the cost of that VF.
1250   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1251   /// then this vectorization factor will be selected if vectorization is
1252   /// possible.
1253   VectorizationFactor
1254   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1255 
1256   VectorizationFactor
1257   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1258                                     const LoopVectorizationPlanner &LVP);
1259 
1260   /// Setup cost-based decisions for user vectorization factor.
1261   /// \return true if the UserVF is a feasible VF to be chosen.
1262   bool selectUserVectorizationFactor(ElementCount UserVF) {
1263     collectUniformsAndScalars(UserVF);
1264     collectInstsToScalarize(UserVF);
1265     return expectedCost(UserVF).first.isValid();
1266   }
1267 
1268   /// \return The size (in bits) of the smallest and widest types in the code
1269   /// that needs to be vectorized. We ignore values that remain scalar such as
1270   /// 64 bit loop indices.
1271   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1272 
1273   /// \return The desired interleave count.
1274   /// If interleave count has been specified by metadata it will be returned.
1275   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1276   /// are the selected vectorization factor and the cost of the selected VF.
1277   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1278 
1279   /// Memory access instruction may be vectorized in more than one way.
1280   /// Form of instruction after vectorization depends on cost.
1281   /// This function takes cost-based decisions for Load/Store instructions
1282   /// and collects them in a map. This decisions map is used for building
1283   /// the lists of loop-uniform and loop-scalar instructions.
1284   /// The calculated cost is saved with widening decision in order to
1285   /// avoid redundant calculations.
1286   void setCostBasedWideningDecision(ElementCount VF);
1287 
1288   /// A struct that represents some properties of the register usage
1289   /// of a loop.
1290   struct RegisterUsage {
1291     /// Holds the number of loop invariant values that are used in the loop.
1292     /// The key is ClassID of target-provided register class.
1293     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1294     /// Holds the maximum number of concurrent live intervals in the loop.
1295     /// The key is ClassID of target-provided register class.
1296     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1297   };
1298 
1299   /// \return Returns information about the register usages of the loop for the
1300   /// given vectorization factors.
1301   SmallVector<RegisterUsage, 8>
1302   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1303 
1304   /// Collect values we want to ignore in the cost model.
1305   void collectValuesToIgnore();
1306 
1307   /// Collect all element types in the loop for which widening is needed.
1308   void collectElementTypesForWidening();
1309 
1310   /// Split reductions into those that happen in the loop, and those that happen
1311   /// outside. In loop reductions are collected into InLoopReductionChains.
1312   void collectInLoopReductions();
1313 
1314   /// Returns true if we should use strict in-order reductions for the given
1315   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1316   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1317   /// of FP operations.
1318   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1319     return !Hints->allowReordering() && RdxDesc.isOrdered();
1320   }
1321 
1322   /// \returns The smallest bitwidth each instruction can be represented with.
1323   /// The vector equivalents of these instructions should be truncated to this
1324   /// type.
1325   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1326     return MinBWs;
1327   }
1328 
1329   /// \returns True if it is more profitable to scalarize instruction \p I for
1330   /// vectorization factor \p VF.
1331   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1332     assert(VF.isVector() &&
1333            "Profitable to scalarize relevant only for VF > 1.");
1334 
1335     // Cost model is not run in the VPlan-native path - return conservative
1336     // result until this changes.
1337     if (EnableVPlanNativePath)
1338       return false;
1339 
1340     auto Scalars = InstsToScalarize.find(VF);
1341     assert(Scalars != InstsToScalarize.end() &&
1342            "VF not yet analyzed for scalarization profitability");
1343     return Scalars->second.find(I) != Scalars->second.end();
1344   }
1345 
1346   /// Returns true if \p I is known to be uniform after vectorization.
1347   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1348     if (VF.isScalar())
1349       return true;
1350 
1351     // Cost model is not run in the VPlan-native path - return conservative
1352     // result until this changes.
1353     if (EnableVPlanNativePath)
1354       return false;
1355 
1356     auto UniformsPerVF = Uniforms.find(VF);
1357     assert(UniformsPerVF != Uniforms.end() &&
1358            "VF not yet analyzed for uniformity");
1359     return UniformsPerVF->second.count(I);
1360   }
1361 
1362   /// Returns true if \p I is known to be scalar after vectorization.
1363   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1364     if (VF.isScalar())
1365       return true;
1366 
1367     // Cost model is not run in the VPlan-native path - return conservative
1368     // result until this changes.
1369     if (EnableVPlanNativePath)
1370       return false;
1371 
1372     auto ScalarsPerVF = Scalars.find(VF);
1373     assert(ScalarsPerVF != Scalars.end() &&
1374            "Scalar values are not calculated for VF");
1375     return ScalarsPerVF->second.count(I);
1376   }
1377 
1378   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1379   /// for vectorization factor \p VF.
1380   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1381     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1382            !isProfitableToScalarize(I, VF) &&
1383            !isScalarAfterVectorization(I, VF);
1384   }
1385 
1386   /// Decision that was taken during cost calculation for memory instruction.
1387   enum InstWidening {
1388     CM_Unknown,
1389     CM_Widen,         // For consecutive accesses with stride +1.
1390     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1391     CM_Interleave,
1392     CM_GatherScatter,
1393     CM_Scalarize
1394   };
1395 
1396   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1397   /// instruction \p I and vector width \p VF.
1398   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1399                            InstructionCost Cost) {
1400     assert(VF.isVector() && "Expected VF >=2");
1401     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1402   }
1403 
1404   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1405   /// interleaving group \p Grp and vector width \p VF.
1406   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1407                            ElementCount VF, InstWidening W,
1408                            InstructionCost Cost) {
1409     assert(VF.isVector() && "Expected VF >=2");
1410     /// Broadcast this decicion to all instructions inside the group.
1411     /// But the cost will be assigned to one instruction only.
1412     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1413       if (auto *I = Grp->getMember(i)) {
1414         if (Grp->getInsertPos() == I)
1415           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1416         else
1417           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1418       }
1419     }
1420   }
1421 
1422   /// Return the cost model decision for the given instruction \p I and vector
1423   /// width \p VF. Return CM_Unknown if this instruction did not pass
1424   /// through the cost modeling.
1425   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1426     assert(VF.isVector() && "Expected VF to be a vector VF");
1427     // Cost model is not run in the VPlan-native path - return conservative
1428     // result until this changes.
1429     if (EnableVPlanNativePath)
1430       return CM_GatherScatter;
1431 
1432     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1433     auto Itr = WideningDecisions.find(InstOnVF);
1434     if (Itr == WideningDecisions.end())
1435       return CM_Unknown;
1436     return Itr->second.first;
1437   }
1438 
1439   /// Return the vectorization cost for the given instruction \p I and vector
1440   /// width \p VF.
1441   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1442     assert(VF.isVector() && "Expected VF >=2");
1443     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1444     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1445            "The cost is not calculated");
1446     return WideningDecisions[InstOnVF].second;
1447   }
1448 
1449   /// Return True if instruction \p I is an optimizable truncate whose operand
1450   /// is an induction variable. Such a truncate will be removed by adding a new
1451   /// induction variable with the destination type.
1452   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1453     // If the instruction is not a truncate, return false.
1454     auto *Trunc = dyn_cast<TruncInst>(I);
1455     if (!Trunc)
1456       return false;
1457 
1458     // Get the source and destination types of the truncate.
1459     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1460     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1461 
1462     // If the truncate is free for the given types, return false. Replacing a
1463     // free truncate with an induction variable would add an induction variable
1464     // update instruction to each iteration of the loop. We exclude from this
1465     // check the primary induction variable since it will need an update
1466     // instruction regardless.
1467     Value *Op = Trunc->getOperand(0);
1468     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1469       return false;
1470 
1471     // If the truncated value is not an induction variable, return false.
1472     return Legal->isInductionPhi(Op);
1473   }
1474 
1475   /// Collects the instructions to scalarize for each predicated instruction in
1476   /// the loop.
1477   void collectInstsToScalarize(ElementCount VF);
1478 
1479   /// Collect Uniform and Scalar values for the given \p VF.
1480   /// The sets depend on CM decision for Load/Store instructions
1481   /// that may be vectorized as interleave, gather-scatter or scalarized.
1482   void collectUniformsAndScalars(ElementCount VF) {
1483     // Do the analysis once.
1484     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1485       return;
1486     setCostBasedWideningDecision(VF);
1487     collectLoopUniforms(VF);
1488     collectLoopScalars(VF);
1489   }
1490 
1491   /// Returns true if the target machine supports masked store operation
1492   /// for the given \p DataType and kind of access to \p Ptr.
1493   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1494     return Legal->isConsecutivePtr(DataType, Ptr) &&
1495            TTI.isLegalMaskedStore(DataType, Alignment);
1496   }
1497 
1498   /// Returns true if the target machine supports masked load operation
1499   /// for the given \p DataType and kind of access to \p Ptr.
1500   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1501     return Legal->isConsecutivePtr(DataType, Ptr) &&
1502            TTI.isLegalMaskedLoad(DataType, Alignment);
1503   }
1504 
1505   /// Returns true if the target machine can represent \p V as a masked gather
1506   /// or scatter operation.
1507   bool isLegalGatherOrScatter(Value *V) {
1508     bool LI = isa<LoadInst>(V);
1509     bool SI = isa<StoreInst>(V);
1510     if (!LI && !SI)
1511       return false;
1512     auto *Ty = getLoadStoreType(V);
1513     Align Align = getLoadStoreAlignment(V);
1514     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1515            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1516   }
1517 
1518   /// Returns true if the target machine supports all of the reduction
1519   /// variables found for the given VF.
1520   bool canVectorizeReductions(ElementCount VF) const {
1521     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1522       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1523       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1524     }));
1525   }
1526 
1527   /// Returns true if \p I is an instruction that will be scalarized with
1528   /// predication. Such instructions include conditional stores and
1529   /// instructions that may divide by zero.
1530   /// If a non-zero VF has been calculated, we check if I will be scalarized
1531   /// predication for that VF.
1532   bool isScalarWithPredication(Instruction *I) const;
1533 
1534   // Returns true if \p I is an instruction that will be predicated either
1535   // through scalar predication or masked load/store or masked gather/scatter.
1536   // Superset of instructions that return true for isScalarWithPredication.
1537   bool isPredicatedInst(Instruction *I) {
1538     if (!blockNeedsPredication(I->getParent()))
1539       return false;
1540     // Loads and stores that need some form of masked operation are predicated
1541     // instructions.
1542     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1543       return Legal->isMaskRequired(I);
1544     return isScalarWithPredication(I);
1545   }
1546 
1547   /// Returns true if \p I is a memory instruction with consecutive memory
1548   /// access that can be widened.
1549   bool
1550   memoryInstructionCanBeWidened(Instruction *I,
1551                                 ElementCount VF = ElementCount::getFixed(1));
1552 
1553   /// Returns true if \p I is a memory instruction in an interleaved-group
1554   /// of memory accesses that can be vectorized with wide vector loads/stores
1555   /// and shuffles.
1556   bool
1557   interleavedAccessCanBeWidened(Instruction *I,
1558                                 ElementCount VF = ElementCount::getFixed(1));
1559 
1560   /// Check if \p Instr belongs to any interleaved access group.
1561   bool isAccessInterleaved(Instruction *Instr) {
1562     return InterleaveInfo.isInterleaved(Instr);
1563   }
1564 
1565   /// Get the interleaved access group that \p Instr belongs to.
1566   const InterleaveGroup<Instruction> *
1567   getInterleavedAccessGroup(Instruction *Instr) {
1568     return InterleaveInfo.getInterleaveGroup(Instr);
1569   }
1570 
1571   /// Returns true if we're required to use a scalar epilogue for at least
1572   /// the final iteration of the original loop.
1573   bool requiresScalarEpilogue(ElementCount VF) const {
1574     if (!isScalarEpilogueAllowed())
1575       return false;
1576     // If we might exit from anywhere but the latch, must run the exiting
1577     // iteration in scalar form.
1578     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1579       return true;
1580     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1581   }
1582 
1583   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1584   /// loop hint annotation.
1585   bool isScalarEpilogueAllowed() const {
1586     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1587   }
1588 
1589   /// Returns true if all loop blocks should be masked to fold tail loop.
1590   bool foldTailByMasking() const { return FoldTailByMasking; }
1591 
1592   bool blockNeedsPredication(BasicBlock *BB) const {
1593     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1594   }
1595 
1596   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1597   /// nodes to the chain of instructions representing the reductions. Uses a
1598   /// MapVector to ensure deterministic iteration order.
1599   using ReductionChainMap =
1600       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1601 
1602   /// Return the chain of instructions representing an inloop reduction.
1603   const ReductionChainMap &getInLoopReductionChains() const {
1604     return InLoopReductionChains;
1605   }
1606 
1607   /// Returns true if the Phi is part of an inloop reduction.
1608   bool isInLoopReduction(PHINode *Phi) const {
1609     return InLoopReductionChains.count(Phi);
1610   }
1611 
1612   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1613   /// with factor VF.  Return the cost of the instruction, including
1614   /// scalarization overhead if it's needed.
1615   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1616 
1617   /// Estimate cost of a call instruction CI if it were vectorized with factor
1618   /// VF. Return the cost of the instruction, including scalarization overhead
1619   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1620   /// scalarized -
1621   /// i.e. either vector version isn't available, or is too expensive.
1622   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1623                                     bool &NeedToScalarize) const;
1624 
1625   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1626   /// that of B.
1627   bool isMoreProfitable(const VectorizationFactor &A,
1628                         const VectorizationFactor &B) const;
1629 
1630   /// Invalidates decisions already taken by the cost model.
1631   void invalidateCostModelingDecisions() {
1632     WideningDecisions.clear();
1633     Uniforms.clear();
1634     Scalars.clear();
1635   }
1636 
1637 private:
1638   unsigned NumPredStores = 0;
1639 
1640   /// \return An upper bound for the vectorization factors for both
1641   /// fixed and scalable vectorization, where the minimum-known number of
1642   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1643   /// disabled or unsupported, then the scalable part will be equal to
1644   /// ElementCount::getScalable(0).
1645   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1646                                            ElementCount UserVF);
1647 
1648   /// \return the maximized element count based on the targets vector
1649   /// registers and the loop trip-count, but limited to a maximum safe VF.
1650   /// This is a helper function of computeFeasibleMaxVF.
1651   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1652   /// issue that occurred on one of the buildbots which cannot be reproduced
1653   /// without having access to the properietary compiler (see comments on
1654   /// D98509). The issue is currently under investigation and this workaround
1655   /// will be removed as soon as possible.
1656   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1657                                        unsigned SmallestType,
1658                                        unsigned WidestType,
1659                                        const ElementCount &MaxSafeVF);
1660 
1661   /// \return the maximum legal scalable VF, based on the safe max number
1662   /// of elements.
1663   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1664 
1665   /// The vectorization cost is a combination of the cost itself and a boolean
1666   /// indicating whether any of the contributing operations will actually
1667   /// operate on vector values after type legalization in the backend. If this
1668   /// latter value is false, then all operations will be scalarized (i.e. no
1669   /// vectorization has actually taken place).
1670   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1671 
1672   /// Returns the expected execution cost. The unit of the cost does
1673   /// not matter because we use the 'cost' units to compare different
1674   /// vector widths. The cost that is returned is *not* normalized by
1675   /// the factor width. If \p Invalid is not nullptr, this function
1676   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1677   /// each instruction that has an Invalid cost for the given VF.
1678   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1679   VectorizationCostTy
1680   expectedCost(ElementCount VF,
1681                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1682 
1683   /// Returns the execution time cost of an instruction for a given vector
1684   /// width. Vector width of one means scalar.
1685   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1686 
1687   /// The cost-computation logic from getInstructionCost which provides
1688   /// the vector type as an output parameter.
1689   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1690                                      Type *&VectorTy);
1691 
1692   /// Return the cost of instructions in an inloop reduction pattern, if I is
1693   /// part of that pattern.
1694   Optional<InstructionCost>
1695   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1696                           TTI::TargetCostKind CostKind);
1697 
1698   /// Calculate vectorization cost of memory instruction \p I.
1699   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1700 
1701   /// The cost computation for scalarized memory instruction.
1702   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1703 
1704   /// The cost computation for interleaving group of memory instructions.
1705   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1706 
1707   /// The cost computation for Gather/Scatter instruction.
1708   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1709 
1710   /// The cost computation for widening instruction \p I with consecutive
1711   /// memory access.
1712   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1713 
1714   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1715   /// Load: scalar load + broadcast.
1716   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1717   /// element)
1718   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1719 
1720   /// Estimate the overhead of scalarizing an instruction. This is a
1721   /// convenience wrapper for the type-based getScalarizationOverhead API.
1722   InstructionCost getScalarizationOverhead(Instruction *I,
1723                                            ElementCount VF) const;
1724 
1725   /// Returns whether the instruction is a load or store and will be a emitted
1726   /// as a vector operation.
1727   bool isConsecutiveLoadOrStore(Instruction *I);
1728 
1729   /// Returns true if an artificially high cost for emulated masked memrefs
1730   /// should be used.
1731   bool useEmulatedMaskMemRefHack(Instruction *I);
1732 
1733   /// Map of scalar integer values to the smallest bitwidth they can be legally
1734   /// represented as. The vector equivalents of these values should be truncated
1735   /// to this type.
1736   MapVector<Instruction *, uint64_t> MinBWs;
1737 
1738   /// A type representing the costs for instructions if they were to be
1739   /// scalarized rather than vectorized. The entries are Instruction-Cost
1740   /// pairs.
1741   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1742 
1743   /// A set containing all BasicBlocks that are known to present after
1744   /// vectorization as a predicated block.
1745   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1746 
1747   /// Records whether it is allowed to have the original scalar loop execute at
1748   /// least once. This may be needed as a fallback loop in case runtime
1749   /// aliasing/dependence checks fail, or to handle the tail/remainder
1750   /// iterations when the trip count is unknown or doesn't divide by the VF,
1751   /// or as a peel-loop to handle gaps in interleave-groups.
1752   /// Under optsize and when the trip count is very small we don't allow any
1753   /// iterations to execute in the scalar loop.
1754   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1755 
1756   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1757   bool FoldTailByMasking = false;
1758 
1759   /// A map holding scalar costs for different vectorization factors. The
1760   /// presence of a cost for an instruction in the mapping indicates that the
1761   /// instruction will be scalarized when vectorizing with the associated
1762   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1763   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1764 
1765   /// Holds the instructions known to be uniform after vectorization.
1766   /// The data is collected per VF.
1767   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1768 
1769   /// Holds the instructions known to be scalar after vectorization.
1770   /// The data is collected per VF.
1771   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1772 
1773   /// Holds the instructions (address computations) that are forced to be
1774   /// scalarized.
1775   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1776 
1777   /// PHINodes of the reductions that should be expanded in-loop along with
1778   /// their associated chains of reduction operations, in program order from top
1779   /// (PHI) to bottom
1780   ReductionChainMap InLoopReductionChains;
1781 
1782   /// A Map of inloop reduction operations and their immediate chain operand.
1783   /// FIXME: This can be removed once reductions can be costed correctly in
1784   /// vplan. This was added to allow quick lookup to the inloop operations,
1785   /// without having to loop through InLoopReductionChains.
1786   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1787 
1788   /// Returns the expected difference in cost from scalarizing the expression
1789   /// feeding a predicated instruction \p PredInst. The instructions to
1790   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1791   /// non-negative return value implies the expression will be scalarized.
1792   /// Currently, only single-use chains are considered for scalarization.
1793   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1794                               ElementCount VF);
1795 
1796   /// Collect the instructions that are uniform after vectorization. An
1797   /// instruction is uniform if we represent it with a single scalar value in
1798   /// the vectorized loop corresponding to each vector iteration. Examples of
1799   /// uniform instructions include pointer operands of consecutive or
1800   /// interleaved memory accesses. Note that although uniformity implies an
1801   /// instruction will be scalar, the reverse is not true. In general, a
1802   /// scalarized instruction will be represented by VF scalar values in the
1803   /// vectorized loop, each corresponding to an iteration of the original
1804   /// scalar loop.
1805   void collectLoopUniforms(ElementCount VF);
1806 
1807   /// Collect the instructions that are scalar after vectorization. An
1808   /// instruction is scalar if it is known to be uniform or will be scalarized
1809   /// during vectorization. Non-uniform scalarized instructions will be
1810   /// represented by VF values in the vectorized loop, each corresponding to an
1811   /// iteration of the original scalar loop.
1812   void collectLoopScalars(ElementCount VF);
1813 
1814   /// Keeps cost model vectorization decision and cost for instructions.
1815   /// Right now it is used for memory instructions only.
1816   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1817                                 std::pair<InstWidening, InstructionCost>>;
1818 
1819   DecisionList WideningDecisions;
1820 
1821   /// Returns true if \p V is expected to be vectorized and it needs to be
1822   /// extracted.
1823   bool needsExtract(Value *V, ElementCount VF) const {
1824     Instruction *I = dyn_cast<Instruction>(V);
1825     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1826         TheLoop->isLoopInvariant(I))
1827       return false;
1828 
1829     // Assume we can vectorize V (and hence we need extraction) if the
1830     // scalars are not computed yet. This can happen, because it is called
1831     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1832     // the scalars are collected. That should be a safe assumption in most
1833     // cases, because we check if the operands have vectorizable types
1834     // beforehand in LoopVectorizationLegality.
1835     return Scalars.find(VF) == Scalars.end() ||
1836            !isScalarAfterVectorization(I, VF);
1837   };
1838 
1839   /// Returns a range containing only operands needing to be extracted.
1840   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1841                                                    ElementCount VF) const {
1842     return SmallVector<Value *, 4>(make_filter_range(
1843         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1844   }
1845 
1846   /// Determines if we have the infrastructure to vectorize loop \p L and its
1847   /// epilogue, assuming the main loop is vectorized by \p VF.
1848   bool isCandidateForEpilogueVectorization(const Loop &L,
1849                                            const ElementCount VF) const;
1850 
1851   /// Returns true if epilogue vectorization is considered profitable, and
1852   /// false otherwise.
1853   /// \p VF is the vectorization factor chosen for the original loop.
1854   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1855 
1856 public:
1857   /// The loop that we evaluate.
1858   Loop *TheLoop;
1859 
1860   /// Predicated scalar evolution analysis.
1861   PredicatedScalarEvolution &PSE;
1862 
1863   /// Loop Info analysis.
1864   LoopInfo *LI;
1865 
1866   /// Vectorization legality.
1867   LoopVectorizationLegality *Legal;
1868 
1869   /// Vector target information.
1870   const TargetTransformInfo &TTI;
1871 
1872   /// Target Library Info.
1873   const TargetLibraryInfo *TLI;
1874 
1875   /// Demanded bits analysis.
1876   DemandedBits *DB;
1877 
1878   /// Assumption cache.
1879   AssumptionCache *AC;
1880 
1881   /// Interface to emit optimization remarks.
1882   OptimizationRemarkEmitter *ORE;
1883 
1884   const Function *TheFunction;
1885 
1886   /// Loop Vectorize Hint.
1887   const LoopVectorizeHints *Hints;
1888 
1889   /// The interleave access information contains groups of interleaved accesses
1890   /// with the same stride and close to each other.
1891   InterleavedAccessInfo &InterleaveInfo;
1892 
1893   /// Values to ignore in the cost model.
1894   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1895 
1896   /// Values to ignore in the cost model when VF > 1.
1897   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1898 
1899   /// All element types found in the loop.
1900   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1901 
1902   /// Profitable vector factors.
1903   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1904 };
1905 } // end namespace llvm
1906 
1907 /// Helper struct to manage generating runtime checks for vectorization.
1908 ///
1909 /// The runtime checks are created up-front in temporary blocks to allow better
1910 /// estimating the cost and un-linked from the existing IR. After deciding to
1911 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1912 /// temporary blocks are completely removed.
1913 class GeneratedRTChecks {
1914   /// Basic block which contains the generated SCEV checks, if any.
1915   BasicBlock *SCEVCheckBlock = nullptr;
1916 
1917   /// The value representing the result of the generated SCEV checks. If it is
1918   /// nullptr, either no SCEV checks have been generated or they have been used.
1919   Value *SCEVCheckCond = nullptr;
1920 
1921   /// Basic block which contains the generated memory runtime checks, if any.
1922   BasicBlock *MemCheckBlock = nullptr;
1923 
1924   /// The value representing the result of the generated memory runtime checks.
1925   /// If it is nullptr, either no memory runtime checks have been generated or
1926   /// they have been used.
1927   Instruction *MemRuntimeCheckCond = nullptr;
1928 
1929   DominatorTree *DT;
1930   LoopInfo *LI;
1931 
1932   SCEVExpander SCEVExp;
1933   SCEVExpander MemCheckExp;
1934 
1935 public:
1936   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1937                     const DataLayout &DL)
1938       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1939         MemCheckExp(SE, DL, "scev.check") {}
1940 
1941   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1942   /// accurately estimate the cost of the runtime checks. The blocks are
1943   /// un-linked from the IR and is added back during vector code generation. If
1944   /// there is no vector code generation, the check blocks are removed
1945   /// completely.
1946   void Create(Loop *L, const LoopAccessInfo &LAI,
1947               const SCEVUnionPredicate &UnionPred) {
1948 
1949     BasicBlock *LoopHeader = L->getHeader();
1950     BasicBlock *Preheader = L->getLoopPreheader();
1951 
1952     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1953     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1954     // may be used by SCEVExpander. The blocks will be un-linked from their
1955     // predecessors and removed from LI & DT at the end of the function.
1956     if (!UnionPred.isAlwaysTrue()) {
1957       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1958                                   nullptr, "vector.scevcheck");
1959 
1960       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1961           &UnionPred, SCEVCheckBlock->getTerminator());
1962     }
1963 
1964     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1965     if (RtPtrChecking.Need) {
1966       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1967       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1968                                  "vector.memcheck");
1969 
1970       std::tie(std::ignore, MemRuntimeCheckCond) =
1971           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1972                            RtPtrChecking.getChecks(), MemCheckExp);
1973       assert(MemRuntimeCheckCond &&
1974              "no RT checks generated although RtPtrChecking "
1975              "claimed checks are required");
1976     }
1977 
1978     if (!MemCheckBlock && !SCEVCheckBlock)
1979       return;
1980 
1981     // Unhook the temporary block with the checks, update various places
1982     // accordingly.
1983     if (SCEVCheckBlock)
1984       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1985     if (MemCheckBlock)
1986       MemCheckBlock->replaceAllUsesWith(Preheader);
1987 
1988     if (SCEVCheckBlock) {
1989       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1990       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1991       Preheader->getTerminator()->eraseFromParent();
1992     }
1993     if (MemCheckBlock) {
1994       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1995       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1996       Preheader->getTerminator()->eraseFromParent();
1997     }
1998 
1999     DT->changeImmediateDominator(LoopHeader, Preheader);
2000     if (MemCheckBlock) {
2001       DT->eraseNode(MemCheckBlock);
2002       LI->removeBlock(MemCheckBlock);
2003     }
2004     if (SCEVCheckBlock) {
2005       DT->eraseNode(SCEVCheckBlock);
2006       LI->removeBlock(SCEVCheckBlock);
2007     }
2008   }
2009 
2010   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2011   /// unused.
2012   ~GeneratedRTChecks() {
2013     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2014     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2015     if (!SCEVCheckCond)
2016       SCEVCleaner.markResultUsed();
2017 
2018     if (!MemRuntimeCheckCond)
2019       MemCheckCleaner.markResultUsed();
2020 
2021     if (MemRuntimeCheckCond) {
2022       auto &SE = *MemCheckExp.getSE();
2023       // Memory runtime check generation creates compares that use expanded
2024       // values. Remove them before running the SCEVExpanderCleaners.
2025       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2026         if (MemCheckExp.isInsertedInstruction(&I))
2027           continue;
2028         SE.forgetValue(&I);
2029         SE.eraseValueFromMap(&I);
2030         I.eraseFromParent();
2031       }
2032     }
2033     MemCheckCleaner.cleanup();
2034     SCEVCleaner.cleanup();
2035 
2036     if (SCEVCheckCond)
2037       SCEVCheckBlock->eraseFromParent();
2038     if (MemRuntimeCheckCond)
2039       MemCheckBlock->eraseFromParent();
2040   }
2041 
2042   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2043   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2044   /// depending on the generated condition.
2045   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2046                              BasicBlock *LoopVectorPreHeader,
2047                              BasicBlock *LoopExitBlock) {
2048     if (!SCEVCheckCond)
2049       return nullptr;
2050     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2051       if (C->isZero())
2052         return nullptr;
2053 
2054     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2055 
2056     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2057     // Create new preheader for vector loop.
2058     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2059       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2060 
2061     SCEVCheckBlock->getTerminator()->eraseFromParent();
2062     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2063     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2064                                                 SCEVCheckBlock);
2065 
2066     DT->addNewBlock(SCEVCheckBlock, Pred);
2067     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2068 
2069     ReplaceInstWithInst(
2070         SCEVCheckBlock->getTerminator(),
2071         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2072     // Mark the check as used, to prevent it from being removed during cleanup.
2073     SCEVCheckCond = nullptr;
2074     return SCEVCheckBlock;
2075   }
2076 
2077   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2078   /// the branches to branch to the vector preheader or \p Bypass, depending on
2079   /// the generated condition.
2080   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2081                                    BasicBlock *LoopVectorPreHeader) {
2082     // Check if we generated code that checks in runtime if arrays overlap.
2083     if (!MemRuntimeCheckCond)
2084       return nullptr;
2085 
2086     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2087     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2088                                                 MemCheckBlock);
2089 
2090     DT->addNewBlock(MemCheckBlock, Pred);
2091     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2092     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2093 
2094     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2095       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2096 
2097     ReplaceInstWithInst(
2098         MemCheckBlock->getTerminator(),
2099         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2100     MemCheckBlock->getTerminator()->setDebugLoc(
2101         Pred->getTerminator()->getDebugLoc());
2102 
2103     // Mark the check as used, to prevent it from being removed during cleanup.
2104     MemRuntimeCheckCond = nullptr;
2105     return MemCheckBlock;
2106   }
2107 };
2108 
2109 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2110 // vectorization. The loop needs to be annotated with #pragma omp simd
2111 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2112 // vector length information is not provided, vectorization is not considered
2113 // explicit. Interleave hints are not allowed either. These limitations will be
2114 // relaxed in the future.
2115 // Please, note that we are currently forced to abuse the pragma 'clang
2116 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2117 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2118 // provides *explicit vectorization hints* (LV can bypass legal checks and
2119 // assume that vectorization is legal). However, both hints are implemented
2120 // using the same metadata (llvm.loop.vectorize, processed by
2121 // LoopVectorizeHints). This will be fixed in the future when the native IR
2122 // representation for pragma 'omp simd' is introduced.
2123 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2124                                    OptimizationRemarkEmitter *ORE) {
2125   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2126   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2127 
2128   // Only outer loops with an explicit vectorization hint are supported.
2129   // Unannotated outer loops are ignored.
2130   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2131     return false;
2132 
2133   Function *Fn = OuterLp->getHeader()->getParent();
2134   if (!Hints.allowVectorization(Fn, OuterLp,
2135                                 true /*VectorizeOnlyWhenForced*/)) {
2136     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2137     return false;
2138   }
2139 
2140   if (Hints.getInterleave() > 1) {
2141     // TODO: Interleave support is future work.
2142     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2143                          "outer loops.\n");
2144     Hints.emitRemarkWithHints();
2145     return false;
2146   }
2147 
2148   return true;
2149 }
2150 
2151 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2152                                   OptimizationRemarkEmitter *ORE,
2153                                   SmallVectorImpl<Loop *> &V) {
2154   // Collect inner loops and outer loops without irreducible control flow. For
2155   // now, only collect outer loops that have explicit vectorization hints. If we
2156   // are stress testing the VPlan H-CFG construction, we collect the outermost
2157   // loop of every loop nest.
2158   if (L.isInnermost() || VPlanBuildStressTest ||
2159       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2160     LoopBlocksRPO RPOT(&L);
2161     RPOT.perform(LI);
2162     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2163       V.push_back(&L);
2164       // TODO: Collect inner loops inside marked outer loops in case
2165       // vectorization fails for the outer loop. Do not invoke
2166       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2167       // already known to be reducible. We can use an inherited attribute for
2168       // that.
2169       return;
2170     }
2171   }
2172   for (Loop *InnerL : L)
2173     collectSupportedLoops(*InnerL, LI, ORE, V);
2174 }
2175 
2176 namespace {
2177 
2178 /// The LoopVectorize Pass.
2179 struct LoopVectorize : public FunctionPass {
2180   /// Pass identification, replacement for typeid
2181   static char ID;
2182 
2183   LoopVectorizePass Impl;
2184 
2185   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2186                          bool VectorizeOnlyWhenForced = false)
2187       : FunctionPass(ID),
2188         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2189     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2190   }
2191 
2192   bool runOnFunction(Function &F) override {
2193     if (skipFunction(F))
2194       return false;
2195 
2196     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2197     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2198     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2199     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2200     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2201     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2202     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2203     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2204     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2205     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2206     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2207     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2208     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2209 
2210     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2211         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2212 
2213     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2214                         GetLAA, *ORE, PSI).MadeAnyChange;
2215   }
2216 
2217   void getAnalysisUsage(AnalysisUsage &AU) const override {
2218     AU.addRequired<AssumptionCacheTracker>();
2219     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2220     AU.addRequired<DominatorTreeWrapperPass>();
2221     AU.addRequired<LoopInfoWrapperPass>();
2222     AU.addRequired<ScalarEvolutionWrapperPass>();
2223     AU.addRequired<TargetTransformInfoWrapperPass>();
2224     AU.addRequired<AAResultsWrapperPass>();
2225     AU.addRequired<LoopAccessLegacyAnalysis>();
2226     AU.addRequired<DemandedBitsWrapperPass>();
2227     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2228     AU.addRequired<InjectTLIMappingsLegacy>();
2229 
2230     // We currently do not preserve loopinfo/dominator analyses with outer loop
2231     // vectorization. Until this is addressed, mark these analyses as preserved
2232     // only for non-VPlan-native path.
2233     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2234     if (!EnableVPlanNativePath) {
2235       AU.addPreserved<LoopInfoWrapperPass>();
2236       AU.addPreserved<DominatorTreeWrapperPass>();
2237     }
2238 
2239     AU.addPreserved<BasicAAWrapperPass>();
2240     AU.addPreserved<GlobalsAAWrapperPass>();
2241     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2242   }
2243 };
2244 
2245 } // end anonymous namespace
2246 
2247 //===----------------------------------------------------------------------===//
2248 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2249 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2250 //===----------------------------------------------------------------------===//
2251 
2252 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2253   // We need to place the broadcast of invariant variables outside the loop,
2254   // but only if it's proven safe to do so. Else, broadcast will be inside
2255   // vector loop body.
2256   Instruction *Instr = dyn_cast<Instruction>(V);
2257   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2258                      (!Instr ||
2259                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2260   // Place the code for broadcasting invariant variables in the new preheader.
2261   IRBuilder<>::InsertPointGuard Guard(Builder);
2262   if (SafeToHoist)
2263     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2264 
2265   // Broadcast the scalar into all locations in the vector.
2266   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2267 
2268   return Shuf;
2269 }
2270 
2271 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2272     const InductionDescriptor &II, Value *Step, Value *Start,
2273     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2274     VPTransformState &State) {
2275   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2276          "Expected either an induction phi-node or a truncate of it!");
2277 
2278   // Construct the initial value of the vector IV in the vector loop preheader
2279   auto CurrIP = Builder.saveIP();
2280   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2281   if (isa<TruncInst>(EntryVal)) {
2282     assert(Start->getType()->isIntegerTy() &&
2283            "Truncation requires an integer type");
2284     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2285     Step = Builder.CreateTrunc(Step, TruncType);
2286     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2287   }
2288   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2289   Value *SteppedStart =
2290       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2291 
2292   // We create vector phi nodes for both integer and floating-point induction
2293   // variables. Here, we determine the kind of arithmetic we will perform.
2294   Instruction::BinaryOps AddOp;
2295   Instruction::BinaryOps MulOp;
2296   if (Step->getType()->isIntegerTy()) {
2297     AddOp = Instruction::Add;
2298     MulOp = Instruction::Mul;
2299   } else {
2300     AddOp = II.getInductionOpcode();
2301     MulOp = Instruction::FMul;
2302   }
2303 
2304   // Multiply the vectorization factor by the step using integer or
2305   // floating-point arithmetic as appropriate.
2306   Type *StepType = Step->getType();
2307   if (Step->getType()->isFloatingPointTy())
2308     StepType = IntegerType::get(StepType->getContext(),
2309                                 StepType->getScalarSizeInBits());
2310   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2311   if (Step->getType()->isFloatingPointTy())
2312     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2313   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2314 
2315   // Create a vector splat to use in the induction update.
2316   //
2317   // FIXME: If the step is non-constant, we create the vector splat with
2318   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2319   //        handle a constant vector splat.
2320   Value *SplatVF = isa<Constant>(Mul)
2321                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2322                        : Builder.CreateVectorSplat(VF, Mul);
2323   Builder.restoreIP(CurrIP);
2324 
2325   // We may need to add the step a number of times, depending on the unroll
2326   // factor. The last of those goes into the PHI.
2327   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2328                                     &*LoopVectorBody->getFirstInsertionPt());
2329   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2330   Instruction *LastInduction = VecInd;
2331   for (unsigned Part = 0; Part < UF; ++Part) {
2332     State.set(Def, LastInduction, Part);
2333 
2334     if (isa<TruncInst>(EntryVal))
2335       addMetadata(LastInduction, EntryVal);
2336     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2337                                           State, Part);
2338 
2339     LastInduction = cast<Instruction>(
2340         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2341     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2342   }
2343 
2344   // Move the last step to the end of the latch block. This ensures consistent
2345   // placement of all induction updates.
2346   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2347   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2348   auto *ICmp = cast<Instruction>(Br->getCondition());
2349   LastInduction->moveBefore(ICmp);
2350   LastInduction->setName("vec.ind.next");
2351 
2352   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2353   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2354 }
2355 
2356 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2357   return Cost->isScalarAfterVectorization(I, VF) ||
2358          Cost->isProfitableToScalarize(I, VF);
2359 }
2360 
2361 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2362   if (shouldScalarizeInstruction(IV))
2363     return true;
2364   auto isScalarInst = [&](User *U) -> bool {
2365     auto *I = cast<Instruction>(U);
2366     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2367   };
2368   return llvm::any_of(IV->users(), isScalarInst);
2369 }
2370 
2371 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2372     const InductionDescriptor &ID, const Instruction *EntryVal,
2373     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2374     unsigned Part, unsigned Lane) {
2375   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2376          "Expected either an induction phi-node or a truncate of it!");
2377 
2378   // This induction variable is not the phi from the original loop but the
2379   // newly-created IV based on the proof that casted Phi is equal to the
2380   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2381   // re-uses the same InductionDescriptor that original IV uses but we don't
2382   // have to do any recording in this case - that is done when original IV is
2383   // processed.
2384   if (isa<TruncInst>(EntryVal))
2385     return;
2386 
2387   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2388   if (Casts.empty())
2389     return;
2390   // Only the first Cast instruction in the Casts vector is of interest.
2391   // The rest of the Casts (if exist) have no uses outside the
2392   // induction update chain itself.
2393   if (Lane < UINT_MAX)
2394     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2395   else
2396     State.set(CastDef, VectorLoopVal, Part);
2397 }
2398 
2399 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2400                                                 TruncInst *Trunc, VPValue *Def,
2401                                                 VPValue *CastDef,
2402                                                 VPTransformState &State) {
2403   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2404          "Primary induction variable must have an integer type");
2405 
2406   auto II = Legal->getInductionVars().find(IV);
2407   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2408 
2409   auto ID = II->second;
2410   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2411 
2412   // The value from the original loop to which we are mapping the new induction
2413   // variable.
2414   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2415 
2416   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2417 
2418   // Generate code for the induction step. Note that induction steps are
2419   // required to be loop-invariant
2420   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2421     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2422            "Induction step should be loop invariant");
2423     if (PSE.getSE()->isSCEVable(IV->getType())) {
2424       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2425       return Exp.expandCodeFor(Step, Step->getType(),
2426                                LoopVectorPreHeader->getTerminator());
2427     }
2428     return cast<SCEVUnknown>(Step)->getValue();
2429   };
2430 
2431   // The scalar value to broadcast. This is derived from the canonical
2432   // induction variable. If a truncation type is given, truncate the canonical
2433   // induction variable and step. Otherwise, derive these values from the
2434   // induction descriptor.
2435   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2436     Value *ScalarIV = Induction;
2437     if (IV != OldInduction) {
2438       ScalarIV = IV->getType()->isIntegerTy()
2439                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2440                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2441                                           IV->getType());
2442       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2443       ScalarIV->setName("offset.idx");
2444     }
2445     if (Trunc) {
2446       auto *TruncType = cast<IntegerType>(Trunc->getType());
2447       assert(Step->getType()->isIntegerTy() &&
2448              "Truncation requires an integer step");
2449       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2450       Step = Builder.CreateTrunc(Step, TruncType);
2451     }
2452     return ScalarIV;
2453   };
2454 
2455   // Create the vector values from the scalar IV, in the absence of creating a
2456   // vector IV.
2457   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2458     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2459     for (unsigned Part = 0; Part < UF; ++Part) {
2460       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2461       Value *EntryPart =
2462           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2463                         ID.getInductionOpcode());
2464       State.set(Def, EntryPart, Part);
2465       if (Trunc)
2466         addMetadata(EntryPart, Trunc);
2467       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2468                                             State, Part);
2469     }
2470   };
2471 
2472   // Fast-math-flags propagate from the original induction instruction.
2473   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2474   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2475     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2476 
2477   // Now do the actual transformations, and start with creating the step value.
2478   Value *Step = CreateStepValue(ID.getStep());
2479   if (VF.isZero() || VF.isScalar()) {
2480     Value *ScalarIV = CreateScalarIV(Step);
2481     CreateSplatIV(ScalarIV, Step);
2482     return;
2483   }
2484 
2485   // Determine if we want a scalar version of the induction variable. This is
2486   // true if the induction variable itself is not widened, or if it has at
2487   // least one user in the loop that is not widened.
2488   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2489   if (!NeedsScalarIV) {
2490     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2491                                     State);
2492     return;
2493   }
2494 
2495   // Try to create a new independent vector induction variable. If we can't
2496   // create the phi node, we will splat the scalar induction variable in each
2497   // loop iteration.
2498   if (!shouldScalarizeInstruction(EntryVal)) {
2499     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2500                                     State);
2501     Value *ScalarIV = CreateScalarIV(Step);
2502     // Create scalar steps that can be used by instructions we will later
2503     // scalarize. Note that the addition of the scalar steps will not increase
2504     // the number of instructions in the loop in the common case prior to
2505     // InstCombine. We will be trading one vector extract for each scalar step.
2506     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2507     return;
2508   }
2509 
2510   // All IV users are scalar instructions, so only emit a scalar IV, not a
2511   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2512   // predicate used by the masked loads/stores.
2513   Value *ScalarIV = CreateScalarIV(Step);
2514   if (!Cost->isScalarEpilogueAllowed())
2515     CreateSplatIV(ScalarIV, Step);
2516   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2517 }
2518 
2519 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2520                                           Instruction::BinaryOps BinOp) {
2521   // Create and check the types.
2522   auto *ValVTy = cast<VectorType>(Val->getType());
2523   ElementCount VLen = ValVTy->getElementCount();
2524 
2525   Type *STy = Val->getType()->getScalarType();
2526   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2527          "Induction Step must be an integer or FP");
2528   assert(Step->getType() == STy && "Step has wrong type");
2529 
2530   SmallVector<Constant *, 8> Indices;
2531 
2532   // Create a vector of consecutive numbers from zero to VF.
2533   VectorType *InitVecValVTy = ValVTy;
2534   Type *InitVecValSTy = STy;
2535   if (STy->isFloatingPointTy()) {
2536     InitVecValSTy =
2537         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2538     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2539   }
2540   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2541 
2542   // Add on StartIdx
2543   Value *StartIdxSplat = Builder.CreateVectorSplat(
2544       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2545   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2546 
2547   if (STy->isIntegerTy()) {
2548     Step = Builder.CreateVectorSplat(VLen, Step);
2549     assert(Step->getType() == Val->getType() && "Invalid step vec");
2550     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2551     // which can be found from the original scalar operations.
2552     Step = Builder.CreateMul(InitVec, Step);
2553     return Builder.CreateAdd(Val, Step, "induction");
2554   }
2555 
2556   // Floating point induction.
2557   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2558          "Binary Opcode should be specified for FP induction");
2559   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2560   Step = Builder.CreateVectorSplat(VLen, Step);
2561   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2562   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2563 }
2564 
2565 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2566                                            Instruction *EntryVal,
2567                                            const InductionDescriptor &ID,
2568                                            VPValue *Def, VPValue *CastDef,
2569                                            VPTransformState &State) {
2570   // We shouldn't have to build scalar steps if we aren't vectorizing.
2571   assert(VF.isVector() && "VF should be greater than one");
2572   // Get the value type and ensure it and the step have the same integer type.
2573   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2574   assert(ScalarIVTy == Step->getType() &&
2575          "Val and Step should have the same type");
2576 
2577   // We build scalar steps for both integer and floating-point induction
2578   // variables. Here, we determine the kind of arithmetic we will perform.
2579   Instruction::BinaryOps AddOp;
2580   Instruction::BinaryOps MulOp;
2581   if (ScalarIVTy->isIntegerTy()) {
2582     AddOp = Instruction::Add;
2583     MulOp = Instruction::Mul;
2584   } else {
2585     AddOp = ID.getInductionOpcode();
2586     MulOp = Instruction::FMul;
2587   }
2588 
2589   // Determine the number of scalars we need to generate for each unroll
2590   // iteration. If EntryVal is uniform, we only need to generate the first
2591   // lane. Otherwise, we generate all VF values.
2592   bool IsUniform =
2593       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2594   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2595   // Compute the scalar steps and save the results in State.
2596   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2597                                      ScalarIVTy->getScalarSizeInBits());
2598   Type *VecIVTy = nullptr;
2599   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2600   if (!IsUniform && VF.isScalable()) {
2601     VecIVTy = VectorType::get(ScalarIVTy, VF);
2602     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2603     SplatStep = Builder.CreateVectorSplat(VF, Step);
2604     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2605   }
2606 
2607   for (unsigned Part = 0; Part < UF; ++Part) {
2608     Value *StartIdx0 =
2609         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2610 
2611     if (!IsUniform && VF.isScalable()) {
2612       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2613       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2614       if (ScalarIVTy->isFloatingPointTy())
2615         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2616       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2617       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2618       State.set(Def, Add, Part);
2619       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2620                                             Part);
2621       // It's useful to record the lane values too for the known minimum number
2622       // of elements so we do those below. This improves the code quality when
2623       // trying to extract the first element, for example.
2624     }
2625 
2626     if (ScalarIVTy->isFloatingPointTy())
2627       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2628 
2629     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2630       Value *StartIdx = Builder.CreateBinOp(
2631           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2632       // The step returned by `createStepForVF` is a runtime-evaluated value
2633       // when VF is scalable. Otherwise, it should be folded into a Constant.
2634       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2635              "Expected StartIdx to be folded to a constant when VF is not "
2636              "scalable");
2637       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2638       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2639       State.set(Def, Add, VPIteration(Part, Lane));
2640       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2641                                             Part, Lane);
2642     }
2643   }
2644 }
2645 
2646 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2647                                                     const VPIteration &Instance,
2648                                                     VPTransformState &State) {
2649   Value *ScalarInst = State.get(Def, Instance);
2650   Value *VectorValue = State.get(Def, Instance.Part);
2651   VectorValue = Builder.CreateInsertElement(
2652       VectorValue, ScalarInst,
2653       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2654   State.set(Def, VectorValue, Instance.Part);
2655 }
2656 
2657 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2658   assert(Vec->getType()->isVectorTy() && "Invalid type");
2659   return Builder.CreateVectorReverse(Vec, "reverse");
2660 }
2661 
2662 // Return whether we allow using masked interleave-groups (for dealing with
2663 // strided loads/stores that reside in predicated blocks, or for dealing
2664 // with gaps).
2665 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2666   // If an override option has been passed in for interleaved accesses, use it.
2667   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2668     return EnableMaskedInterleavedMemAccesses;
2669 
2670   return TTI.enableMaskedInterleavedAccessVectorization();
2671 }
2672 
2673 // Try to vectorize the interleave group that \p Instr belongs to.
2674 //
2675 // E.g. Translate following interleaved load group (factor = 3):
2676 //   for (i = 0; i < N; i+=3) {
2677 //     R = Pic[i];             // Member of index 0
2678 //     G = Pic[i+1];           // Member of index 1
2679 //     B = Pic[i+2];           // Member of index 2
2680 //     ... // do something to R, G, B
2681 //   }
2682 // To:
2683 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2684 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2685 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2686 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2687 //
2688 // Or translate following interleaved store group (factor = 3):
2689 //   for (i = 0; i < N; i+=3) {
2690 //     ... do something to R, G, B
2691 //     Pic[i]   = R;           // Member of index 0
2692 //     Pic[i+1] = G;           // Member of index 1
2693 //     Pic[i+2] = B;           // Member of index 2
2694 //   }
2695 // To:
2696 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2697 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2698 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2699 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2700 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2701 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2702     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2703     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2704     VPValue *BlockInMask) {
2705   Instruction *Instr = Group->getInsertPos();
2706   const DataLayout &DL = Instr->getModule()->getDataLayout();
2707 
2708   // Prepare for the vector type of the interleaved load/store.
2709   Type *ScalarTy = getLoadStoreType(Instr);
2710   unsigned InterleaveFactor = Group->getFactor();
2711   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2712   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2713 
2714   // Prepare for the new pointers.
2715   SmallVector<Value *, 2> AddrParts;
2716   unsigned Index = Group->getIndex(Instr);
2717 
2718   // TODO: extend the masked interleaved-group support to reversed access.
2719   assert((!BlockInMask || !Group->isReverse()) &&
2720          "Reversed masked interleave-group not supported.");
2721 
2722   // If the group is reverse, adjust the index to refer to the last vector lane
2723   // instead of the first. We adjust the index from the first vector lane,
2724   // rather than directly getting the pointer for lane VF - 1, because the
2725   // pointer operand of the interleaved access is supposed to be uniform. For
2726   // uniform instructions, we're only required to generate a value for the
2727   // first vector lane in each unroll iteration.
2728   if (Group->isReverse())
2729     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2730 
2731   for (unsigned Part = 0; Part < UF; Part++) {
2732     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2733     setDebugLocFromInst(AddrPart);
2734 
2735     // Notice current instruction could be any index. Need to adjust the address
2736     // to the member of index 0.
2737     //
2738     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2739     //       b = A[i];       // Member of index 0
2740     // Current pointer is pointed to A[i+1], adjust it to A[i].
2741     //
2742     // E.g.  A[i+1] = a;     // Member of index 1
2743     //       A[i]   = b;     // Member of index 0
2744     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2745     // Current pointer is pointed to A[i+2], adjust it to A[i].
2746 
2747     bool InBounds = false;
2748     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2749       InBounds = gep->isInBounds();
2750     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2751     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2752 
2753     // Cast to the vector pointer type.
2754     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2755     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2756     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2757   }
2758 
2759   setDebugLocFromInst(Instr);
2760   Value *PoisonVec = PoisonValue::get(VecTy);
2761 
2762   Value *MaskForGaps = nullptr;
2763   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2764     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2765     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2766   }
2767 
2768   // Vectorize the interleaved load group.
2769   if (isa<LoadInst>(Instr)) {
2770     // For each unroll part, create a wide load for the group.
2771     SmallVector<Value *, 2> NewLoads;
2772     for (unsigned Part = 0; Part < UF; Part++) {
2773       Instruction *NewLoad;
2774       if (BlockInMask || MaskForGaps) {
2775         assert(useMaskedInterleavedAccesses(*TTI) &&
2776                "masked interleaved groups are not allowed.");
2777         Value *GroupMask = MaskForGaps;
2778         if (BlockInMask) {
2779           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2780           Value *ShuffledMask = Builder.CreateShuffleVector(
2781               BlockInMaskPart,
2782               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2783               "interleaved.mask");
2784           GroupMask = MaskForGaps
2785                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2786                                                 MaskForGaps)
2787                           : ShuffledMask;
2788         }
2789         NewLoad =
2790             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2791                                      GroupMask, PoisonVec, "wide.masked.vec");
2792       }
2793       else
2794         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2795                                             Group->getAlign(), "wide.vec");
2796       Group->addMetadata(NewLoad);
2797       NewLoads.push_back(NewLoad);
2798     }
2799 
2800     // For each member in the group, shuffle out the appropriate data from the
2801     // wide loads.
2802     unsigned J = 0;
2803     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2804       Instruction *Member = Group->getMember(I);
2805 
2806       // Skip the gaps in the group.
2807       if (!Member)
2808         continue;
2809 
2810       auto StrideMask =
2811           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2812       for (unsigned Part = 0; Part < UF; Part++) {
2813         Value *StridedVec = Builder.CreateShuffleVector(
2814             NewLoads[Part], StrideMask, "strided.vec");
2815 
2816         // If this member has different type, cast the result type.
2817         if (Member->getType() != ScalarTy) {
2818           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2819           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2820           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2821         }
2822 
2823         if (Group->isReverse())
2824           StridedVec = reverseVector(StridedVec);
2825 
2826         State.set(VPDefs[J], StridedVec, Part);
2827       }
2828       ++J;
2829     }
2830     return;
2831   }
2832 
2833   // The sub vector type for current instruction.
2834   auto *SubVT = VectorType::get(ScalarTy, VF);
2835 
2836   // Vectorize the interleaved store group.
2837   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2838   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2839          "masked interleaved groups are not allowed.");
2840   assert((!MaskForGaps || !VF.isScalable()) &&
2841          "masking gaps for scalable vectors is not yet supported.");
2842   for (unsigned Part = 0; Part < UF; Part++) {
2843     // Collect the stored vector from each member.
2844     SmallVector<Value *, 4> StoredVecs;
2845     for (unsigned i = 0; i < InterleaveFactor; i++) {
2846       assert((Group->getMember(i) || MaskForGaps) &&
2847              "Fail to get a member from an interleaved store group");
2848       Instruction *Member = Group->getMember(i);
2849 
2850       // Skip the gaps in the group.
2851       if (!Member) {
2852         Value *Undef = PoisonValue::get(SubVT);
2853         StoredVecs.push_back(Undef);
2854         continue;
2855       }
2856 
2857       Value *StoredVec = State.get(StoredValues[i], Part);
2858 
2859       if (Group->isReverse())
2860         StoredVec = reverseVector(StoredVec);
2861 
2862       // If this member has different type, cast it to a unified type.
2863 
2864       if (StoredVec->getType() != SubVT)
2865         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2866 
2867       StoredVecs.push_back(StoredVec);
2868     }
2869 
2870     // Concatenate all vectors into a wide vector.
2871     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2872 
2873     // Interleave the elements in the wide vector.
2874     Value *IVec = Builder.CreateShuffleVector(
2875         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2876         "interleaved.vec");
2877 
2878     Instruction *NewStoreInstr;
2879     if (BlockInMask || MaskForGaps) {
2880       Value *GroupMask = MaskForGaps;
2881       if (BlockInMask) {
2882         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2883         Value *ShuffledMask = Builder.CreateShuffleVector(
2884             BlockInMaskPart,
2885             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2886             "interleaved.mask");
2887         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2888                                                       ShuffledMask, MaskForGaps)
2889                                 : ShuffledMask;
2890       }
2891       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2892                                                 Group->getAlign(), GroupMask);
2893     } else
2894       NewStoreInstr =
2895           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2896 
2897     Group->addMetadata(NewStoreInstr);
2898   }
2899 }
2900 
2901 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2902     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2903     VPValue *StoredValue, VPValue *BlockInMask) {
2904   // Attempt to issue a wide load.
2905   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2906   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2907 
2908   assert((LI || SI) && "Invalid Load/Store instruction");
2909   assert((!SI || StoredValue) && "No stored value provided for widened store");
2910   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2911 
2912   LoopVectorizationCostModel::InstWidening Decision =
2913       Cost->getWideningDecision(Instr, VF);
2914   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2915           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2916           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2917          "CM decision is not to widen the memory instruction");
2918 
2919   Type *ScalarDataTy = getLoadStoreType(Instr);
2920 
2921   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2922   const Align Alignment = getLoadStoreAlignment(Instr);
2923 
2924   // Determine if the pointer operand of the access is either consecutive or
2925   // reverse consecutive.
2926   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2927   bool ConsecutiveStride =
2928       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2929   bool CreateGatherScatter =
2930       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2931 
2932   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2933   // gather/scatter. Otherwise Decision should have been to Scalarize.
2934   assert((ConsecutiveStride || CreateGatherScatter) &&
2935          "The instruction should be scalarized");
2936   (void)ConsecutiveStride;
2937 
2938   VectorParts BlockInMaskParts(UF);
2939   bool isMaskRequired = BlockInMask;
2940   if (isMaskRequired)
2941     for (unsigned Part = 0; Part < UF; ++Part)
2942       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2943 
2944   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2945     // Calculate the pointer for the specific unroll-part.
2946     GetElementPtrInst *PartPtr = nullptr;
2947 
2948     bool InBounds = false;
2949     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2950       InBounds = gep->isInBounds();
2951     if (Reverse) {
2952       // If the address is consecutive but reversed, then the
2953       // wide store needs to start at the last vector element.
2954       // RunTimeVF =  VScale * VF.getKnownMinValue()
2955       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2956       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2957       // NumElt = -Part * RunTimeVF
2958       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2959       // LastLane = 1 - RunTimeVF
2960       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2961       PartPtr =
2962           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2963       PartPtr->setIsInBounds(InBounds);
2964       PartPtr = cast<GetElementPtrInst>(
2965           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2966       PartPtr->setIsInBounds(InBounds);
2967       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2968         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2969     } else {
2970       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2971       PartPtr = cast<GetElementPtrInst>(
2972           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2973       PartPtr->setIsInBounds(InBounds);
2974     }
2975 
2976     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2977     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2978   };
2979 
2980   // Handle Stores:
2981   if (SI) {
2982     setDebugLocFromInst(SI);
2983 
2984     for (unsigned Part = 0; Part < UF; ++Part) {
2985       Instruction *NewSI = nullptr;
2986       Value *StoredVal = State.get(StoredValue, Part);
2987       if (CreateGatherScatter) {
2988         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2989         Value *VectorGep = State.get(Addr, Part);
2990         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2991                                             MaskPart);
2992       } else {
2993         if (Reverse) {
2994           // If we store to reverse consecutive memory locations, then we need
2995           // to reverse the order of elements in the stored value.
2996           StoredVal = reverseVector(StoredVal);
2997           // We don't want to update the value in the map as it might be used in
2998           // another expression. So don't call resetVectorValue(StoredVal).
2999         }
3000         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3001         if (isMaskRequired)
3002           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3003                                             BlockInMaskParts[Part]);
3004         else
3005           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3006       }
3007       addMetadata(NewSI, SI);
3008     }
3009     return;
3010   }
3011 
3012   // Handle loads.
3013   assert(LI && "Must have a load instruction");
3014   setDebugLocFromInst(LI);
3015   for (unsigned Part = 0; Part < UF; ++Part) {
3016     Value *NewLI;
3017     if (CreateGatherScatter) {
3018       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
3019       Value *VectorGep = State.get(Addr, Part);
3020       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
3021                                          nullptr, "wide.masked.gather");
3022       addMetadata(NewLI, LI);
3023     } else {
3024       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3025       if (isMaskRequired)
3026         NewLI = Builder.CreateMaskedLoad(
3027             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
3028             PoisonValue::get(DataTy), "wide.masked.load");
3029       else
3030         NewLI =
3031             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
3032 
3033       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3034       addMetadata(NewLI, LI);
3035       if (Reverse)
3036         NewLI = reverseVector(NewLI);
3037     }
3038 
3039     State.set(Def, NewLI, Part);
3040   }
3041 }
3042 
3043 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
3044                                                VPUser &User,
3045                                                const VPIteration &Instance,
3046                                                bool IfPredicateInstr,
3047                                                VPTransformState &State) {
3048   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3049 
3050   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3051   // the first lane and part.
3052   if (isa<NoAliasScopeDeclInst>(Instr))
3053     if (!Instance.isFirstIteration())
3054       return;
3055 
3056   setDebugLocFromInst(Instr);
3057 
3058   // Does this instruction return a value ?
3059   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3060 
3061   Instruction *Cloned = Instr->clone();
3062   if (!IsVoidRetTy)
3063     Cloned->setName(Instr->getName() + ".cloned");
3064 
3065   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3066                                Builder.GetInsertPoint());
3067   // Replace the operands of the cloned instructions with their scalar
3068   // equivalents in the new loop.
3069   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3070     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3071     auto InputInstance = Instance;
3072     if (!Operand || !OrigLoop->contains(Operand) ||
3073         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3074       InputInstance.Lane = VPLane::getFirstLane();
3075     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3076     Cloned->setOperand(op, NewOp);
3077   }
3078   addNewMetadata(Cloned, Instr);
3079 
3080   // Place the cloned scalar in the new loop.
3081   Builder.Insert(Cloned);
3082 
3083   State.set(Def, Cloned, Instance);
3084 
3085   // If we just cloned a new assumption, add it the assumption cache.
3086   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3087     AC->registerAssumption(II);
3088 
3089   // End if-block.
3090   if (IfPredicateInstr)
3091     PredicatedInstructions.push_back(Cloned);
3092 }
3093 
3094 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3095                                                       Value *End, Value *Step,
3096                                                       Instruction *DL) {
3097   BasicBlock *Header = L->getHeader();
3098   BasicBlock *Latch = L->getLoopLatch();
3099   // As we're just creating this loop, it's possible no latch exists
3100   // yet. If so, use the header as this will be a single block loop.
3101   if (!Latch)
3102     Latch = Header;
3103 
3104   IRBuilder<> B(&*Header->getFirstInsertionPt());
3105   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3106   setDebugLocFromInst(OldInst, &B);
3107   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3108 
3109   B.SetInsertPoint(Latch->getTerminator());
3110   setDebugLocFromInst(OldInst, &B);
3111 
3112   // Create i+1 and fill the PHINode.
3113   //
3114   // If the tail is not folded, we know that End - Start >= Step (either
3115   // statically or through the minimum iteration checks). We also know that both
3116   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3117   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3118   // overflows and we can mark the induction increment as NUW.
3119   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3120                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3121   Induction->addIncoming(Start, L->getLoopPreheader());
3122   Induction->addIncoming(Next, Latch);
3123   // Create the compare.
3124   Value *ICmp = B.CreateICmpEQ(Next, End);
3125   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3126 
3127   // Now we have two terminators. Remove the old one from the block.
3128   Latch->getTerminator()->eraseFromParent();
3129 
3130   return Induction;
3131 }
3132 
3133 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3134   if (TripCount)
3135     return TripCount;
3136 
3137   assert(L && "Create Trip Count for null loop.");
3138   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3139   // Find the loop boundaries.
3140   ScalarEvolution *SE = PSE.getSE();
3141   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3142   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3143          "Invalid loop count");
3144 
3145   Type *IdxTy = Legal->getWidestInductionType();
3146   assert(IdxTy && "No type for induction");
3147 
3148   // The exit count might have the type of i64 while the phi is i32. This can
3149   // happen if we have an induction variable that is sign extended before the
3150   // compare. The only way that we get a backedge taken count is that the
3151   // induction variable was signed and as such will not overflow. In such a case
3152   // truncation is legal.
3153   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3154       IdxTy->getPrimitiveSizeInBits())
3155     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3156   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3157 
3158   // Get the total trip count from the count by adding 1.
3159   const SCEV *ExitCount = SE->getAddExpr(
3160       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3161 
3162   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3163 
3164   // Expand the trip count and place the new instructions in the preheader.
3165   // Notice that the pre-header does not change, only the loop body.
3166   SCEVExpander Exp(*SE, DL, "induction");
3167 
3168   // Count holds the overall loop count (N).
3169   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3170                                 L->getLoopPreheader()->getTerminator());
3171 
3172   if (TripCount->getType()->isPointerTy())
3173     TripCount =
3174         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3175                                     L->getLoopPreheader()->getTerminator());
3176 
3177   return TripCount;
3178 }
3179 
3180 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3181   if (VectorTripCount)
3182     return VectorTripCount;
3183 
3184   Value *TC = getOrCreateTripCount(L);
3185   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3186 
3187   Type *Ty = TC->getType();
3188   // This is where we can make the step a runtime constant.
3189   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3190 
3191   // If the tail is to be folded by masking, round the number of iterations N
3192   // up to a multiple of Step instead of rounding down. This is done by first
3193   // adding Step-1 and then rounding down. Note that it's ok if this addition
3194   // overflows: the vector induction variable will eventually wrap to zero given
3195   // that it starts at zero and its Step is a power of two; the loop will then
3196   // exit, with the last early-exit vector comparison also producing all-true.
3197   if (Cost->foldTailByMasking()) {
3198     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3199            "VF*UF must be a power of 2 when folding tail by masking");
3200     assert(!VF.isScalable() &&
3201            "Tail folding not yet supported for scalable vectors");
3202     TC = Builder.CreateAdd(
3203         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3204   }
3205 
3206   // Now we need to generate the expression for the part of the loop that the
3207   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3208   // iterations are not required for correctness, or N - Step, otherwise. Step
3209   // is equal to the vectorization factor (number of SIMD elements) times the
3210   // unroll factor (number of SIMD instructions).
3211   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3212 
3213   // There are cases where we *must* run at least one iteration in the remainder
3214   // loop.  See the cost model for when this can happen.  If the step evenly
3215   // divides the trip count, we set the remainder to be equal to the step. If
3216   // the step does not evenly divide the trip count, no adjustment is necessary
3217   // since there will already be scalar iterations. Note that the minimum
3218   // iterations check ensures that N >= Step.
3219   if (Cost->requiresScalarEpilogue(VF)) {
3220     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3221     R = Builder.CreateSelect(IsZero, Step, R);
3222   }
3223 
3224   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3225 
3226   return VectorTripCount;
3227 }
3228 
3229 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3230                                                    const DataLayout &DL) {
3231   // Verify that V is a vector type with same number of elements as DstVTy.
3232   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3233   unsigned VF = DstFVTy->getNumElements();
3234   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3235   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3236   Type *SrcElemTy = SrcVecTy->getElementType();
3237   Type *DstElemTy = DstFVTy->getElementType();
3238   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3239          "Vector elements must have same size");
3240 
3241   // Do a direct cast if element types are castable.
3242   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3243     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3244   }
3245   // V cannot be directly casted to desired vector type.
3246   // May happen when V is a floating point vector but DstVTy is a vector of
3247   // pointers or vice-versa. Handle this using a two-step bitcast using an
3248   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3249   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3250          "Only one type should be a pointer type");
3251   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3252          "Only one type should be a floating point type");
3253   Type *IntTy =
3254       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3255   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3256   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3257   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3258 }
3259 
3260 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3261                                                          BasicBlock *Bypass) {
3262   Value *Count = getOrCreateTripCount(L);
3263   // Reuse existing vector loop preheader for TC checks.
3264   // Note that new preheader block is generated for vector loop.
3265   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3266   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3267 
3268   // Generate code to check if the loop's trip count is less than VF * UF, or
3269   // equal to it in case a scalar epilogue is required; this implies that the
3270   // vector trip count is zero. This check also covers the case where adding one
3271   // to the backedge-taken count overflowed leading to an incorrect trip count
3272   // of zero. In this case we will also jump to the scalar loop.
3273   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3274                                             : ICmpInst::ICMP_ULT;
3275 
3276   // If tail is to be folded, vector loop takes care of all iterations.
3277   Value *CheckMinIters = Builder.getFalse();
3278   if (!Cost->foldTailByMasking()) {
3279     Value *Step =
3280         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3281     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3282   }
3283   // Create new preheader for vector loop.
3284   LoopVectorPreHeader =
3285       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3286                  "vector.ph");
3287 
3288   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3289                                DT->getNode(Bypass)->getIDom()) &&
3290          "TC check is expected to dominate Bypass");
3291 
3292   // Update dominator for Bypass & LoopExit (if needed).
3293   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3294   if (!Cost->requiresScalarEpilogue(VF))
3295     // If there is an epilogue which must run, there's no edge from the
3296     // middle block to exit blocks  and thus no need to update the immediate
3297     // dominator of the exit blocks.
3298     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3299 
3300   ReplaceInstWithInst(
3301       TCCheckBlock->getTerminator(),
3302       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3303   LoopBypassBlocks.push_back(TCCheckBlock);
3304 }
3305 
3306 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3307 
3308   BasicBlock *const SCEVCheckBlock =
3309       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3310   if (!SCEVCheckBlock)
3311     return nullptr;
3312 
3313   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3314            (OptForSizeBasedOnProfile &&
3315             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3316          "Cannot SCEV check stride or overflow when optimizing for size");
3317 
3318 
3319   // Update dominator only if this is first RT check.
3320   if (LoopBypassBlocks.empty()) {
3321     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3322     if (!Cost->requiresScalarEpilogue(VF))
3323       // If there is an epilogue which must run, there's no edge from the
3324       // middle block to exit blocks  and thus no need to update the immediate
3325       // dominator of the exit blocks.
3326       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3327   }
3328 
3329   LoopBypassBlocks.push_back(SCEVCheckBlock);
3330   AddedSafetyChecks = true;
3331   return SCEVCheckBlock;
3332 }
3333 
3334 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3335                                                       BasicBlock *Bypass) {
3336   // VPlan-native path does not do any analysis for runtime checks currently.
3337   if (EnableVPlanNativePath)
3338     return nullptr;
3339 
3340   BasicBlock *const MemCheckBlock =
3341       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3342 
3343   // Check if we generated code that checks in runtime if arrays overlap. We put
3344   // the checks into a separate block to make the more common case of few
3345   // elements faster.
3346   if (!MemCheckBlock)
3347     return nullptr;
3348 
3349   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3350     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3351            "Cannot emit memory checks when optimizing for size, unless forced "
3352            "to vectorize.");
3353     ORE->emit([&]() {
3354       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3355                                         L->getStartLoc(), L->getHeader())
3356              << "Code-size may be reduced by not forcing "
3357                 "vectorization, or by source-code modifications "
3358                 "eliminating the need for runtime checks "
3359                 "(e.g., adding 'restrict').";
3360     });
3361   }
3362 
3363   LoopBypassBlocks.push_back(MemCheckBlock);
3364 
3365   AddedSafetyChecks = true;
3366 
3367   // We currently don't use LoopVersioning for the actual loop cloning but we
3368   // still use it to add the noalias metadata.
3369   LVer = std::make_unique<LoopVersioning>(
3370       *Legal->getLAI(),
3371       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3372       DT, PSE.getSE());
3373   LVer->prepareNoAliasMetadata();
3374   return MemCheckBlock;
3375 }
3376 
3377 Value *InnerLoopVectorizer::emitTransformedIndex(
3378     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3379     const InductionDescriptor &ID) const {
3380 
3381   SCEVExpander Exp(*SE, DL, "induction");
3382   auto Step = ID.getStep();
3383   auto StartValue = ID.getStartValue();
3384   assert(Index->getType()->getScalarType() == Step->getType() &&
3385          "Index scalar type does not match StepValue type");
3386 
3387   // Note: the IR at this point is broken. We cannot use SE to create any new
3388   // SCEV and then expand it, hoping that SCEV's simplification will give us
3389   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3390   // lead to various SCEV crashes. So all we can do is to use builder and rely
3391   // on InstCombine for future simplifications. Here we handle some trivial
3392   // cases only.
3393   auto CreateAdd = [&B](Value *X, Value *Y) {
3394     assert(X->getType() == Y->getType() && "Types don't match!");
3395     if (auto *CX = dyn_cast<ConstantInt>(X))
3396       if (CX->isZero())
3397         return Y;
3398     if (auto *CY = dyn_cast<ConstantInt>(Y))
3399       if (CY->isZero())
3400         return X;
3401     return B.CreateAdd(X, Y);
3402   };
3403 
3404   // We allow X to be a vector type, in which case Y will potentially be
3405   // splatted into a vector with the same element count.
3406   auto CreateMul = [&B](Value *X, Value *Y) {
3407     assert(X->getType()->getScalarType() == Y->getType() &&
3408            "Types don't match!");
3409     if (auto *CX = dyn_cast<ConstantInt>(X))
3410       if (CX->isOne())
3411         return Y;
3412     if (auto *CY = dyn_cast<ConstantInt>(Y))
3413       if (CY->isOne())
3414         return X;
3415     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3416     if (XVTy && !isa<VectorType>(Y->getType()))
3417       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3418     return B.CreateMul(X, Y);
3419   };
3420 
3421   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3422   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3423   // the DomTree is not kept up-to-date for additional blocks generated in the
3424   // vector loop. By using the header as insertion point, we guarantee that the
3425   // expanded instructions dominate all their uses.
3426   auto GetInsertPoint = [this, &B]() {
3427     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3428     if (InsertBB != LoopVectorBody &&
3429         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3430       return LoopVectorBody->getTerminator();
3431     return &*B.GetInsertPoint();
3432   };
3433 
3434   switch (ID.getKind()) {
3435   case InductionDescriptor::IK_IntInduction: {
3436     assert(!isa<VectorType>(Index->getType()) &&
3437            "Vector indices not supported for integer inductions yet");
3438     assert(Index->getType() == StartValue->getType() &&
3439            "Index type does not match StartValue type");
3440     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3441       return B.CreateSub(StartValue, Index);
3442     auto *Offset = CreateMul(
3443         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3444     return CreateAdd(StartValue, Offset);
3445   }
3446   case InductionDescriptor::IK_PtrInduction: {
3447     assert(isa<SCEVConstant>(Step) &&
3448            "Expected constant step for pointer induction");
3449     return B.CreateGEP(
3450         ID.getElementType(), StartValue,
3451         CreateMul(Index,
3452                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3453                                     GetInsertPoint())));
3454   }
3455   case InductionDescriptor::IK_FpInduction: {
3456     assert(!isa<VectorType>(Index->getType()) &&
3457            "Vector indices not supported for FP inductions yet");
3458     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3459     auto InductionBinOp = ID.getInductionBinOp();
3460     assert(InductionBinOp &&
3461            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3462             InductionBinOp->getOpcode() == Instruction::FSub) &&
3463            "Original bin op should be defined for FP induction");
3464 
3465     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3466     Value *MulExp = B.CreateFMul(StepValue, Index);
3467     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3468                          "induction");
3469   }
3470   case InductionDescriptor::IK_NoInduction:
3471     return nullptr;
3472   }
3473   llvm_unreachable("invalid enum");
3474 }
3475 
3476 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3477   LoopScalarBody = OrigLoop->getHeader();
3478   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3479   assert(LoopVectorPreHeader && "Invalid loop structure");
3480   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3481   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3482          "multiple exit loop without required epilogue?");
3483 
3484   LoopMiddleBlock =
3485       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3486                  LI, nullptr, Twine(Prefix) + "middle.block");
3487   LoopScalarPreHeader =
3488       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3489                  nullptr, Twine(Prefix) + "scalar.ph");
3490 
3491   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3492 
3493   // Set up the middle block terminator.  Two cases:
3494   // 1) If we know that we must execute the scalar epilogue, emit an
3495   //    unconditional branch.
3496   // 2) Otherwise, we must have a single unique exit block (due to how we
3497   //    implement the multiple exit case).  In this case, set up a conditonal
3498   //    branch from the middle block to the loop scalar preheader, and the
3499   //    exit block.  completeLoopSkeleton will update the condition to use an
3500   //    iteration check, if required to decide whether to execute the remainder.
3501   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3502     BranchInst::Create(LoopScalarPreHeader) :
3503     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3504                        Builder.getTrue());
3505   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3506   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3507 
3508   // We intentionally don't let SplitBlock to update LoopInfo since
3509   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3510   // LoopVectorBody is explicitly added to the correct place few lines later.
3511   LoopVectorBody =
3512       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3513                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3514 
3515   // Update dominator for loop exit.
3516   if (!Cost->requiresScalarEpilogue(VF))
3517     // If there is an epilogue which must run, there's no edge from the
3518     // middle block to exit blocks  and thus no need to update the immediate
3519     // dominator of the exit blocks.
3520     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3521 
3522   // Create and register the new vector loop.
3523   Loop *Lp = LI->AllocateLoop();
3524   Loop *ParentLoop = OrigLoop->getParentLoop();
3525 
3526   // Insert the new loop into the loop nest and register the new basic blocks
3527   // before calling any utilities such as SCEV that require valid LoopInfo.
3528   if (ParentLoop) {
3529     ParentLoop->addChildLoop(Lp);
3530   } else {
3531     LI->addTopLevelLoop(Lp);
3532   }
3533   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3534   return Lp;
3535 }
3536 
3537 void InnerLoopVectorizer::createInductionResumeValues(
3538     Loop *L, Value *VectorTripCount,
3539     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3540   assert(VectorTripCount && L && "Expected valid arguments");
3541   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3542           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3543          "Inconsistent information about additional bypass.");
3544   // We are going to resume the execution of the scalar loop.
3545   // Go over all of the induction variables that we found and fix the
3546   // PHIs that are left in the scalar version of the loop.
3547   // The starting values of PHI nodes depend on the counter of the last
3548   // iteration in the vectorized loop.
3549   // If we come from a bypass edge then we need to start from the original
3550   // start value.
3551   for (auto &InductionEntry : Legal->getInductionVars()) {
3552     PHINode *OrigPhi = InductionEntry.first;
3553     InductionDescriptor II = InductionEntry.second;
3554 
3555     // Create phi nodes to merge from the  backedge-taken check block.
3556     PHINode *BCResumeVal =
3557         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3558                         LoopScalarPreHeader->getTerminator());
3559     // Copy original phi DL over to the new one.
3560     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3561     Value *&EndValue = IVEndValues[OrigPhi];
3562     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3563     if (OrigPhi == OldInduction) {
3564       // We know what the end value is.
3565       EndValue = VectorTripCount;
3566     } else {
3567       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3568 
3569       // Fast-math-flags propagate from the original induction instruction.
3570       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3571         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3572 
3573       Type *StepType = II.getStep()->getType();
3574       Instruction::CastOps CastOp =
3575           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3576       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3577       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3578       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3579       EndValue->setName("ind.end");
3580 
3581       // Compute the end value for the additional bypass (if applicable).
3582       if (AdditionalBypass.first) {
3583         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3584         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3585                                          StepType, true);
3586         CRD =
3587             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3588         EndValueFromAdditionalBypass =
3589             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3590         EndValueFromAdditionalBypass->setName("ind.end");
3591       }
3592     }
3593     // The new PHI merges the original incoming value, in case of a bypass,
3594     // or the value at the end of the vectorized loop.
3595     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3596 
3597     // Fix the scalar body counter (PHI node).
3598     // The old induction's phi node in the scalar body needs the truncated
3599     // value.
3600     for (BasicBlock *BB : LoopBypassBlocks)
3601       BCResumeVal->addIncoming(II.getStartValue(), BB);
3602 
3603     if (AdditionalBypass.first)
3604       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3605                                             EndValueFromAdditionalBypass);
3606 
3607     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3608   }
3609 }
3610 
3611 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3612                                                       MDNode *OrigLoopID) {
3613   assert(L && "Expected valid loop.");
3614 
3615   // The trip counts should be cached by now.
3616   Value *Count = getOrCreateTripCount(L);
3617   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3618 
3619   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3620 
3621   // Add a check in the middle block to see if we have completed
3622   // all of the iterations in the first vector loop.  Three cases:
3623   // 1) If we require a scalar epilogue, there is no conditional branch as
3624   //    we unconditionally branch to the scalar preheader.  Do nothing.
3625   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3626   //    Thus if tail is to be folded, we know we don't need to run the
3627   //    remainder and we can use the previous value for the condition (true).
3628   // 3) Otherwise, construct a runtime check.
3629   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3630     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3631                                         Count, VectorTripCount, "cmp.n",
3632                                         LoopMiddleBlock->getTerminator());
3633 
3634     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3635     // of the corresponding compare because they may have ended up with
3636     // different line numbers and we want to avoid awkward line stepping while
3637     // debugging. Eg. if the compare has got a line number inside the loop.
3638     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3639     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3640   }
3641 
3642   // Get ready to start creating new instructions into the vectorized body.
3643   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3644          "Inconsistent vector loop preheader");
3645   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3646 
3647   Optional<MDNode *> VectorizedLoopID =
3648       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3649                                       LLVMLoopVectorizeFollowupVectorized});
3650   if (VectorizedLoopID.hasValue()) {
3651     L->setLoopID(VectorizedLoopID.getValue());
3652 
3653     // Do not setAlreadyVectorized if loop attributes have been defined
3654     // explicitly.
3655     return LoopVectorPreHeader;
3656   }
3657 
3658   // Keep all loop hints from the original loop on the vector loop (we'll
3659   // replace the vectorizer-specific hints below).
3660   if (MDNode *LID = OrigLoop->getLoopID())
3661     L->setLoopID(LID);
3662 
3663   LoopVectorizeHints Hints(L, true, *ORE);
3664   Hints.setAlreadyVectorized();
3665 
3666 #ifdef EXPENSIVE_CHECKS
3667   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3668   LI->verify(*DT);
3669 #endif
3670 
3671   return LoopVectorPreHeader;
3672 }
3673 
3674 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3675   /*
3676    In this function we generate a new loop. The new loop will contain
3677    the vectorized instructions while the old loop will continue to run the
3678    scalar remainder.
3679 
3680        [ ] <-- loop iteration number check.
3681     /   |
3682    /    v
3683   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3684   |  /  |
3685   | /   v
3686   ||   [ ]     <-- vector pre header.
3687   |/    |
3688   |     v
3689   |    [  ] \
3690   |    [  ]_|   <-- vector loop.
3691   |     |
3692   |     v
3693   \   -[ ]   <--- middle-block.
3694    \/   |
3695    /\   v
3696    | ->[ ]     <--- new preheader.
3697    |    |
3698  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3699    |   [ ] \
3700    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3701     \   |
3702      \  v
3703       >[ ]     <-- exit block(s).
3704    ...
3705    */
3706 
3707   // Get the metadata of the original loop before it gets modified.
3708   MDNode *OrigLoopID = OrigLoop->getLoopID();
3709 
3710   // Workaround!  Compute the trip count of the original loop and cache it
3711   // before we start modifying the CFG.  This code has a systemic problem
3712   // wherein it tries to run analysis over partially constructed IR; this is
3713   // wrong, and not simply for SCEV.  The trip count of the original loop
3714   // simply happens to be prone to hitting this in practice.  In theory, we
3715   // can hit the same issue for any SCEV, or ValueTracking query done during
3716   // mutation.  See PR49900.
3717   getOrCreateTripCount(OrigLoop);
3718 
3719   // Create an empty vector loop, and prepare basic blocks for the runtime
3720   // checks.
3721   Loop *Lp = createVectorLoopSkeleton("");
3722 
3723   // Now, compare the new count to zero. If it is zero skip the vector loop and
3724   // jump to the scalar loop. This check also covers the case where the
3725   // backedge-taken count is uint##_max: adding one to it will overflow leading
3726   // to an incorrect trip count of zero. In this (rare) case we will also jump
3727   // to the scalar loop.
3728   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3729 
3730   // Generate the code to check any assumptions that we've made for SCEV
3731   // expressions.
3732   emitSCEVChecks(Lp, LoopScalarPreHeader);
3733 
3734   // Generate the code that checks in runtime if arrays overlap. We put the
3735   // checks into a separate block to make the more common case of few elements
3736   // faster.
3737   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3738 
3739   // Some loops have a single integer induction variable, while other loops
3740   // don't. One example is c++ iterators that often have multiple pointer
3741   // induction variables. In the code below we also support a case where we
3742   // don't have a single induction variable.
3743   //
3744   // We try to obtain an induction variable from the original loop as hard
3745   // as possible. However if we don't find one that:
3746   //   - is an integer
3747   //   - counts from zero, stepping by one
3748   //   - is the size of the widest induction variable type
3749   // then we create a new one.
3750   OldInduction = Legal->getPrimaryInduction();
3751   Type *IdxTy = Legal->getWidestInductionType();
3752   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3753   // The loop step is equal to the vectorization factor (num of SIMD elements)
3754   // times the unroll factor (num of SIMD instructions).
3755   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3756   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3757   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3758   Induction =
3759       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3760                               getDebugLocFromInstOrOperands(OldInduction));
3761 
3762   // Emit phis for the new starting index of the scalar loop.
3763   createInductionResumeValues(Lp, CountRoundDown);
3764 
3765   return completeLoopSkeleton(Lp, OrigLoopID);
3766 }
3767 
3768 // Fix up external users of the induction variable. At this point, we are
3769 // in LCSSA form, with all external PHIs that use the IV having one input value,
3770 // coming from the remainder loop. We need those PHIs to also have a correct
3771 // value for the IV when arriving directly from the middle block.
3772 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3773                                        const InductionDescriptor &II,
3774                                        Value *CountRoundDown, Value *EndValue,
3775                                        BasicBlock *MiddleBlock) {
3776   // There are two kinds of external IV usages - those that use the value
3777   // computed in the last iteration (the PHI) and those that use the penultimate
3778   // value (the value that feeds into the phi from the loop latch).
3779   // We allow both, but they, obviously, have different values.
3780 
3781   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3782 
3783   DenseMap<Value *, Value *> MissingVals;
3784 
3785   // An external user of the last iteration's value should see the value that
3786   // the remainder loop uses to initialize its own IV.
3787   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3788   for (User *U : PostInc->users()) {
3789     Instruction *UI = cast<Instruction>(U);
3790     if (!OrigLoop->contains(UI)) {
3791       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3792       MissingVals[UI] = EndValue;
3793     }
3794   }
3795 
3796   // An external user of the penultimate value need to see EndValue - Step.
3797   // The simplest way to get this is to recompute it from the constituent SCEVs,
3798   // that is Start + (Step * (CRD - 1)).
3799   for (User *U : OrigPhi->users()) {
3800     auto *UI = cast<Instruction>(U);
3801     if (!OrigLoop->contains(UI)) {
3802       const DataLayout &DL =
3803           OrigLoop->getHeader()->getModule()->getDataLayout();
3804       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3805 
3806       IRBuilder<> B(MiddleBlock->getTerminator());
3807 
3808       // Fast-math-flags propagate from the original induction instruction.
3809       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3810         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3811 
3812       Value *CountMinusOne = B.CreateSub(
3813           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3814       Value *CMO =
3815           !II.getStep()->getType()->isIntegerTy()
3816               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3817                              II.getStep()->getType())
3818               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3819       CMO->setName("cast.cmo");
3820       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3821       Escape->setName("ind.escape");
3822       MissingVals[UI] = Escape;
3823     }
3824   }
3825 
3826   for (auto &I : MissingVals) {
3827     PHINode *PHI = cast<PHINode>(I.first);
3828     // One corner case we have to handle is two IVs "chasing" each-other,
3829     // that is %IV2 = phi [...], [ %IV1, %latch ]
3830     // In this case, if IV1 has an external use, we need to avoid adding both
3831     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3832     // don't already have an incoming value for the middle block.
3833     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3834       PHI->addIncoming(I.second, MiddleBlock);
3835   }
3836 }
3837 
3838 namespace {
3839 
3840 struct CSEDenseMapInfo {
3841   static bool canHandle(const Instruction *I) {
3842     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3843            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3844   }
3845 
3846   static inline Instruction *getEmptyKey() {
3847     return DenseMapInfo<Instruction *>::getEmptyKey();
3848   }
3849 
3850   static inline Instruction *getTombstoneKey() {
3851     return DenseMapInfo<Instruction *>::getTombstoneKey();
3852   }
3853 
3854   static unsigned getHashValue(const Instruction *I) {
3855     assert(canHandle(I) && "Unknown instruction!");
3856     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3857                                                            I->value_op_end()));
3858   }
3859 
3860   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3861     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3862         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3863       return LHS == RHS;
3864     return LHS->isIdenticalTo(RHS);
3865   }
3866 };
3867 
3868 } // end anonymous namespace
3869 
3870 ///Perform cse of induction variable instructions.
3871 static void cse(BasicBlock *BB) {
3872   // Perform simple cse.
3873   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3874   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3875     if (!CSEDenseMapInfo::canHandle(&In))
3876       continue;
3877 
3878     // Check if we can replace this instruction with any of the
3879     // visited instructions.
3880     if (Instruction *V = CSEMap.lookup(&In)) {
3881       In.replaceAllUsesWith(V);
3882       In.eraseFromParent();
3883       continue;
3884     }
3885 
3886     CSEMap[&In] = &In;
3887   }
3888 }
3889 
3890 InstructionCost
3891 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3892                                               bool &NeedToScalarize) const {
3893   Function *F = CI->getCalledFunction();
3894   Type *ScalarRetTy = CI->getType();
3895   SmallVector<Type *, 4> Tys, ScalarTys;
3896   for (auto &ArgOp : CI->args())
3897     ScalarTys.push_back(ArgOp->getType());
3898 
3899   // Estimate cost of scalarized vector call. The source operands are assumed
3900   // to be vectors, so we need to extract individual elements from there,
3901   // execute VF scalar calls, and then gather the result into the vector return
3902   // value.
3903   InstructionCost ScalarCallCost =
3904       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3905   if (VF.isScalar())
3906     return ScalarCallCost;
3907 
3908   // Compute corresponding vector type for return value and arguments.
3909   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3910   for (Type *ScalarTy : ScalarTys)
3911     Tys.push_back(ToVectorTy(ScalarTy, VF));
3912 
3913   // Compute costs of unpacking argument values for the scalar calls and
3914   // packing the return values to a vector.
3915   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3916 
3917   InstructionCost Cost =
3918       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3919 
3920   // If we can't emit a vector call for this function, then the currently found
3921   // cost is the cost we need to return.
3922   NeedToScalarize = true;
3923   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3924   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3925 
3926   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3927     return Cost;
3928 
3929   // If the corresponding vector cost is cheaper, return its cost.
3930   InstructionCost VectorCallCost =
3931       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3932   if (VectorCallCost < Cost) {
3933     NeedToScalarize = false;
3934     Cost = VectorCallCost;
3935   }
3936   return Cost;
3937 }
3938 
3939 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3940   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3941     return Elt;
3942   return VectorType::get(Elt, VF);
3943 }
3944 
3945 InstructionCost
3946 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3947                                                    ElementCount VF) const {
3948   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3949   assert(ID && "Expected intrinsic call!");
3950   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3951   FastMathFlags FMF;
3952   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3953     FMF = FPMO->getFastMathFlags();
3954 
3955   SmallVector<const Value *> Arguments(CI->args());
3956   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3957   SmallVector<Type *> ParamTys;
3958   std::transform(FTy->param_begin(), FTy->param_end(),
3959                  std::back_inserter(ParamTys),
3960                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3961 
3962   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3963                                     dyn_cast<IntrinsicInst>(CI));
3964   return TTI.getIntrinsicInstrCost(CostAttrs,
3965                                    TargetTransformInfo::TCK_RecipThroughput);
3966 }
3967 
3968 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3969   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3970   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3971   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3972 }
3973 
3974 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3975   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3976   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3977   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3978 }
3979 
3980 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3981   // For every instruction `I` in MinBWs, truncate the operands, create a
3982   // truncated version of `I` and reextend its result. InstCombine runs
3983   // later and will remove any ext/trunc pairs.
3984   SmallPtrSet<Value *, 4> Erased;
3985   for (const auto &KV : Cost->getMinimalBitwidths()) {
3986     // If the value wasn't vectorized, we must maintain the original scalar
3987     // type. The absence of the value from State indicates that it
3988     // wasn't vectorized.
3989     // FIXME: Should not rely on getVPValue at this point.
3990     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3991     if (!State.hasAnyVectorValue(Def))
3992       continue;
3993     for (unsigned Part = 0; Part < UF; ++Part) {
3994       Value *I = State.get(Def, Part);
3995       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3996         continue;
3997       Type *OriginalTy = I->getType();
3998       Type *ScalarTruncatedTy =
3999           IntegerType::get(OriginalTy->getContext(), KV.second);
4000       auto *TruncatedTy = VectorType::get(
4001           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
4002       if (TruncatedTy == OriginalTy)
4003         continue;
4004 
4005       IRBuilder<> B(cast<Instruction>(I));
4006       auto ShrinkOperand = [&](Value *V) -> Value * {
4007         if (auto *ZI = dyn_cast<ZExtInst>(V))
4008           if (ZI->getSrcTy() == TruncatedTy)
4009             return ZI->getOperand(0);
4010         return B.CreateZExtOrTrunc(V, TruncatedTy);
4011       };
4012 
4013       // The actual instruction modification depends on the instruction type,
4014       // unfortunately.
4015       Value *NewI = nullptr;
4016       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4017         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
4018                              ShrinkOperand(BO->getOperand(1)));
4019 
4020         // Any wrapping introduced by shrinking this operation shouldn't be
4021         // considered undefined behavior. So, we can't unconditionally copy
4022         // arithmetic wrapping flags to NewI.
4023         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
4024       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
4025         NewI =
4026             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
4027                          ShrinkOperand(CI->getOperand(1)));
4028       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
4029         NewI = B.CreateSelect(SI->getCondition(),
4030                               ShrinkOperand(SI->getTrueValue()),
4031                               ShrinkOperand(SI->getFalseValue()));
4032       } else if (auto *CI = dyn_cast<CastInst>(I)) {
4033         switch (CI->getOpcode()) {
4034         default:
4035           llvm_unreachable("Unhandled cast!");
4036         case Instruction::Trunc:
4037           NewI = ShrinkOperand(CI->getOperand(0));
4038           break;
4039         case Instruction::SExt:
4040           NewI = B.CreateSExtOrTrunc(
4041               CI->getOperand(0),
4042               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4043           break;
4044         case Instruction::ZExt:
4045           NewI = B.CreateZExtOrTrunc(
4046               CI->getOperand(0),
4047               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4048           break;
4049         }
4050       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
4051         auto Elements0 =
4052             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
4053         auto *O0 = B.CreateZExtOrTrunc(
4054             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
4055         auto Elements1 =
4056             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
4057         auto *O1 = B.CreateZExtOrTrunc(
4058             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
4059 
4060         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4061       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4062         // Don't do anything with the operands, just extend the result.
4063         continue;
4064       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4065         auto Elements =
4066             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
4067         auto *O0 = B.CreateZExtOrTrunc(
4068             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
4069         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4070         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4071       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4072         auto Elements =
4073             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
4074         auto *O0 = B.CreateZExtOrTrunc(
4075             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
4076         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4077       } else {
4078         // If we don't know what to do, be conservative and don't do anything.
4079         continue;
4080       }
4081 
4082       // Lastly, extend the result.
4083       NewI->takeName(cast<Instruction>(I));
4084       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4085       I->replaceAllUsesWith(Res);
4086       cast<Instruction>(I)->eraseFromParent();
4087       Erased.insert(I);
4088       State.reset(Def, Res, Part);
4089     }
4090   }
4091 
4092   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4093   for (const auto &KV : Cost->getMinimalBitwidths()) {
4094     // If the value wasn't vectorized, we must maintain the original scalar
4095     // type. The absence of the value from State indicates that it
4096     // wasn't vectorized.
4097     // FIXME: Should not rely on getVPValue at this point.
4098     VPValue *Def = State.Plan->getVPValue(KV.first, true);
4099     if (!State.hasAnyVectorValue(Def))
4100       continue;
4101     for (unsigned Part = 0; Part < UF; ++Part) {
4102       Value *I = State.get(Def, Part);
4103       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4104       if (Inst && Inst->use_empty()) {
4105         Value *NewI = Inst->getOperand(0);
4106         Inst->eraseFromParent();
4107         State.reset(Def, NewI, Part);
4108       }
4109     }
4110   }
4111 }
4112 
4113 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4114   // Insert truncates and extends for any truncated instructions as hints to
4115   // InstCombine.
4116   if (VF.isVector())
4117     truncateToMinimalBitwidths(State);
4118 
4119   // Fix widened non-induction PHIs by setting up the PHI operands.
4120   if (OrigPHIsToFix.size()) {
4121     assert(EnableVPlanNativePath &&
4122            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4123     fixNonInductionPHIs(State);
4124   }
4125 
4126   // At this point every instruction in the original loop is widened to a
4127   // vector form. Now we need to fix the recurrences in the loop. These PHI
4128   // nodes are currently empty because we did not want to introduce cycles.
4129   // This is the second stage of vectorizing recurrences.
4130   fixCrossIterationPHIs(State);
4131 
4132   // Forget the original basic block.
4133   PSE.getSE()->forgetLoop(OrigLoop);
4134 
4135   // If we inserted an edge from the middle block to the unique exit block,
4136   // update uses outside the loop (phis) to account for the newly inserted
4137   // edge.
4138   if (!Cost->requiresScalarEpilogue(VF)) {
4139     // Fix-up external users of the induction variables.
4140     for (auto &Entry : Legal->getInductionVars())
4141       fixupIVUsers(Entry.first, Entry.second,
4142                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4143                    IVEndValues[Entry.first], LoopMiddleBlock);
4144 
4145     fixLCSSAPHIs(State);
4146   }
4147 
4148   for (Instruction *PI : PredicatedInstructions)
4149     sinkScalarOperands(&*PI);
4150 
4151   // Remove redundant induction instructions.
4152   cse(LoopVectorBody);
4153 
4154   // Set/update profile weights for the vector and remainder loops as original
4155   // loop iterations are now distributed among them. Note that original loop
4156   // represented by LoopScalarBody becomes remainder loop after vectorization.
4157   //
4158   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4159   // end up getting slightly roughened result but that should be OK since
4160   // profile is not inherently precise anyway. Note also possible bypass of
4161   // vector code caused by legality checks is ignored, assigning all the weight
4162   // to the vector loop, optimistically.
4163   //
4164   // For scalable vectorization we can't know at compile time how many iterations
4165   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4166   // vscale of '1'.
4167   setProfileInfoAfterUnrolling(
4168       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4169       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4170 }
4171 
4172 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4173   // In order to support recurrences we need to be able to vectorize Phi nodes.
4174   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4175   // stage #2: We now need to fix the recurrences by adding incoming edges to
4176   // the currently empty PHI nodes. At this point every instruction in the
4177   // original loop is widened to a vector form so we can use them to construct
4178   // the incoming edges.
4179   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4180   for (VPRecipeBase &R : Header->phis()) {
4181     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
4182       fixReduction(ReductionPhi, State);
4183     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
4184       fixFirstOrderRecurrence(FOR, State);
4185   }
4186 }
4187 
4188 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4189                                                   VPTransformState &State) {
4190   // This is the second phase of vectorizing first-order recurrences. An
4191   // overview of the transformation is described below. Suppose we have the
4192   // following loop.
4193   //
4194   //   for (int i = 0; i < n; ++i)
4195   //     b[i] = a[i] - a[i - 1];
4196   //
4197   // There is a first-order recurrence on "a". For this loop, the shorthand
4198   // scalar IR looks like:
4199   //
4200   //   scalar.ph:
4201   //     s_init = a[-1]
4202   //     br scalar.body
4203   //
4204   //   scalar.body:
4205   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4206   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4207   //     s2 = a[i]
4208   //     b[i] = s2 - s1
4209   //     br cond, scalar.body, ...
4210   //
4211   // In this example, s1 is a recurrence because it's value depends on the
4212   // previous iteration. In the first phase of vectorization, we created a
4213   // vector phi v1 for s1. We now complete the vectorization and produce the
4214   // shorthand vector IR shown below (for VF = 4, UF = 1).
4215   //
4216   //   vector.ph:
4217   //     v_init = vector(..., ..., ..., a[-1])
4218   //     br vector.body
4219   //
4220   //   vector.body
4221   //     i = phi [0, vector.ph], [i+4, vector.body]
4222   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4223   //     v2 = a[i, i+1, i+2, i+3];
4224   //     v3 = vector(v1(3), v2(0, 1, 2))
4225   //     b[i, i+1, i+2, i+3] = v2 - v3
4226   //     br cond, vector.body, middle.block
4227   //
4228   //   middle.block:
4229   //     x = v2(3)
4230   //     br scalar.ph
4231   //
4232   //   scalar.ph:
4233   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4234   //     br scalar.body
4235   //
4236   // After execution completes the vector loop, we extract the next value of
4237   // the recurrence (x) to use as the initial value in the scalar loop.
4238 
4239   // Extract the last vector element in the middle block. This will be the
4240   // initial value for the recurrence when jumping to the scalar loop.
4241   VPValue *PreviousDef = PhiR->getBackedgeValue();
4242   Value *Incoming = State.get(PreviousDef, UF - 1);
4243   auto *ExtractForScalar = Incoming;
4244   auto *IdxTy = Builder.getInt32Ty();
4245   if (VF.isVector()) {
4246     auto *One = ConstantInt::get(IdxTy, 1);
4247     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4248     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4249     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4250     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4251                                                     "vector.recur.extract");
4252   }
4253   // Extract the second last element in the middle block if the
4254   // Phi is used outside the loop. We need to extract the phi itself
4255   // and not the last element (the phi update in the current iteration). This
4256   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4257   // when the scalar loop is not run at all.
4258   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4259   if (VF.isVector()) {
4260     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4261     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4262     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4263         Incoming, Idx, "vector.recur.extract.for.phi");
4264   } else if (UF > 1)
4265     // When loop is unrolled without vectorizing, initialize
4266     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4267     // of `Incoming`. This is analogous to the vectorized case above: extracting
4268     // the second last element when VF > 1.
4269     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4270 
4271   // Fix the initial value of the original recurrence in the scalar loop.
4272   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4273   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4274   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4275   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4276   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4277     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4278     Start->addIncoming(Incoming, BB);
4279   }
4280 
4281   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4282   Phi->setName("scalar.recur");
4283 
4284   // Finally, fix users of the recurrence outside the loop. The users will need
4285   // either the last value of the scalar recurrence or the last value of the
4286   // vector recurrence we extracted in the middle block. Since the loop is in
4287   // LCSSA form, we just need to find all the phi nodes for the original scalar
4288   // recurrence in the exit block, and then add an edge for the middle block.
4289   // Note that LCSSA does not imply single entry when the original scalar loop
4290   // had multiple exiting edges (as we always run the last iteration in the
4291   // scalar epilogue); in that case, there is no edge from middle to exit and
4292   // and thus no phis which needed updated.
4293   if (!Cost->requiresScalarEpilogue(VF))
4294     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4295       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
4296         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4297 }
4298 
4299 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4300                                        VPTransformState &State) {
4301   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4302   // Get it's reduction variable descriptor.
4303   assert(Legal->isReductionVariable(OrigPhi) &&
4304          "Unable to find the reduction variable");
4305   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4306 
4307   RecurKind RK = RdxDesc.getRecurrenceKind();
4308   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4309   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4310   setDebugLocFromInst(ReductionStartValue);
4311 
4312   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
4313   // This is the vector-clone of the value that leaves the loop.
4314   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4315 
4316   // Wrap flags are in general invalid after vectorization, clear them.
4317   clearReductionWrapFlags(RdxDesc, State);
4318 
4319   // Before each round, move the insertion point right between
4320   // the PHIs and the values we are going to write.
4321   // This allows us to write both PHINodes and the extractelement
4322   // instructions.
4323   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4324 
4325   setDebugLocFromInst(LoopExitInst);
4326 
4327   Type *PhiTy = OrigPhi->getType();
4328   // If tail is folded by masking, the vector value to leave the loop should be
4329   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4330   // instead of the former. For an inloop reduction the reduction will already
4331   // be predicated, and does not need to be handled here.
4332   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4333     for (unsigned Part = 0; Part < UF; ++Part) {
4334       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4335       Value *Sel = nullptr;
4336       for (User *U : VecLoopExitInst->users()) {
4337         if (isa<SelectInst>(U)) {
4338           assert(!Sel && "Reduction exit feeding two selects");
4339           Sel = U;
4340         } else
4341           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4342       }
4343       assert(Sel && "Reduction exit feeds no select");
4344       State.reset(LoopExitInstDef, Sel, Part);
4345 
4346       // If the target can create a predicated operator for the reduction at no
4347       // extra cost in the loop (for example a predicated vadd), it can be
4348       // cheaper for the select to remain in the loop than be sunk out of it,
4349       // and so use the select value for the phi instead of the old
4350       // LoopExitValue.
4351       if (PreferPredicatedReductionSelect ||
4352           TTI->preferPredicatedReductionSelect(
4353               RdxDesc.getOpcode(), PhiTy,
4354               TargetTransformInfo::ReductionFlags())) {
4355         auto *VecRdxPhi =
4356             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4357         VecRdxPhi->setIncomingValueForBlock(
4358             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4359       }
4360     }
4361   }
4362 
4363   // If the vector reduction can be performed in a smaller type, we truncate
4364   // then extend the loop exit value to enable InstCombine to evaluate the
4365   // entire expression in the smaller type.
4366   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4367     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4368     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4369     Builder.SetInsertPoint(
4370         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4371     VectorParts RdxParts(UF);
4372     for (unsigned Part = 0; Part < UF; ++Part) {
4373       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4374       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4375       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4376                                         : Builder.CreateZExt(Trunc, VecTy);
4377       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4378            UI != RdxParts[Part]->user_end();)
4379         if (*UI != Trunc) {
4380           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4381           RdxParts[Part] = Extnd;
4382         } else {
4383           ++UI;
4384         }
4385     }
4386     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4387     for (unsigned Part = 0; Part < UF; ++Part) {
4388       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4389       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4390     }
4391   }
4392 
4393   // Reduce all of the unrolled parts into a single vector.
4394   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4395   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4396 
4397   // The middle block terminator has already been assigned a DebugLoc here (the
4398   // OrigLoop's single latch terminator). We want the whole middle block to
4399   // appear to execute on this line because: (a) it is all compiler generated,
4400   // (b) these instructions are always executed after evaluating the latch
4401   // conditional branch, and (c) other passes may add new predecessors which
4402   // terminate on this line. This is the easiest way to ensure we don't
4403   // accidentally cause an extra step back into the loop while debugging.
4404   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4405   if (PhiR->isOrdered())
4406     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4407   else {
4408     // Floating-point operations should have some FMF to enable the reduction.
4409     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4410     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4411     for (unsigned Part = 1; Part < UF; ++Part) {
4412       Value *RdxPart = State.get(LoopExitInstDef, Part);
4413       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4414         ReducedPartRdx = Builder.CreateBinOp(
4415             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4416       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
4417         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
4418                                            ReducedPartRdx, RdxPart);
4419       else
4420         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4421     }
4422   }
4423 
4424   // Create the reduction after the loop. Note that inloop reductions create the
4425   // target reduction in the loop using a Reduction recipe.
4426   if (VF.isVector() && !PhiR->isInLoop()) {
4427     ReducedPartRdx =
4428         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
4429     // If the reduction can be performed in a smaller type, we need to extend
4430     // the reduction to the wider type before we branch to the original loop.
4431     if (PhiTy != RdxDesc.getRecurrenceType())
4432       ReducedPartRdx = RdxDesc.isSigned()
4433                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4434                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4435   }
4436 
4437   // Create a phi node that merges control-flow from the backedge-taken check
4438   // block and the middle block.
4439   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4440                                         LoopScalarPreHeader->getTerminator());
4441   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4442     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4443   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4444 
4445   // Now, we need to fix the users of the reduction variable
4446   // inside and outside of the scalar remainder loop.
4447 
4448   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4449   // in the exit blocks.  See comment on analogous loop in
4450   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4451   if (!Cost->requiresScalarEpilogue(VF))
4452     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4453       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4454         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4455 
4456   // Fix the scalar loop reduction variable with the incoming reduction sum
4457   // from the vector body and from the backedge value.
4458   int IncomingEdgeBlockIdx =
4459       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4460   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4461   // Pick the other block.
4462   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4463   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4464   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4465 }
4466 
4467 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4468                                                   VPTransformState &State) {
4469   RecurKind RK = RdxDesc.getRecurrenceKind();
4470   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4471     return;
4472 
4473   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4474   assert(LoopExitInstr && "null loop exit instruction");
4475   SmallVector<Instruction *, 8> Worklist;
4476   SmallPtrSet<Instruction *, 8> Visited;
4477   Worklist.push_back(LoopExitInstr);
4478   Visited.insert(LoopExitInstr);
4479 
4480   while (!Worklist.empty()) {
4481     Instruction *Cur = Worklist.pop_back_val();
4482     if (isa<OverflowingBinaryOperator>(Cur))
4483       for (unsigned Part = 0; Part < UF; ++Part) {
4484         // FIXME: Should not rely on getVPValue at this point.
4485         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4486         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4487       }
4488 
4489     for (User *U : Cur->users()) {
4490       Instruction *UI = cast<Instruction>(U);
4491       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4492           Visited.insert(UI).second)
4493         Worklist.push_back(UI);
4494     }
4495   }
4496 }
4497 
4498 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4499   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4500     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4501       // Some phis were already hand updated by the reduction and recurrence
4502       // code above, leave them alone.
4503       continue;
4504 
4505     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4506     // Non-instruction incoming values will have only one value.
4507 
4508     VPLane Lane = VPLane::getFirstLane();
4509     if (isa<Instruction>(IncomingValue) &&
4510         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4511                                            VF))
4512       Lane = VPLane::getLastLaneForVF(VF);
4513 
4514     // Can be a loop invariant incoming value or the last scalar value to be
4515     // extracted from the vectorized loop.
4516     // FIXME: Should not rely on getVPValue at this point.
4517     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4518     Value *lastIncomingValue =
4519         OrigLoop->isLoopInvariant(IncomingValue)
4520             ? IncomingValue
4521             : State.get(State.Plan->getVPValue(IncomingValue, true),
4522                         VPIteration(UF - 1, Lane));
4523     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4524   }
4525 }
4526 
4527 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4528   // The basic block and loop containing the predicated instruction.
4529   auto *PredBB = PredInst->getParent();
4530   auto *VectorLoop = LI->getLoopFor(PredBB);
4531 
4532   // Initialize a worklist with the operands of the predicated instruction.
4533   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4534 
4535   // Holds instructions that we need to analyze again. An instruction may be
4536   // reanalyzed if we don't yet know if we can sink it or not.
4537   SmallVector<Instruction *, 8> InstsToReanalyze;
4538 
4539   // Returns true if a given use occurs in the predicated block. Phi nodes use
4540   // their operands in their corresponding predecessor blocks.
4541   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4542     auto *I = cast<Instruction>(U.getUser());
4543     BasicBlock *BB = I->getParent();
4544     if (auto *Phi = dyn_cast<PHINode>(I))
4545       BB = Phi->getIncomingBlock(
4546           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4547     return BB == PredBB;
4548   };
4549 
4550   // Iteratively sink the scalarized operands of the predicated instruction
4551   // into the block we created for it. When an instruction is sunk, it's
4552   // operands are then added to the worklist. The algorithm ends after one pass
4553   // through the worklist doesn't sink a single instruction.
4554   bool Changed;
4555   do {
4556     // Add the instructions that need to be reanalyzed to the worklist, and
4557     // reset the changed indicator.
4558     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4559     InstsToReanalyze.clear();
4560     Changed = false;
4561 
4562     while (!Worklist.empty()) {
4563       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4564 
4565       // We can't sink an instruction if it is a phi node, is not in the loop,
4566       // or may have side effects.
4567       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4568           I->mayHaveSideEffects())
4569         continue;
4570 
4571       // If the instruction is already in PredBB, check if we can sink its
4572       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4573       // sinking the scalar instruction I, hence it appears in PredBB; but it
4574       // may have failed to sink I's operands (recursively), which we try
4575       // (again) here.
4576       if (I->getParent() == PredBB) {
4577         Worklist.insert(I->op_begin(), I->op_end());
4578         continue;
4579       }
4580 
4581       // It's legal to sink the instruction if all its uses occur in the
4582       // predicated block. Otherwise, there's nothing to do yet, and we may
4583       // need to reanalyze the instruction.
4584       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4585         InstsToReanalyze.push_back(I);
4586         continue;
4587       }
4588 
4589       // Move the instruction to the beginning of the predicated block, and add
4590       // it's operands to the worklist.
4591       I->moveBefore(&*PredBB->getFirstInsertionPt());
4592       Worklist.insert(I->op_begin(), I->op_end());
4593 
4594       // The sinking may have enabled other instructions to be sunk, so we will
4595       // need to iterate.
4596       Changed = true;
4597     }
4598   } while (Changed);
4599 }
4600 
4601 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4602   for (PHINode *OrigPhi : OrigPHIsToFix) {
4603     VPWidenPHIRecipe *VPPhi =
4604         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4605     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4606     // Make sure the builder has a valid insert point.
4607     Builder.SetInsertPoint(NewPhi);
4608     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4609       VPValue *Inc = VPPhi->getIncomingValue(i);
4610       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4611       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4612     }
4613   }
4614 }
4615 
4616 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4617   return Cost->useOrderedReductions(RdxDesc);
4618 }
4619 
4620 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4621                                    VPUser &Operands, unsigned UF,
4622                                    ElementCount VF, bool IsPtrLoopInvariant,
4623                                    SmallBitVector &IsIndexLoopInvariant,
4624                                    VPTransformState &State) {
4625   // Construct a vector GEP by widening the operands of the scalar GEP as
4626   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4627   // results in a vector of pointers when at least one operand of the GEP
4628   // is vector-typed. Thus, to keep the representation compact, we only use
4629   // vector-typed operands for loop-varying values.
4630 
4631   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4632     // If we are vectorizing, but the GEP has only loop-invariant operands,
4633     // the GEP we build (by only using vector-typed operands for
4634     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4635     // produce a vector of pointers, we need to either arbitrarily pick an
4636     // operand to broadcast, or broadcast a clone of the original GEP.
4637     // Here, we broadcast a clone of the original.
4638     //
4639     // TODO: If at some point we decide to scalarize instructions having
4640     //       loop-invariant operands, this special case will no longer be
4641     //       required. We would add the scalarization decision to
4642     //       collectLoopScalars() and teach getVectorValue() to broadcast
4643     //       the lane-zero scalar value.
4644     auto *Clone = Builder.Insert(GEP->clone());
4645     for (unsigned Part = 0; Part < UF; ++Part) {
4646       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4647       State.set(VPDef, EntryPart, Part);
4648       addMetadata(EntryPart, GEP);
4649     }
4650   } else {
4651     // If the GEP has at least one loop-varying operand, we are sure to
4652     // produce a vector of pointers. But if we are only unrolling, we want
4653     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4654     // produce with the code below will be scalar (if VF == 1) or vector
4655     // (otherwise). Note that for the unroll-only case, we still maintain
4656     // values in the vector mapping with initVector, as we do for other
4657     // instructions.
4658     for (unsigned Part = 0; Part < UF; ++Part) {
4659       // The pointer operand of the new GEP. If it's loop-invariant, we
4660       // won't broadcast it.
4661       auto *Ptr = IsPtrLoopInvariant
4662                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4663                       : State.get(Operands.getOperand(0), Part);
4664 
4665       // Collect all the indices for the new GEP. If any index is
4666       // loop-invariant, we won't broadcast it.
4667       SmallVector<Value *, 4> Indices;
4668       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4669         VPValue *Operand = Operands.getOperand(I);
4670         if (IsIndexLoopInvariant[I - 1])
4671           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4672         else
4673           Indices.push_back(State.get(Operand, Part));
4674       }
4675 
4676       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4677       // but it should be a vector, otherwise.
4678       auto *NewGEP =
4679           GEP->isInBounds()
4680               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4681                                           Indices)
4682               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4683       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4684              "NewGEP is not a pointer vector");
4685       State.set(VPDef, NewGEP, Part);
4686       addMetadata(NewGEP, GEP);
4687     }
4688   }
4689 }
4690 
4691 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4692                                               VPWidenPHIRecipe *PhiR,
4693                                               VPTransformState &State) {
4694   PHINode *P = cast<PHINode>(PN);
4695   if (EnableVPlanNativePath) {
4696     // Currently we enter here in the VPlan-native path for non-induction
4697     // PHIs where all control flow is uniform. We simply widen these PHIs.
4698     // Create a vector phi with no operands - the vector phi operands will be
4699     // set at the end of vector code generation.
4700     Type *VecTy = (State.VF.isScalar())
4701                       ? PN->getType()
4702                       : VectorType::get(PN->getType(), State.VF);
4703     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4704     State.set(PhiR, VecPhi, 0);
4705     OrigPHIsToFix.push_back(P);
4706 
4707     return;
4708   }
4709 
4710   assert(PN->getParent() == OrigLoop->getHeader() &&
4711          "Non-header phis should have been handled elsewhere");
4712 
4713   // In order to support recurrences we need to be able to vectorize Phi nodes.
4714   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4715   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4716   // this value when we vectorize all of the instructions that use the PHI.
4717 
4718   assert(!Legal->isReductionVariable(P) &&
4719          "reductions should be handled elsewhere");
4720 
4721   setDebugLocFromInst(P);
4722 
4723   // This PHINode must be an induction variable.
4724   // Make sure that we know about it.
4725   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4726 
4727   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4728   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4729 
4730   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4731   // which can be found from the original scalar operations.
4732   switch (II.getKind()) {
4733   case InductionDescriptor::IK_NoInduction:
4734     llvm_unreachable("Unknown induction");
4735   case InductionDescriptor::IK_IntInduction:
4736   case InductionDescriptor::IK_FpInduction:
4737     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4738   case InductionDescriptor::IK_PtrInduction: {
4739     // Handle the pointer induction variable case.
4740     assert(P->getType()->isPointerTy() && "Unexpected type.");
4741 
4742     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4743       // This is the normalized GEP that starts counting at zero.
4744       Value *PtrInd =
4745           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4746       // Determine the number of scalars we need to generate for each unroll
4747       // iteration. If the instruction is uniform, we only need to generate the
4748       // first lane. Otherwise, we generate all VF values.
4749       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4750       unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
4751 
4752       bool NeedsVectorIndex = !IsUniform && VF.isScalable();
4753       Value *UnitStepVec = nullptr, *PtrIndSplat = nullptr;
4754       if (NeedsVectorIndex) {
4755         Type *VecIVTy = VectorType::get(PtrInd->getType(), VF);
4756         UnitStepVec = Builder.CreateStepVector(VecIVTy);
4757         PtrIndSplat = Builder.CreateVectorSplat(VF, PtrInd);
4758       }
4759 
4760       for (unsigned Part = 0; Part < UF; ++Part) {
4761         Value *PartStart = createStepForVF(
4762             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4763 
4764         if (NeedsVectorIndex) {
4765           // Here we cache the whole vector, which means we can support the
4766           // extraction of any lane. However, in some cases the extractelement
4767           // instruction that is generated for scalar uses of this vector (e.g.
4768           // a load instruction) is not folded away. Therefore we still
4769           // calculate values for the first n lanes to avoid redundant moves
4770           // (when extracting the 0th element) and to produce scalar code (i.e.
4771           // additional add/gep instructions instead of expensive extractelement
4772           // instructions) when extracting higher-order elements.
4773           Value *PartStartSplat = Builder.CreateVectorSplat(VF, PartStart);
4774           Value *Indices = Builder.CreateAdd(PartStartSplat, UnitStepVec);
4775           Value *GlobalIndices = Builder.CreateAdd(PtrIndSplat, Indices);
4776           Value *SclrGep =
4777               emitTransformedIndex(Builder, GlobalIndices, PSE.getSE(), DL, II);
4778           SclrGep->setName("next.gep");
4779           State.set(PhiR, SclrGep, Part);
4780         }
4781 
4782         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4783           Value *Idx = Builder.CreateAdd(
4784               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4785           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4786           Value *SclrGep =
4787               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4788           SclrGep->setName("next.gep");
4789           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4790         }
4791       }
4792       return;
4793     }
4794     assert(isa<SCEVConstant>(II.getStep()) &&
4795            "Induction step not a SCEV constant!");
4796     Type *PhiType = II.getStep()->getType();
4797 
4798     // Build a pointer phi
4799     Value *ScalarStartValue = II.getStartValue();
4800     Type *ScStValueType = ScalarStartValue->getType();
4801     PHINode *NewPointerPhi =
4802         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4803     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4804 
4805     // A pointer induction, performed by using a gep
4806     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4807     Instruction *InductionLoc = LoopLatch->getTerminator();
4808     const SCEV *ScalarStep = II.getStep();
4809     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4810     Value *ScalarStepValue =
4811         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4812     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4813     Value *NumUnrolledElems =
4814         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4815     Value *InductionGEP = GetElementPtrInst::Create(
4816         II.getElementType(), NewPointerPhi,
4817         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4818         InductionLoc);
4819     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4820 
4821     // Create UF many actual address geps that use the pointer
4822     // phi as base and a vectorized version of the step value
4823     // (<step*0, ..., step*N>) as offset.
4824     for (unsigned Part = 0; Part < State.UF; ++Part) {
4825       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4826       Value *StartOffsetScalar =
4827           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4828       Value *StartOffset =
4829           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4830       // Create a vector of consecutive numbers from zero to VF.
4831       StartOffset =
4832           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4833 
4834       Value *GEP = Builder.CreateGEP(
4835           II.getElementType(), NewPointerPhi,
4836           Builder.CreateMul(
4837               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4838               "vector.gep"));
4839       State.set(PhiR, GEP, Part);
4840     }
4841   }
4842   }
4843 }
4844 
4845 /// A helper function for checking whether an integer division-related
4846 /// instruction may divide by zero (in which case it must be predicated if
4847 /// executed conditionally in the scalar code).
4848 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4849 /// Non-zero divisors that are non compile-time constants will not be
4850 /// converted into multiplication, so we will still end up scalarizing
4851 /// the division, but can do so w/o predication.
4852 static bool mayDivideByZero(Instruction &I) {
4853   assert((I.getOpcode() == Instruction::UDiv ||
4854           I.getOpcode() == Instruction::SDiv ||
4855           I.getOpcode() == Instruction::URem ||
4856           I.getOpcode() == Instruction::SRem) &&
4857          "Unexpected instruction");
4858   Value *Divisor = I.getOperand(1);
4859   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4860   return !CInt || CInt->isZero();
4861 }
4862 
4863 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4864                                            VPUser &User,
4865                                            VPTransformState &State) {
4866   switch (I.getOpcode()) {
4867   case Instruction::Call:
4868   case Instruction::Br:
4869   case Instruction::PHI:
4870   case Instruction::GetElementPtr:
4871   case Instruction::Select:
4872     llvm_unreachable("This instruction is handled by a different recipe.");
4873   case Instruction::UDiv:
4874   case Instruction::SDiv:
4875   case Instruction::SRem:
4876   case Instruction::URem:
4877   case Instruction::Add:
4878   case Instruction::FAdd:
4879   case Instruction::Sub:
4880   case Instruction::FSub:
4881   case Instruction::FNeg:
4882   case Instruction::Mul:
4883   case Instruction::FMul:
4884   case Instruction::FDiv:
4885   case Instruction::FRem:
4886   case Instruction::Shl:
4887   case Instruction::LShr:
4888   case Instruction::AShr:
4889   case Instruction::And:
4890   case Instruction::Or:
4891   case Instruction::Xor: {
4892     // Just widen unops and binops.
4893     setDebugLocFromInst(&I);
4894 
4895     for (unsigned Part = 0; Part < UF; ++Part) {
4896       SmallVector<Value *, 2> Ops;
4897       for (VPValue *VPOp : User.operands())
4898         Ops.push_back(State.get(VPOp, Part));
4899 
4900       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4901 
4902       if (auto *VecOp = dyn_cast<Instruction>(V))
4903         VecOp->copyIRFlags(&I);
4904 
4905       // Use this vector value for all users of the original instruction.
4906       State.set(Def, V, Part);
4907       addMetadata(V, &I);
4908     }
4909 
4910     break;
4911   }
4912   case Instruction::ICmp:
4913   case Instruction::FCmp: {
4914     // Widen compares. Generate vector compares.
4915     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4916     auto *Cmp = cast<CmpInst>(&I);
4917     setDebugLocFromInst(Cmp);
4918     for (unsigned Part = 0; Part < UF; ++Part) {
4919       Value *A = State.get(User.getOperand(0), Part);
4920       Value *B = State.get(User.getOperand(1), Part);
4921       Value *C = nullptr;
4922       if (FCmp) {
4923         // Propagate fast math flags.
4924         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4925         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4926         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4927       } else {
4928         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4929       }
4930       State.set(Def, C, Part);
4931       addMetadata(C, &I);
4932     }
4933 
4934     break;
4935   }
4936 
4937   case Instruction::ZExt:
4938   case Instruction::SExt:
4939   case Instruction::FPToUI:
4940   case Instruction::FPToSI:
4941   case Instruction::FPExt:
4942   case Instruction::PtrToInt:
4943   case Instruction::IntToPtr:
4944   case Instruction::SIToFP:
4945   case Instruction::UIToFP:
4946   case Instruction::Trunc:
4947   case Instruction::FPTrunc:
4948   case Instruction::BitCast: {
4949     auto *CI = cast<CastInst>(&I);
4950     setDebugLocFromInst(CI);
4951 
4952     /// Vectorize casts.
4953     Type *DestTy =
4954         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
4955 
4956     for (unsigned Part = 0; Part < UF; ++Part) {
4957       Value *A = State.get(User.getOperand(0), Part);
4958       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4959       State.set(Def, Cast, Part);
4960       addMetadata(Cast, &I);
4961     }
4962     break;
4963   }
4964   default:
4965     // This instruction is not vectorized by simple widening.
4966     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4967     llvm_unreachable("Unhandled instruction!");
4968   } // end of switch.
4969 }
4970 
4971 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4972                                                VPUser &ArgOperands,
4973                                                VPTransformState &State) {
4974   assert(!isa<DbgInfoIntrinsic>(I) &&
4975          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4976   setDebugLocFromInst(&I);
4977 
4978   Module *M = I.getParent()->getParent()->getParent();
4979   auto *CI = cast<CallInst>(&I);
4980 
4981   SmallVector<Type *, 4> Tys;
4982   for (Value *ArgOperand : CI->args())
4983     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4984 
4985   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4986 
4987   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4988   // version of the instruction.
4989   // Is it beneficial to perform intrinsic call compared to lib call?
4990   bool NeedToScalarize = false;
4991   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4992   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4993   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4994   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4995          "Instruction should be scalarized elsewhere.");
4996   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4997          "Either the intrinsic cost or vector call cost must be valid");
4998 
4999   for (unsigned Part = 0; Part < UF; ++Part) {
5000     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
5001     SmallVector<Value *, 4> Args;
5002     for (auto &I : enumerate(ArgOperands.operands())) {
5003       // Some intrinsics have a scalar argument - don't replace it with a
5004       // vector.
5005       Value *Arg;
5006       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5007         Arg = State.get(I.value(), Part);
5008       else {
5009         Arg = State.get(I.value(), VPIteration(0, 0));
5010         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
5011           TysForDecl.push_back(Arg->getType());
5012       }
5013       Args.push_back(Arg);
5014     }
5015 
5016     Function *VectorF;
5017     if (UseVectorIntrinsic) {
5018       // Use vector version of the intrinsic.
5019       if (VF.isVector())
5020         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5021       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5022       assert(VectorF && "Can't retrieve vector intrinsic.");
5023     } else {
5024       // Use vector version of the function call.
5025       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5026 #ifndef NDEBUG
5027       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5028              "Can't create vector function.");
5029 #endif
5030         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5031     }
5032       SmallVector<OperandBundleDef, 1> OpBundles;
5033       CI->getOperandBundlesAsDefs(OpBundles);
5034       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5035 
5036       if (isa<FPMathOperator>(V))
5037         V->copyFastMathFlags(CI);
5038 
5039       State.set(Def, V, Part);
5040       addMetadata(V, &I);
5041   }
5042 }
5043 
5044 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5045                                                  VPUser &Operands,
5046                                                  bool InvariantCond,
5047                                                  VPTransformState &State) {
5048   setDebugLocFromInst(&I);
5049 
5050   // The condition can be loop invariant  but still defined inside the
5051   // loop. This means that we can't just use the original 'cond' value.
5052   // We have to take the 'vectorized' value and pick the first lane.
5053   // Instcombine will make this a no-op.
5054   auto *InvarCond = InvariantCond
5055                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5056                         : nullptr;
5057 
5058   for (unsigned Part = 0; Part < UF; ++Part) {
5059     Value *Cond =
5060         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5061     Value *Op0 = State.get(Operands.getOperand(1), Part);
5062     Value *Op1 = State.get(Operands.getOperand(2), Part);
5063     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5064     State.set(VPDef, Sel, Part);
5065     addMetadata(Sel, &I);
5066   }
5067 }
5068 
5069 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5070   // We should not collect Scalars more than once per VF. Right now, this
5071   // function is called from collectUniformsAndScalars(), which already does
5072   // this check. Collecting Scalars for VF=1 does not make any sense.
5073   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5074          "This function should not be visited twice for the same VF");
5075 
5076   SmallSetVector<Instruction *, 8> Worklist;
5077 
5078   // These sets are used to seed the analysis with pointers used by memory
5079   // accesses that will remain scalar.
5080   SmallSetVector<Instruction *, 8> ScalarPtrs;
5081   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5082   auto *Latch = TheLoop->getLoopLatch();
5083 
5084   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5085   // The pointer operands of loads and stores will be scalar as long as the
5086   // memory access is not a gather or scatter operation. The value operand of a
5087   // store will remain scalar if the store is scalarized.
5088   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5089     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5090     assert(WideningDecision != CM_Unknown &&
5091            "Widening decision should be ready at this moment");
5092     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5093       if (Ptr == Store->getValueOperand())
5094         return WideningDecision == CM_Scalarize;
5095     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5096            "Ptr is neither a value or pointer operand");
5097     return WideningDecision != CM_GatherScatter;
5098   };
5099 
5100   // A helper that returns true if the given value is a bitcast or
5101   // getelementptr instruction contained in the loop.
5102   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5103     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5104             isa<GetElementPtrInst>(V)) &&
5105            !TheLoop->isLoopInvariant(V);
5106   };
5107 
5108   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5109     if (!isa<PHINode>(Ptr) ||
5110         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5111       return false;
5112     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5113     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5114       return false;
5115     return isScalarUse(MemAccess, Ptr);
5116   };
5117 
5118   // A helper that evaluates a memory access's use of a pointer. If the
5119   // pointer is actually the pointer induction of a loop, it is being
5120   // inserted into Worklist. If the use will be a scalar use, and the
5121   // pointer is only used by memory accesses, we place the pointer in
5122   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5123   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5124     if (isScalarPtrInduction(MemAccess, Ptr)) {
5125       Worklist.insert(cast<Instruction>(Ptr));
5126       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5127                         << "\n");
5128 
5129       Instruction *Update = cast<Instruction>(
5130           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5131 
5132       // If there is more than one user of Update (Ptr), we shouldn't assume it
5133       // will be scalar after vectorisation as other users of the instruction
5134       // may require widening. Otherwise, add it to ScalarPtrs.
5135       if (Update->hasOneUse() && cast<Value>(*Update->user_begin()) == Ptr) {
5136         ScalarPtrs.insert(Update);
5137         return;
5138       }
5139     }
5140     // We only care about bitcast and getelementptr instructions contained in
5141     // the loop.
5142     if (!isLoopVaryingBitCastOrGEP(Ptr))
5143       return;
5144 
5145     // If the pointer has already been identified as scalar (e.g., if it was
5146     // also identified as uniform), there's nothing to do.
5147     auto *I = cast<Instruction>(Ptr);
5148     if (Worklist.count(I))
5149       return;
5150 
5151     // If the use of the pointer will be a scalar use, and all users of the
5152     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5153     // place the pointer in PossibleNonScalarPtrs.
5154     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5155           return isa<LoadInst>(U) || isa<StoreInst>(U);
5156         }))
5157       ScalarPtrs.insert(I);
5158     else
5159       PossibleNonScalarPtrs.insert(I);
5160   };
5161 
5162   // We seed the scalars analysis with three classes of instructions: (1)
5163   // instructions marked uniform-after-vectorization and (2) bitcast,
5164   // getelementptr and (pointer) phi instructions used by memory accesses
5165   // requiring a scalar use.
5166   //
5167   // (1) Add to the worklist all instructions that have been identified as
5168   // uniform-after-vectorization.
5169   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5170 
5171   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5172   // memory accesses requiring a scalar use. The pointer operands of loads and
5173   // stores will be scalar as long as the memory accesses is not a gather or
5174   // scatter operation. The value operand of a store will remain scalar if the
5175   // store is scalarized.
5176   for (auto *BB : TheLoop->blocks())
5177     for (auto &I : *BB) {
5178       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5179         evaluatePtrUse(Load, Load->getPointerOperand());
5180       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5181         evaluatePtrUse(Store, Store->getPointerOperand());
5182         evaluatePtrUse(Store, Store->getValueOperand());
5183       }
5184     }
5185   for (auto *I : ScalarPtrs)
5186     if (!PossibleNonScalarPtrs.count(I)) {
5187       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5188       Worklist.insert(I);
5189     }
5190 
5191   // Insert the forced scalars.
5192   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5193   // induction variable when the PHI user is scalarized.
5194   auto ForcedScalar = ForcedScalars.find(VF);
5195   if (ForcedScalar != ForcedScalars.end())
5196     for (auto *I : ForcedScalar->second)
5197       Worklist.insert(I);
5198 
5199   // Expand the worklist by looking through any bitcasts and getelementptr
5200   // instructions we've already identified as scalar. This is similar to the
5201   // expansion step in collectLoopUniforms(); however, here we're only
5202   // expanding to include additional bitcasts and getelementptr instructions.
5203   unsigned Idx = 0;
5204   while (Idx != Worklist.size()) {
5205     Instruction *Dst = Worklist[Idx++];
5206     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5207       continue;
5208     auto *Src = cast<Instruction>(Dst->getOperand(0));
5209     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5210           auto *J = cast<Instruction>(U);
5211           return !TheLoop->contains(J) || Worklist.count(J) ||
5212                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5213                   isScalarUse(J, Src));
5214         })) {
5215       Worklist.insert(Src);
5216       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5217     }
5218   }
5219 
5220   // An induction variable will remain scalar if all users of the induction
5221   // variable and induction variable update remain scalar.
5222   for (auto &Induction : Legal->getInductionVars()) {
5223     auto *Ind = Induction.first;
5224     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5225 
5226     // If tail-folding is applied, the primary induction variable will be used
5227     // to feed a vector compare.
5228     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5229       continue;
5230 
5231     // Determine if all users of the induction variable are scalar after
5232     // vectorization.
5233     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5234       auto *I = cast<Instruction>(U);
5235       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5236     });
5237     if (!ScalarInd)
5238       continue;
5239 
5240     // Determine if all users of the induction variable update instruction are
5241     // scalar after vectorization.
5242     auto ScalarIndUpdate =
5243         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5244           auto *I = cast<Instruction>(U);
5245           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5246         });
5247     if (!ScalarIndUpdate)
5248       continue;
5249 
5250     // The induction variable and its update instruction will remain scalar.
5251     Worklist.insert(Ind);
5252     Worklist.insert(IndUpdate);
5253     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5254     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5255                       << "\n");
5256   }
5257 
5258   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5259 }
5260 
5261 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5262   if (!blockNeedsPredication(I->getParent()))
5263     return false;
5264   switch(I->getOpcode()) {
5265   default:
5266     break;
5267   case Instruction::Load:
5268   case Instruction::Store: {
5269     if (!Legal->isMaskRequired(I))
5270       return false;
5271     auto *Ptr = getLoadStorePointerOperand(I);
5272     auto *Ty = getLoadStoreType(I);
5273     const Align Alignment = getLoadStoreAlignment(I);
5274     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5275                                 TTI.isLegalMaskedGather(Ty, Alignment))
5276                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5277                                 TTI.isLegalMaskedScatter(Ty, Alignment));
5278   }
5279   case Instruction::UDiv:
5280   case Instruction::SDiv:
5281   case Instruction::SRem:
5282   case Instruction::URem:
5283     return mayDivideByZero(*I);
5284   }
5285   return false;
5286 }
5287 
5288 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5289     Instruction *I, ElementCount VF) {
5290   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5291   assert(getWideningDecision(I, VF) == CM_Unknown &&
5292          "Decision should not be set yet.");
5293   auto *Group = getInterleavedAccessGroup(I);
5294   assert(Group && "Must have a group.");
5295 
5296   // If the instruction's allocated size doesn't equal it's type size, it
5297   // requires padding and will be scalarized.
5298   auto &DL = I->getModule()->getDataLayout();
5299   auto *ScalarTy = getLoadStoreType(I);
5300   if (hasIrregularType(ScalarTy, DL))
5301     return false;
5302 
5303   // Check if masking is required.
5304   // A Group may need masking for one of two reasons: it resides in a block that
5305   // needs predication, or it was decided to use masking to deal with gaps
5306   // (either a gap at the end of a load-access that may result in a speculative
5307   // load, or any gaps in a store-access).
5308   bool PredicatedAccessRequiresMasking =
5309       blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5310   bool LoadAccessWithGapsRequiresEpilogMasking =
5311       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
5312       !isScalarEpilogueAllowed();
5313   bool StoreAccessWithGapsRequiresMasking =
5314       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
5315   if (!PredicatedAccessRequiresMasking &&
5316       !LoadAccessWithGapsRequiresEpilogMasking &&
5317       !StoreAccessWithGapsRequiresMasking)
5318     return true;
5319 
5320   // If masked interleaving is required, we expect that the user/target had
5321   // enabled it, because otherwise it either wouldn't have been created or
5322   // it should have been invalidated by the CostModel.
5323   assert(useMaskedInterleavedAccesses(TTI) &&
5324          "Masked interleave-groups for predicated accesses are not enabled.");
5325 
5326   if (Group->isReverse())
5327     return false;
5328 
5329   auto *Ty = getLoadStoreType(I);
5330   const Align Alignment = getLoadStoreAlignment(I);
5331   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5332                           : TTI.isLegalMaskedStore(Ty, Alignment);
5333 }
5334 
5335 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5336     Instruction *I, ElementCount VF) {
5337   // Get and ensure we have a valid memory instruction.
5338   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
5339 
5340   auto *Ptr = getLoadStorePointerOperand(I);
5341   auto *ScalarTy = getLoadStoreType(I);
5342 
5343   // In order to be widened, the pointer should be consecutive, first of all.
5344   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
5345     return false;
5346 
5347   // If the instruction is a store located in a predicated block, it will be
5348   // scalarized.
5349   if (isScalarWithPredication(I))
5350     return false;
5351 
5352   // If the instruction's allocated size doesn't equal it's type size, it
5353   // requires padding and will be scalarized.
5354   auto &DL = I->getModule()->getDataLayout();
5355   if (hasIrregularType(ScalarTy, DL))
5356     return false;
5357 
5358   return true;
5359 }
5360 
5361 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5362   // We should not collect Uniforms more than once per VF. Right now,
5363   // this function is called from collectUniformsAndScalars(), which
5364   // already does this check. Collecting Uniforms for VF=1 does not make any
5365   // sense.
5366 
5367   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5368          "This function should not be visited twice for the same VF");
5369 
5370   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5371   // not analyze again.  Uniforms.count(VF) will return 1.
5372   Uniforms[VF].clear();
5373 
5374   // We now know that the loop is vectorizable!
5375   // Collect instructions inside the loop that will remain uniform after
5376   // vectorization.
5377 
5378   // Global values, params and instructions outside of current loop are out of
5379   // scope.
5380   auto isOutOfScope = [&](Value *V) -> bool {
5381     Instruction *I = dyn_cast<Instruction>(V);
5382     return (!I || !TheLoop->contains(I));
5383   };
5384 
5385   SetVector<Instruction *> Worklist;
5386   BasicBlock *Latch = TheLoop->getLoopLatch();
5387 
5388   // Instructions that are scalar with predication must not be considered
5389   // uniform after vectorization, because that would create an erroneous
5390   // replicating region where only a single instance out of VF should be formed.
5391   // TODO: optimize such seldom cases if found important, see PR40816.
5392   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5393     if (isOutOfScope(I)) {
5394       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5395                         << *I << "\n");
5396       return;
5397     }
5398     if (isScalarWithPredication(I)) {
5399       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5400                         << *I << "\n");
5401       return;
5402     }
5403     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5404     Worklist.insert(I);
5405   };
5406 
5407   // Start with the conditional branch. If the branch condition is an
5408   // instruction contained in the loop that is only used by the branch, it is
5409   // uniform.
5410   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5411   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5412     addToWorklistIfAllowed(Cmp);
5413 
5414   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5415     InstWidening WideningDecision = getWideningDecision(I, VF);
5416     assert(WideningDecision != CM_Unknown &&
5417            "Widening decision should be ready at this moment");
5418 
5419     // A uniform memory op is itself uniform.  We exclude uniform stores
5420     // here as they demand the last lane, not the first one.
5421     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5422       assert(WideningDecision == CM_Scalarize);
5423       return true;
5424     }
5425 
5426     return (WideningDecision == CM_Widen ||
5427             WideningDecision == CM_Widen_Reverse ||
5428             WideningDecision == CM_Interleave);
5429   };
5430 
5431 
5432   // Returns true if Ptr is the pointer operand of a memory access instruction
5433   // I, and I is known to not require scalarization.
5434   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5435     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5436   };
5437 
5438   // Holds a list of values which are known to have at least one uniform use.
5439   // Note that there may be other uses which aren't uniform.  A "uniform use"
5440   // here is something which only demands lane 0 of the unrolled iterations;
5441   // it does not imply that all lanes produce the same value (e.g. this is not
5442   // the usual meaning of uniform)
5443   SetVector<Value *> HasUniformUse;
5444 
5445   // Scan the loop for instructions which are either a) known to have only
5446   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5447   for (auto *BB : TheLoop->blocks())
5448     for (auto &I : *BB) {
5449       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
5450         switch (II->getIntrinsicID()) {
5451         case Intrinsic::sideeffect:
5452         case Intrinsic::experimental_noalias_scope_decl:
5453         case Intrinsic::assume:
5454         case Intrinsic::lifetime_start:
5455         case Intrinsic::lifetime_end:
5456           if (TheLoop->hasLoopInvariantOperands(&I))
5457             addToWorklistIfAllowed(&I);
5458           break;
5459         default:
5460           break;
5461         }
5462       }
5463 
5464       // ExtractValue instructions must be uniform, because the operands are
5465       // known to be loop-invariant.
5466       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
5467         assert(isOutOfScope(EVI->getAggregateOperand()) &&
5468                "Expected aggregate value to be loop invariant");
5469         addToWorklistIfAllowed(EVI);
5470         continue;
5471       }
5472 
5473       // If there's no pointer operand, there's nothing to do.
5474       auto *Ptr = getLoadStorePointerOperand(&I);
5475       if (!Ptr)
5476         continue;
5477 
5478       // A uniform memory op is itself uniform.  We exclude uniform stores
5479       // here as they demand the last lane, not the first one.
5480       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5481         addToWorklistIfAllowed(&I);
5482 
5483       if (isUniformDecision(&I, VF)) {
5484         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5485         HasUniformUse.insert(Ptr);
5486       }
5487     }
5488 
5489   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5490   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5491   // disallows uses outside the loop as well.
5492   for (auto *V : HasUniformUse) {
5493     if (isOutOfScope(V))
5494       continue;
5495     auto *I = cast<Instruction>(V);
5496     auto UsersAreMemAccesses =
5497       llvm::all_of(I->users(), [&](User *U) -> bool {
5498         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5499       });
5500     if (UsersAreMemAccesses)
5501       addToWorklistIfAllowed(I);
5502   }
5503 
5504   // Expand Worklist in topological order: whenever a new instruction
5505   // is added , its users should be already inside Worklist.  It ensures
5506   // a uniform instruction will only be used by uniform instructions.
5507   unsigned idx = 0;
5508   while (idx != Worklist.size()) {
5509     Instruction *I = Worklist[idx++];
5510 
5511     for (auto OV : I->operand_values()) {
5512       // isOutOfScope operands cannot be uniform instructions.
5513       if (isOutOfScope(OV))
5514         continue;
5515       // First order recurrence Phi's should typically be considered
5516       // non-uniform.
5517       auto *OP = dyn_cast<PHINode>(OV);
5518       if (OP && Legal->isFirstOrderRecurrence(OP))
5519         continue;
5520       // If all the users of the operand are uniform, then add the
5521       // operand into the uniform worklist.
5522       auto *OI = cast<Instruction>(OV);
5523       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5524             auto *J = cast<Instruction>(U);
5525             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5526           }))
5527         addToWorklistIfAllowed(OI);
5528     }
5529   }
5530 
5531   // For an instruction to be added into Worklist above, all its users inside
5532   // the loop should also be in Worklist. However, this condition cannot be
5533   // true for phi nodes that form a cyclic dependence. We must process phi
5534   // nodes separately. An induction variable will remain uniform if all users
5535   // of the induction variable and induction variable update remain uniform.
5536   // The code below handles both pointer and non-pointer induction variables.
5537   for (auto &Induction : Legal->getInductionVars()) {
5538     auto *Ind = Induction.first;
5539     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5540 
5541     // Determine if all users of the induction variable are uniform after
5542     // vectorization.
5543     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5544       auto *I = cast<Instruction>(U);
5545       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5546              isVectorizedMemAccessUse(I, Ind);
5547     });
5548     if (!UniformInd)
5549       continue;
5550 
5551     // Determine if all users of the induction variable update instruction are
5552     // uniform after vectorization.
5553     auto UniformIndUpdate =
5554         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5555           auto *I = cast<Instruction>(U);
5556           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5557                  isVectorizedMemAccessUse(I, IndUpdate);
5558         });
5559     if (!UniformIndUpdate)
5560       continue;
5561 
5562     // The induction variable and its update instruction will remain uniform.
5563     addToWorklistIfAllowed(Ind);
5564     addToWorklistIfAllowed(IndUpdate);
5565   }
5566 
5567   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5568 }
5569 
5570 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5571   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5572 
5573   if (Legal->getRuntimePointerChecking()->Need) {
5574     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5575         "runtime pointer checks needed. Enable vectorization of this "
5576         "loop with '#pragma clang loop vectorize(enable)' when "
5577         "compiling with -Os/-Oz",
5578         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5579     return true;
5580   }
5581 
5582   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5583     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5584         "runtime SCEV checks needed. Enable vectorization of this "
5585         "loop with '#pragma clang loop vectorize(enable)' when "
5586         "compiling with -Os/-Oz",
5587         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5588     return true;
5589   }
5590 
5591   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5592   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5593     reportVectorizationFailure("Runtime stride check for small trip count",
5594         "runtime stride == 1 checks needed. Enable vectorization of "
5595         "this loop without such check by compiling with -Os/-Oz",
5596         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5597     return true;
5598   }
5599 
5600   return false;
5601 }
5602 
5603 ElementCount
5604 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5605   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
5606     return ElementCount::getScalable(0);
5607 
5608   if (Hints->isScalableVectorizationDisabled()) {
5609     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5610                             "ScalableVectorizationDisabled", ORE, TheLoop);
5611     return ElementCount::getScalable(0);
5612   }
5613 
5614   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
5615 
5616   auto MaxScalableVF = ElementCount::getScalable(
5617       std::numeric_limits<ElementCount::ScalarTy>::max());
5618 
5619   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5620   // FIXME: While for scalable vectors this is currently sufficient, this should
5621   // be replaced by a more detailed mechanism that filters out specific VFs,
5622   // instead of invalidating vectorization for a whole set of VFs based on the
5623   // MaxVF.
5624 
5625   // Disable scalable vectorization if the loop contains unsupported reductions.
5626   if (!canVectorizeReductions(MaxScalableVF)) {
5627     reportVectorizationInfo(
5628         "Scalable vectorization not supported for the reduction "
5629         "operations found in this loop.",
5630         "ScalableVFUnfeasible", ORE, TheLoop);
5631     return ElementCount::getScalable(0);
5632   }
5633 
5634   // Disable scalable vectorization if the loop contains any instructions
5635   // with element types not supported for scalable vectors.
5636   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5637         return !Ty->isVoidTy() &&
5638                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5639       })) {
5640     reportVectorizationInfo("Scalable vectorization is not supported "
5641                             "for all element types found in this loop.",
5642                             "ScalableVFUnfeasible", ORE, TheLoop);
5643     return ElementCount::getScalable(0);
5644   }
5645 
5646   if (Legal->isSafeForAnyVectorWidth())
5647     return MaxScalableVF;
5648 
5649   // Limit MaxScalableVF by the maximum safe dependence distance.
5650   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5651   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5652     unsigned VScaleMax = TheFunction->getFnAttribute(Attribute::VScaleRange)
5653                              .getVScaleRangeArgs()
5654                              .second;
5655     if (VScaleMax > 0)
5656       MaxVScale = VScaleMax;
5657   }
5658   MaxScalableVF = ElementCount::getScalable(
5659       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5660   if (!MaxScalableVF)
5661     reportVectorizationInfo(
5662         "Max legal vector width too small, scalable vectorization "
5663         "unfeasible.",
5664         "ScalableVFUnfeasible", ORE, TheLoop);
5665 
5666   return MaxScalableVF;
5667 }
5668 
5669 FixedScalableVFPair
5670 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5671                                                  ElementCount UserVF) {
5672   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5673   unsigned SmallestType, WidestType;
5674   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5675 
5676   // Get the maximum safe dependence distance in bits computed by LAA.
5677   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5678   // the memory accesses that is most restrictive (involved in the smallest
5679   // dependence distance).
5680   unsigned MaxSafeElements =
5681       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5682 
5683   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5684   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5685 
5686   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5687                     << ".\n");
5688   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5689                     << ".\n");
5690 
5691   // First analyze the UserVF, fall back if the UserVF should be ignored.
5692   if (UserVF) {
5693     auto MaxSafeUserVF =
5694         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5695 
5696     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
5697       // If `VF=vscale x N` is safe, then so is `VF=N`
5698       if (UserVF.isScalable())
5699         return FixedScalableVFPair(
5700             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
5701       else
5702         return UserVF;
5703     }
5704 
5705     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5706 
5707     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5708     // is better to ignore the hint and let the compiler choose a suitable VF.
5709     if (!UserVF.isScalable()) {
5710       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5711                         << " is unsafe, clamping to max safe VF="
5712                         << MaxSafeFixedVF << ".\n");
5713       ORE->emit([&]() {
5714         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5715                                           TheLoop->getStartLoc(),
5716                                           TheLoop->getHeader())
5717                << "User-specified vectorization factor "
5718                << ore::NV("UserVectorizationFactor", UserVF)
5719                << " is unsafe, clamping to maximum safe vectorization factor "
5720                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5721       });
5722       return MaxSafeFixedVF;
5723     }
5724 
5725     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5726       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5727                         << " is ignored because scalable vectors are not "
5728                            "available.\n");
5729       ORE->emit([&]() {
5730         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5731                                           TheLoop->getStartLoc(),
5732                                           TheLoop->getHeader())
5733                << "User-specified vectorization factor "
5734                << ore::NV("UserVectorizationFactor", UserVF)
5735                << " is ignored because the target does not support scalable "
5736                   "vectors. The compiler will pick a more suitable value.";
5737       });
5738     } else {
5739       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5740                         << " is unsafe. Ignoring scalable UserVF.\n");
5741       ORE->emit([&]() {
5742         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5743                                           TheLoop->getStartLoc(),
5744                                           TheLoop->getHeader())
5745                << "User-specified vectorization factor "
5746                << ore::NV("UserVectorizationFactor", UserVF)
5747                << " is unsafe. Ignoring the hint to let the compiler pick a "
5748                   "more suitable value.";
5749       });
5750     }
5751   }
5752 
5753   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5754                     << " / " << WidestType << " bits.\n");
5755 
5756   FixedScalableVFPair Result(ElementCount::getFixed(1),
5757                              ElementCount::getScalable(0));
5758   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5759                                            WidestType, MaxSafeFixedVF))
5760     Result.FixedVF = MaxVF;
5761 
5762   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5763                                            WidestType, MaxSafeScalableVF))
5764     if (MaxVF.isScalable()) {
5765       Result.ScalableVF = MaxVF;
5766       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5767                         << "\n");
5768     }
5769 
5770   return Result;
5771 }
5772 
5773 FixedScalableVFPair
5774 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5775   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5776     // TODO: It may by useful to do since it's still likely to be dynamically
5777     // uniform if the target can skip.
5778     reportVectorizationFailure(
5779         "Not inserting runtime ptr check for divergent target",
5780         "runtime pointer checks needed. Not enabled for divergent target",
5781         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5782     return FixedScalableVFPair::getNone();
5783   }
5784 
5785   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5786   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5787   if (TC == 1) {
5788     reportVectorizationFailure("Single iteration (non) loop",
5789         "loop trip count is one, irrelevant for vectorization",
5790         "SingleIterationLoop", ORE, TheLoop);
5791     return FixedScalableVFPair::getNone();
5792   }
5793 
5794   switch (ScalarEpilogueStatus) {
5795   case CM_ScalarEpilogueAllowed:
5796     return computeFeasibleMaxVF(TC, UserVF);
5797   case CM_ScalarEpilogueNotAllowedUsePredicate:
5798     LLVM_FALLTHROUGH;
5799   case CM_ScalarEpilogueNotNeededUsePredicate:
5800     LLVM_DEBUG(
5801         dbgs() << "LV: vector predicate hint/switch found.\n"
5802                << "LV: Not allowing scalar epilogue, creating predicated "
5803                << "vector loop.\n");
5804     break;
5805   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5806     // fallthrough as a special case of OptForSize
5807   case CM_ScalarEpilogueNotAllowedOptSize:
5808     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5809       LLVM_DEBUG(
5810           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5811     else
5812       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5813                         << "count.\n");
5814 
5815     // Bail if runtime checks are required, which are not good when optimising
5816     // for size.
5817     if (runtimeChecksRequired())
5818       return FixedScalableVFPair::getNone();
5819 
5820     break;
5821   }
5822 
5823   // The only loops we can vectorize without a scalar epilogue, are loops with
5824   // a bottom-test and a single exiting block. We'd have to handle the fact
5825   // that not every instruction executes on the last iteration.  This will
5826   // require a lane mask which varies through the vector loop body.  (TODO)
5827   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5828     // If there was a tail-folding hint/switch, but we can't fold the tail by
5829     // masking, fallback to a vectorization with a scalar epilogue.
5830     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5831       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5832                            "scalar epilogue instead.\n");
5833       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5834       return computeFeasibleMaxVF(TC, UserVF);
5835     }
5836     return FixedScalableVFPair::getNone();
5837   }
5838 
5839   // Now try the tail folding
5840 
5841   // Invalidate interleave groups that require an epilogue if we can't mask
5842   // the interleave-group.
5843   if (!useMaskedInterleavedAccesses(TTI)) {
5844     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5845            "No decisions should have been taken at this point");
5846     // Note: There is no need to invalidate any cost modeling decisions here, as
5847     // non where taken so far.
5848     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5849   }
5850 
5851   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5852   // Avoid tail folding if the trip count is known to be a multiple of any VF
5853   // we chose.
5854   // FIXME: The condition below pessimises the case for fixed-width vectors,
5855   // when scalable VFs are also candidates for vectorization.
5856   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5857     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5858     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5859            "MaxFixedVF must be a power of 2");
5860     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5861                                    : MaxFixedVF.getFixedValue();
5862     ScalarEvolution *SE = PSE.getSE();
5863     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5864     const SCEV *ExitCount = SE->getAddExpr(
5865         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5866     const SCEV *Rem = SE->getURemExpr(
5867         SE->applyLoopGuards(ExitCount, TheLoop),
5868         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5869     if (Rem->isZero()) {
5870       // Accept MaxFixedVF if we do not have a tail.
5871       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5872       return MaxFactors;
5873     }
5874   }
5875 
5876   // For scalable vectors, don't use tail folding as this is currently not yet
5877   // supported. The code is likely to have ended up here if the tripcount is
5878   // low, in which case it makes sense not to use scalable vectors.
5879   if (MaxFactors.ScalableVF.isVector())
5880     MaxFactors.ScalableVF = ElementCount::getScalable(0);
5881 
5882   // If we don't know the precise trip count, or if the trip count that we
5883   // found modulo the vectorization factor is not zero, try to fold the tail
5884   // by masking.
5885   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5886   if (Legal->prepareToFoldTailByMasking()) {
5887     FoldTailByMasking = true;
5888     return MaxFactors;
5889   }
5890 
5891   // If there was a tail-folding hint/switch, but we can't fold the tail by
5892   // masking, fallback to a vectorization with a scalar epilogue.
5893   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5894     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5895                          "scalar epilogue instead.\n");
5896     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5897     return MaxFactors;
5898   }
5899 
5900   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5901     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5902     return FixedScalableVFPair::getNone();
5903   }
5904 
5905   if (TC == 0) {
5906     reportVectorizationFailure(
5907         "Unable to calculate the loop count due to complex control flow",
5908         "unable to calculate the loop count due to complex control flow",
5909         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5910     return FixedScalableVFPair::getNone();
5911   }
5912 
5913   reportVectorizationFailure(
5914       "Cannot optimize for size and vectorize at the same time.",
5915       "cannot optimize for size and vectorize at the same time. "
5916       "Enable vectorization of this loop with '#pragma clang loop "
5917       "vectorize(enable)' when compiling with -Os/-Oz",
5918       "NoTailLoopWithOptForSize", ORE, TheLoop);
5919   return FixedScalableVFPair::getNone();
5920 }
5921 
5922 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5923     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5924     const ElementCount &MaxSafeVF) {
5925   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5926   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5927       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5928                            : TargetTransformInfo::RGK_FixedWidthVector);
5929 
5930   // Convenience function to return the minimum of two ElementCounts.
5931   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5932     assert((LHS.isScalable() == RHS.isScalable()) &&
5933            "Scalable flags must match");
5934     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5935   };
5936 
5937   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5938   // Note that both WidestRegister and WidestType may not be a powers of 2.
5939   auto MaxVectorElementCount = ElementCount::get(
5940       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5941       ComputeScalableMaxVF);
5942   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5943   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5944                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5945 
5946   if (!MaxVectorElementCount) {
5947     LLVM_DEBUG(dbgs() << "LV: The target has no "
5948                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5949                       << " vector registers.\n");
5950     return ElementCount::getFixed(1);
5951   }
5952 
5953   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5954   if (ConstTripCount &&
5955       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5956       isPowerOf2_32(ConstTripCount)) {
5957     // We need to clamp the VF to be the ConstTripCount. There is no point in
5958     // choosing a higher viable VF as done in the loop below. If
5959     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5960     // the TC is less than or equal to the known number of lanes.
5961     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5962                       << ConstTripCount << "\n");
5963     return TripCountEC;
5964   }
5965 
5966   ElementCount MaxVF = MaxVectorElementCount;
5967   if (TTI.shouldMaximizeVectorBandwidth() ||
5968       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5969     auto MaxVectorElementCountMaxBW = ElementCount::get(
5970         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5971         ComputeScalableMaxVF);
5972     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5973 
5974     // Collect all viable vectorization factors larger than the default MaxVF
5975     // (i.e. MaxVectorElementCount).
5976     SmallVector<ElementCount, 8> VFs;
5977     for (ElementCount VS = MaxVectorElementCount * 2;
5978          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5979       VFs.push_back(VS);
5980 
5981     // For each VF calculate its register usage.
5982     auto RUs = calculateRegisterUsage(VFs);
5983 
5984     // Select the largest VF which doesn't require more registers than existing
5985     // ones.
5986     for (int i = RUs.size() - 1; i >= 0; --i) {
5987       bool Selected = true;
5988       for (auto &pair : RUs[i].MaxLocalUsers) {
5989         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5990         if (pair.second > TargetNumRegisters)
5991           Selected = false;
5992       }
5993       if (Selected) {
5994         MaxVF = VFs[i];
5995         break;
5996       }
5997     }
5998     if (ElementCount MinVF =
5999             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
6000       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
6001         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
6002                           << ") with target's minimum: " << MinVF << '\n');
6003         MaxVF = MinVF;
6004       }
6005     }
6006   }
6007   return MaxVF;
6008 }
6009 
6010 bool LoopVectorizationCostModel::isMoreProfitable(
6011     const VectorizationFactor &A, const VectorizationFactor &B) const {
6012   InstructionCost CostA = A.Cost;
6013   InstructionCost CostB = B.Cost;
6014 
6015   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
6016 
6017   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
6018       MaxTripCount) {
6019     // If we are folding the tail and the trip count is a known (possibly small)
6020     // constant, the trip count will be rounded up to an integer number of
6021     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
6022     // which we compare directly. When not folding the tail, the total cost will
6023     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
6024     // approximated with the per-lane cost below instead of using the tripcount
6025     // as here.
6026     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
6027     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
6028     return RTCostA < RTCostB;
6029   }
6030 
6031   // When set to preferred, for now assume vscale may be larger than 1, so
6032   // that scalable vectorization is slightly favorable over fixed-width
6033   // vectorization.
6034   if (Hints->isScalableVectorizationPreferred())
6035     if (A.Width.isScalable() && !B.Width.isScalable())
6036       return (CostA * B.Width.getKnownMinValue()) <=
6037              (CostB * A.Width.getKnownMinValue());
6038 
6039   // To avoid the need for FP division:
6040   //      (CostA / A.Width) < (CostB / B.Width)
6041   // <=>  (CostA * B.Width) < (CostB * A.Width)
6042   return (CostA * B.Width.getKnownMinValue()) <
6043          (CostB * A.Width.getKnownMinValue());
6044 }
6045 
6046 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
6047     const ElementCountSet &VFCandidates) {
6048   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
6049   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
6050   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
6051   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
6052          "Expected Scalar VF to be a candidate");
6053 
6054   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
6055   VectorizationFactor ChosenFactor = ScalarCost;
6056 
6057   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6058   if (ForceVectorization && VFCandidates.size() > 1) {
6059     // Ignore scalar width, because the user explicitly wants vectorization.
6060     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6061     // evaluation.
6062     ChosenFactor.Cost = InstructionCost::getMax();
6063   }
6064 
6065   SmallVector<InstructionVFPair> InvalidCosts;
6066   for (const auto &i : VFCandidates) {
6067     // The cost for scalar VF=1 is already calculated, so ignore it.
6068     if (i.isScalar())
6069       continue;
6070 
6071     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
6072     VectorizationFactor Candidate(i, C.first);
6073     LLVM_DEBUG(
6074         dbgs() << "LV: Vector loop of width " << i << " costs: "
6075                << (Candidate.Cost / Candidate.Width.getKnownMinValue())
6076                << (i.isScalable() ? " (assuming a minimum vscale of 1)" : "")
6077                << ".\n");
6078 
6079     if (!C.second && !ForceVectorization) {
6080       LLVM_DEBUG(
6081           dbgs() << "LV: Not considering vector loop of width " << i
6082                  << " because it will not generate any vector instructions.\n");
6083       continue;
6084     }
6085 
6086     // If profitable add it to ProfitableVF list.
6087     if (isMoreProfitable(Candidate, ScalarCost))
6088       ProfitableVFs.push_back(Candidate);
6089 
6090     if (isMoreProfitable(Candidate, ChosenFactor))
6091       ChosenFactor = Candidate;
6092   }
6093 
6094   // Emit a report of VFs with invalid costs in the loop.
6095   if (!InvalidCosts.empty()) {
6096     // Group the remarks per instruction, keeping the instruction order from
6097     // InvalidCosts.
6098     std::map<Instruction *, unsigned> Numbering;
6099     unsigned I = 0;
6100     for (auto &Pair : InvalidCosts)
6101       if (!Numbering.count(Pair.first))
6102         Numbering[Pair.first] = I++;
6103 
6104     // Sort the list, first on instruction(number) then on VF.
6105     llvm::sort(InvalidCosts,
6106                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
6107                  if (Numbering[A.first] != Numbering[B.first])
6108                    return Numbering[A.first] < Numbering[B.first];
6109                  ElementCountComparator ECC;
6110                  return ECC(A.second, B.second);
6111                });
6112 
6113     // For a list of ordered instruction-vf pairs:
6114     //   [(load, vf1), (load, vf2), (store, vf1)]
6115     // Group the instructions together to emit separate remarks for:
6116     //   load  (vf1, vf2)
6117     //   store (vf1)
6118     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
6119     auto Subset = ArrayRef<InstructionVFPair>();
6120     do {
6121       if (Subset.empty())
6122         Subset = Tail.take_front(1);
6123 
6124       Instruction *I = Subset.front().first;
6125 
6126       // If the next instruction is different, or if there are no other pairs,
6127       // emit a remark for the collated subset. e.g.
6128       //   [(load, vf1), (load, vf2))]
6129       // to emit:
6130       //  remark: invalid costs for 'load' at VF=(vf, vf2)
6131       if (Subset == Tail || Tail[Subset.size()].first != I) {
6132         std::string OutString;
6133         raw_string_ostream OS(OutString);
6134         assert(!Subset.empty() && "Unexpected empty range");
6135         OS << "Instruction with invalid costs prevented vectorization at VF=(";
6136         for (auto &Pair : Subset)
6137           OS << (Pair.second == Subset.front().second ? "" : ", ")
6138              << Pair.second;
6139         OS << "):";
6140         if (auto *CI = dyn_cast<CallInst>(I))
6141           OS << " call to " << CI->getCalledFunction()->getName();
6142         else
6143           OS << " " << I->getOpcodeName();
6144         OS.flush();
6145         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
6146         Tail = Tail.drop_front(Subset.size());
6147         Subset = {};
6148       } else
6149         // Grow the subset by one element
6150         Subset = Tail.take_front(Subset.size() + 1);
6151     } while (!Tail.empty());
6152   }
6153 
6154   if (!EnableCondStoresVectorization && NumPredStores) {
6155     reportVectorizationFailure("There are conditional stores.",
6156         "store that is conditionally executed prevents vectorization",
6157         "ConditionalStore", ORE, TheLoop);
6158     ChosenFactor = ScalarCost;
6159   }
6160 
6161   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6162                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
6163              << "LV: Vectorization seems to be not beneficial, "
6164              << "but was forced by a user.\n");
6165   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6166   return ChosenFactor;
6167 }
6168 
6169 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6170     const Loop &L, ElementCount VF) const {
6171   // Cross iteration phis such as reductions need special handling and are
6172   // currently unsupported.
6173   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6174         return Legal->isFirstOrderRecurrence(&Phi) ||
6175                Legal->isReductionVariable(&Phi);
6176       }))
6177     return false;
6178 
6179   // Phis with uses outside of the loop require special handling and are
6180   // currently unsupported.
6181   for (auto &Entry : Legal->getInductionVars()) {
6182     // Look for uses of the value of the induction at the last iteration.
6183     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6184     for (User *U : PostInc->users())
6185       if (!L.contains(cast<Instruction>(U)))
6186         return false;
6187     // Look for uses of penultimate value of the induction.
6188     for (User *U : Entry.first->users())
6189       if (!L.contains(cast<Instruction>(U)))
6190         return false;
6191   }
6192 
6193   // Induction variables that are widened require special handling that is
6194   // currently not supported.
6195   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6196         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6197                  this->isProfitableToScalarize(Entry.first, VF));
6198       }))
6199     return false;
6200 
6201   // Epilogue vectorization code has not been auditted to ensure it handles
6202   // non-latch exits properly.  It may be fine, but it needs auditted and
6203   // tested.
6204   if (L.getExitingBlock() != L.getLoopLatch())
6205     return false;
6206 
6207   return true;
6208 }
6209 
6210 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6211     const ElementCount VF) const {
6212   // FIXME: We need a much better cost-model to take different parameters such
6213   // as register pressure, code size increase and cost of extra branches into
6214   // account. For now we apply a very crude heuristic and only consider loops
6215   // with vectorization factors larger than a certain value.
6216   // We also consider epilogue vectorization unprofitable for targets that don't
6217   // consider interleaving beneficial (eg. MVE).
6218   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6219     return false;
6220   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6221     return true;
6222   return false;
6223 }
6224 
6225 VectorizationFactor
6226 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6227     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6228   VectorizationFactor Result = VectorizationFactor::Disabled();
6229   if (!EnableEpilogueVectorization) {
6230     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6231     return Result;
6232   }
6233 
6234   if (!isScalarEpilogueAllowed()) {
6235     LLVM_DEBUG(
6236         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6237                   "allowed.\n";);
6238     return Result;
6239   }
6240 
6241   // FIXME: This can be fixed for scalable vectors later, because at this stage
6242   // the LoopVectorizer will only consider vectorizing a loop with scalable
6243   // vectors when the loop has a hint to enable vectorization for a given VF.
6244   if (MainLoopVF.isScalable()) {
6245     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6246                          "yet supported.\n");
6247     return Result;
6248   }
6249 
6250   // Not really a cost consideration, but check for unsupported cases here to
6251   // simplify the logic.
6252   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6253     LLVM_DEBUG(
6254         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6255                   "not a supported candidate.\n";);
6256     return Result;
6257   }
6258 
6259   if (EpilogueVectorizationForceVF > 1) {
6260     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6261     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
6262     if (LVP.hasPlanWithVFs({MainLoopVF, ForcedEC}))
6263       return {ForcedEC, 0};
6264     else {
6265       LLVM_DEBUG(
6266           dbgs()
6267               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6268       return Result;
6269     }
6270   }
6271 
6272   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6273       TheLoop->getHeader()->getParent()->hasMinSize()) {
6274     LLVM_DEBUG(
6275         dbgs()
6276             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6277     return Result;
6278   }
6279 
6280   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6281     return Result;
6282 
6283   for (auto &NextVF : ProfitableVFs)
6284     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6285         (Result.Width.getFixedValue() == 1 ||
6286          isMoreProfitable(NextVF, Result)) &&
6287         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6288       Result = NextVF;
6289 
6290   if (Result != VectorizationFactor::Disabled())
6291     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6292                       << Result.Width.getFixedValue() << "\n";);
6293   return Result;
6294 }
6295 
6296 std::pair<unsigned, unsigned>
6297 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6298   unsigned MinWidth = -1U;
6299   unsigned MaxWidth = 8;
6300   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6301   for (Type *T : ElementTypesInLoop) {
6302     MinWidth = std::min<unsigned>(
6303         MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6304     MaxWidth = std::max<unsigned>(
6305         MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6306   }
6307   return {MinWidth, MaxWidth};
6308 }
6309 
6310 void LoopVectorizationCostModel::collectElementTypesForWidening() {
6311   ElementTypesInLoop.clear();
6312   // For each block.
6313   for (BasicBlock *BB : TheLoop->blocks()) {
6314     // For each instruction in the loop.
6315     for (Instruction &I : BB->instructionsWithoutDebug()) {
6316       Type *T = I.getType();
6317 
6318       // Skip ignored values.
6319       if (ValuesToIgnore.count(&I))
6320         continue;
6321 
6322       // Only examine Loads, Stores and PHINodes.
6323       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6324         continue;
6325 
6326       // Examine PHI nodes that are reduction variables. Update the type to
6327       // account for the recurrence type.
6328       if (auto *PN = dyn_cast<PHINode>(&I)) {
6329         if (!Legal->isReductionVariable(PN))
6330           continue;
6331         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6332         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6333             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6334                                       RdxDesc.getRecurrenceType(),
6335                                       TargetTransformInfo::ReductionFlags()))
6336           continue;
6337         T = RdxDesc.getRecurrenceType();
6338       }
6339 
6340       // Examine the stored values.
6341       if (auto *ST = dyn_cast<StoreInst>(&I))
6342         T = ST->getValueOperand()->getType();
6343 
6344       // Ignore loaded pointer types and stored pointer types that are not
6345       // vectorizable.
6346       //
6347       // FIXME: The check here attempts to predict whether a load or store will
6348       //        be vectorized. We only know this for certain after a VF has
6349       //        been selected. Here, we assume that if an access can be
6350       //        vectorized, it will be. We should also look at extending this
6351       //        optimization to non-pointer types.
6352       //
6353       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6354           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6355         continue;
6356 
6357       ElementTypesInLoop.insert(T);
6358     }
6359   }
6360 }
6361 
6362 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6363                                                            unsigned LoopCost) {
6364   // -- The interleave heuristics --
6365   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6366   // There are many micro-architectural considerations that we can't predict
6367   // at this level. For example, frontend pressure (on decode or fetch) due to
6368   // code size, or the number and capabilities of the execution ports.
6369   //
6370   // We use the following heuristics to select the interleave count:
6371   // 1. If the code has reductions, then we interleave to break the cross
6372   // iteration dependency.
6373   // 2. If the loop is really small, then we interleave to reduce the loop
6374   // overhead.
6375   // 3. We don't interleave if we think that we will spill registers to memory
6376   // due to the increased register pressure.
6377 
6378   if (!isScalarEpilogueAllowed())
6379     return 1;
6380 
6381   // We used the distance for the interleave count.
6382   if (Legal->getMaxSafeDepDistBytes() != -1U)
6383     return 1;
6384 
6385   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6386   const bool HasReductions = !Legal->getReductionVars().empty();
6387   // Do not interleave loops with a relatively small known or estimated trip
6388   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6389   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6390   // because with the above conditions interleaving can expose ILP and break
6391   // cross iteration dependences for reductions.
6392   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6393       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6394     return 1;
6395 
6396   RegisterUsage R = calculateRegisterUsage({VF})[0];
6397   // We divide by these constants so assume that we have at least one
6398   // instruction that uses at least one register.
6399   for (auto& pair : R.MaxLocalUsers) {
6400     pair.second = std::max(pair.second, 1U);
6401   }
6402 
6403   // We calculate the interleave count using the following formula.
6404   // Subtract the number of loop invariants from the number of available
6405   // registers. These registers are used by all of the interleaved instances.
6406   // Next, divide the remaining registers by the number of registers that is
6407   // required by the loop, in order to estimate how many parallel instances
6408   // fit without causing spills. All of this is rounded down if necessary to be
6409   // a power of two. We want power of two interleave count to simplify any
6410   // addressing operations or alignment considerations.
6411   // We also want power of two interleave counts to ensure that the induction
6412   // variable of the vector loop wraps to zero, when tail is folded by masking;
6413   // this currently happens when OptForSize, in which case IC is set to 1 above.
6414   unsigned IC = UINT_MAX;
6415 
6416   for (auto& pair : R.MaxLocalUsers) {
6417     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6418     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6419                       << " registers of "
6420                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6421     if (VF.isScalar()) {
6422       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6423         TargetNumRegisters = ForceTargetNumScalarRegs;
6424     } else {
6425       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6426         TargetNumRegisters = ForceTargetNumVectorRegs;
6427     }
6428     unsigned MaxLocalUsers = pair.second;
6429     unsigned LoopInvariantRegs = 0;
6430     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6431       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6432 
6433     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6434     // Don't count the induction variable as interleaved.
6435     if (EnableIndVarRegisterHeur) {
6436       TmpIC =
6437           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6438                         std::max(1U, (MaxLocalUsers - 1)));
6439     }
6440 
6441     IC = std::min(IC, TmpIC);
6442   }
6443 
6444   // Clamp the interleave ranges to reasonable counts.
6445   unsigned MaxInterleaveCount =
6446       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6447 
6448   // Check if the user has overridden the max.
6449   if (VF.isScalar()) {
6450     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6451       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6452   } else {
6453     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6454       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6455   }
6456 
6457   // If trip count is known or estimated compile time constant, limit the
6458   // interleave count to be less than the trip count divided by VF, provided it
6459   // is at least 1.
6460   //
6461   // For scalable vectors we can't know if interleaving is beneficial. It may
6462   // not be beneficial for small loops if none of the lanes in the second vector
6463   // iterations is enabled. However, for larger loops, there is likely to be a
6464   // similar benefit as for fixed-width vectors. For now, we choose to leave
6465   // the InterleaveCount as if vscale is '1', although if some information about
6466   // the vector is known (e.g. min vector size), we can make a better decision.
6467   if (BestKnownTC) {
6468     MaxInterleaveCount =
6469         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6470     // Make sure MaxInterleaveCount is greater than 0.
6471     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6472   }
6473 
6474   assert(MaxInterleaveCount > 0 &&
6475          "Maximum interleave count must be greater than 0");
6476 
6477   // Clamp the calculated IC to be between the 1 and the max interleave count
6478   // that the target and trip count allows.
6479   if (IC > MaxInterleaveCount)
6480     IC = MaxInterleaveCount;
6481   else
6482     // Make sure IC is greater than 0.
6483     IC = std::max(1u, IC);
6484 
6485   assert(IC > 0 && "Interleave count must be greater than 0.");
6486 
6487   // If we did not calculate the cost for VF (because the user selected the VF)
6488   // then we calculate the cost of VF here.
6489   if (LoopCost == 0) {
6490     InstructionCost C = expectedCost(VF).first;
6491     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
6492     LoopCost = *C.getValue();
6493   }
6494 
6495   assert(LoopCost && "Non-zero loop cost expected");
6496 
6497   // Interleave if we vectorized this loop and there is a reduction that could
6498   // benefit from interleaving.
6499   if (VF.isVector() && HasReductions) {
6500     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6501     return IC;
6502   }
6503 
6504   // Note that if we've already vectorized the loop we will have done the
6505   // runtime check and so interleaving won't require further checks.
6506   bool InterleavingRequiresRuntimePointerCheck =
6507       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6508 
6509   // We want to interleave small loops in order to reduce the loop overhead and
6510   // potentially expose ILP opportunities.
6511   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6512                     << "LV: IC is " << IC << '\n'
6513                     << "LV: VF is " << VF << '\n');
6514   const bool AggressivelyInterleaveReductions =
6515       TTI.enableAggressiveInterleaving(HasReductions);
6516   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6517     // We assume that the cost overhead is 1 and we use the cost model
6518     // to estimate the cost of the loop and interleave until the cost of the
6519     // loop overhead is about 5% of the cost of the loop.
6520     unsigned SmallIC =
6521         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6522 
6523     // Interleave until store/load ports (estimated by max interleave count) are
6524     // saturated.
6525     unsigned NumStores = Legal->getNumStores();
6526     unsigned NumLoads = Legal->getNumLoads();
6527     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6528     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6529 
6530     // There is little point in interleaving for reductions containing selects
6531     // and compares when VF=1 since it may just create more overhead than it's
6532     // worth for loops with small trip counts. This is because we still have to
6533     // do the final reduction after the loop.
6534     bool HasSelectCmpReductions =
6535         HasReductions &&
6536         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6537           const RecurrenceDescriptor &RdxDesc = Reduction.second;
6538           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
6539               RdxDesc.getRecurrenceKind());
6540         });
6541     if (HasSelectCmpReductions) {
6542       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
6543       return 1;
6544     }
6545 
6546     // If we have a scalar reduction (vector reductions are already dealt with
6547     // by this point), we can increase the critical path length if the loop
6548     // we're interleaving is inside another loop. For tree-wise reductions
6549     // set the limit to 2, and for ordered reductions it's best to disable
6550     // interleaving entirely.
6551     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6552       bool HasOrderedReductions =
6553           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6554             const RecurrenceDescriptor &RdxDesc = Reduction.second;
6555             return RdxDesc.isOrdered();
6556           });
6557       if (HasOrderedReductions) {
6558         LLVM_DEBUG(
6559             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
6560         return 1;
6561       }
6562 
6563       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6564       SmallIC = std::min(SmallIC, F);
6565       StoresIC = std::min(StoresIC, F);
6566       LoadsIC = std::min(LoadsIC, F);
6567     }
6568 
6569     if (EnableLoadStoreRuntimeInterleave &&
6570         std::max(StoresIC, LoadsIC) > SmallIC) {
6571       LLVM_DEBUG(
6572           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6573       return std::max(StoresIC, LoadsIC);
6574     }
6575 
6576     // If there are scalar reductions and TTI has enabled aggressive
6577     // interleaving for reductions, we will interleave to expose ILP.
6578     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6579         AggressivelyInterleaveReductions) {
6580       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6581       // Interleave no less than SmallIC but not as aggressive as the normal IC
6582       // to satisfy the rare situation when resources are too limited.
6583       return std::max(IC / 2, SmallIC);
6584     } else {
6585       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6586       return SmallIC;
6587     }
6588   }
6589 
6590   // Interleave if this is a large loop (small loops are already dealt with by
6591   // this point) that could benefit from interleaving.
6592   if (AggressivelyInterleaveReductions) {
6593     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6594     return IC;
6595   }
6596 
6597   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6598   return 1;
6599 }
6600 
6601 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6602 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6603   // This function calculates the register usage by measuring the highest number
6604   // of values that are alive at a single location. Obviously, this is a very
6605   // rough estimation. We scan the loop in a topological order in order and
6606   // assign a number to each instruction. We use RPO to ensure that defs are
6607   // met before their users. We assume that each instruction that has in-loop
6608   // users starts an interval. We record every time that an in-loop value is
6609   // used, so we have a list of the first and last occurrences of each
6610   // instruction. Next, we transpose this data structure into a multi map that
6611   // holds the list of intervals that *end* at a specific location. This multi
6612   // map allows us to perform a linear search. We scan the instructions linearly
6613   // and record each time that a new interval starts, by placing it in a set.
6614   // If we find this value in the multi-map then we remove it from the set.
6615   // The max register usage is the maximum size of the set.
6616   // We also search for instructions that are defined outside the loop, but are
6617   // used inside the loop. We need this number separately from the max-interval
6618   // usage number because when we unroll, loop-invariant values do not take
6619   // more register.
6620   LoopBlocksDFS DFS(TheLoop);
6621   DFS.perform(LI);
6622 
6623   RegisterUsage RU;
6624 
6625   // Each 'key' in the map opens a new interval. The values
6626   // of the map are the index of the 'last seen' usage of the
6627   // instruction that is the key.
6628   using IntervalMap = DenseMap<Instruction *, unsigned>;
6629 
6630   // Maps instruction to its index.
6631   SmallVector<Instruction *, 64> IdxToInstr;
6632   // Marks the end of each interval.
6633   IntervalMap EndPoint;
6634   // Saves the list of instruction indices that are used in the loop.
6635   SmallPtrSet<Instruction *, 8> Ends;
6636   // Saves the list of values that are used in the loop but are
6637   // defined outside the loop, such as arguments and constants.
6638   SmallPtrSet<Value *, 8> LoopInvariants;
6639 
6640   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6641     for (Instruction &I : BB->instructionsWithoutDebug()) {
6642       IdxToInstr.push_back(&I);
6643 
6644       // Save the end location of each USE.
6645       for (Value *U : I.operands()) {
6646         auto *Instr = dyn_cast<Instruction>(U);
6647 
6648         // Ignore non-instruction values such as arguments, constants, etc.
6649         if (!Instr)
6650           continue;
6651 
6652         // If this instruction is outside the loop then record it and continue.
6653         if (!TheLoop->contains(Instr)) {
6654           LoopInvariants.insert(Instr);
6655           continue;
6656         }
6657 
6658         // Overwrite previous end points.
6659         EndPoint[Instr] = IdxToInstr.size();
6660         Ends.insert(Instr);
6661       }
6662     }
6663   }
6664 
6665   // Saves the list of intervals that end with the index in 'key'.
6666   using InstrList = SmallVector<Instruction *, 2>;
6667   DenseMap<unsigned, InstrList> TransposeEnds;
6668 
6669   // Transpose the EndPoints to a list of values that end at each index.
6670   for (auto &Interval : EndPoint)
6671     TransposeEnds[Interval.second].push_back(Interval.first);
6672 
6673   SmallPtrSet<Instruction *, 8> OpenIntervals;
6674   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6675   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6676 
6677   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6678 
6679   // A lambda that gets the register usage for the given type and VF.
6680   const auto &TTICapture = TTI;
6681   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6682     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6683       return 0;
6684     InstructionCost::CostType RegUsage =
6685         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6686     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6687            "Nonsensical values for register usage.");
6688     return RegUsage;
6689   };
6690 
6691   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6692     Instruction *I = IdxToInstr[i];
6693 
6694     // Remove all of the instructions that end at this location.
6695     InstrList &List = TransposeEnds[i];
6696     for (Instruction *ToRemove : List)
6697       OpenIntervals.erase(ToRemove);
6698 
6699     // Ignore instructions that are never used within the loop.
6700     if (!Ends.count(I))
6701       continue;
6702 
6703     // Skip ignored values.
6704     if (ValuesToIgnore.count(I))
6705       continue;
6706 
6707     // For each VF find the maximum usage of registers.
6708     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6709       // Count the number of live intervals.
6710       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6711 
6712       if (VFs[j].isScalar()) {
6713         for (auto Inst : OpenIntervals) {
6714           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6715           if (RegUsage.find(ClassID) == RegUsage.end())
6716             RegUsage[ClassID] = 1;
6717           else
6718             RegUsage[ClassID] += 1;
6719         }
6720       } else {
6721         collectUniformsAndScalars(VFs[j]);
6722         for (auto Inst : OpenIntervals) {
6723           // Skip ignored values for VF > 1.
6724           if (VecValuesToIgnore.count(Inst))
6725             continue;
6726           if (isScalarAfterVectorization(Inst, VFs[j])) {
6727             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6728             if (RegUsage.find(ClassID) == RegUsage.end())
6729               RegUsage[ClassID] = 1;
6730             else
6731               RegUsage[ClassID] += 1;
6732           } else {
6733             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6734             if (RegUsage.find(ClassID) == RegUsage.end())
6735               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6736             else
6737               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6738           }
6739         }
6740       }
6741 
6742       for (auto& pair : RegUsage) {
6743         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6744           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6745         else
6746           MaxUsages[j][pair.first] = pair.second;
6747       }
6748     }
6749 
6750     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6751                       << OpenIntervals.size() << '\n');
6752 
6753     // Add the current instruction to the list of open intervals.
6754     OpenIntervals.insert(I);
6755   }
6756 
6757   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6758     SmallMapVector<unsigned, unsigned, 4> Invariant;
6759 
6760     for (auto Inst : LoopInvariants) {
6761       unsigned Usage =
6762           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6763       unsigned ClassID =
6764           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6765       if (Invariant.find(ClassID) == Invariant.end())
6766         Invariant[ClassID] = Usage;
6767       else
6768         Invariant[ClassID] += Usage;
6769     }
6770 
6771     LLVM_DEBUG({
6772       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6773       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6774              << " item\n";
6775       for (const auto &pair : MaxUsages[i]) {
6776         dbgs() << "LV(REG): RegisterClass: "
6777                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6778                << " registers\n";
6779       }
6780       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6781              << " item\n";
6782       for (const auto &pair : Invariant) {
6783         dbgs() << "LV(REG): RegisterClass: "
6784                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6785                << " registers\n";
6786       }
6787     });
6788 
6789     RU.LoopInvariantRegs = Invariant;
6790     RU.MaxLocalUsers = MaxUsages[i];
6791     RUs[i] = RU;
6792   }
6793 
6794   return RUs;
6795 }
6796 
6797 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6798   // TODO: Cost model for emulated masked load/store is completely
6799   // broken. This hack guides the cost model to use an artificially
6800   // high enough value to practically disable vectorization with such
6801   // operations, except where previously deployed legality hack allowed
6802   // using very low cost values. This is to avoid regressions coming simply
6803   // from moving "masked load/store" check from legality to cost model.
6804   // Masked Load/Gather emulation was previously never allowed.
6805   // Limited number of Masked Store/Scatter emulation was allowed.
6806   assert(isPredicatedInst(I) &&
6807          "Expecting a scalar emulated instruction");
6808   return isa<LoadInst>(I) ||
6809          (isa<StoreInst>(I) &&
6810           NumPredStores > NumberOfStoresToPredicate);
6811 }
6812 
6813 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6814   // If we aren't vectorizing the loop, or if we've already collected the
6815   // instructions to scalarize, there's nothing to do. Collection may already
6816   // have occurred if we have a user-selected VF and are now computing the
6817   // expected cost for interleaving.
6818   if (VF.isScalar() || VF.isZero() ||
6819       InstsToScalarize.find(VF) != InstsToScalarize.end())
6820     return;
6821 
6822   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6823   // not profitable to scalarize any instructions, the presence of VF in the
6824   // map will indicate that we've analyzed it already.
6825   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6826 
6827   // Find all the instructions that are scalar with predication in the loop and
6828   // determine if it would be better to not if-convert the blocks they are in.
6829   // If so, we also record the instructions to scalarize.
6830   for (BasicBlock *BB : TheLoop->blocks()) {
6831     if (!blockNeedsPredication(BB))
6832       continue;
6833     for (Instruction &I : *BB)
6834       if (isScalarWithPredication(&I)) {
6835         ScalarCostsTy ScalarCosts;
6836         // Do not apply discount if scalable, because that would lead to
6837         // invalid scalarization costs.
6838         // Do not apply discount logic if hacked cost is needed
6839         // for emulated masked memrefs.
6840         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I) &&
6841             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6842           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6843         // Remember that BB will remain after vectorization.
6844         PredicatedBBsAfterVectorization.insert(BB);
6845       }
6846   }
6847 }
6848 
6849 int LoopVectorizationCostModel::computePredInstDiscount(
6850     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6851   assert(!isUniformAfterVectorization(PredInst, VF) &&
6852          "Instruction marked uniform-after-vectorization will be predicated");
6853 
6854   // Initialize the discount to zero, meaning that the scalar version and the
6855   // vector version cost the same.
6856   InstructionCost Discount = 0;
6857 
6858   // Holds instructions to analyze. The instructions we visit are mapped in
6859   // ScalarCosts. Those instructions are the ones that would be scalarized if
6860   // we find that the scalar version costs less.
6861   SmallVector<Instruction *, 8> Worklist;
6862 
6863   // Returns true if the given instruction can be scalarized.
6864   auto canBeScalarized = [&](Instruction *I) -> bool {
6865     // We only attempt to scalarize instructions forming a single-use chain
6866     // from the original predicated block that would otherwise be vectorized.
6867     // Although not strictly necessary, we give up on instructions we know will
6868     // already be scalar to avoid traversing chains that are unlikely to be
6869     // beneficial.
6870     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6871         isScalarAfterVectorization(I, VF))
6872       return false;
6873 
6874     // If the instruction is scalar with predication, it will be analyzed
6875     // separately. We ignore it within the context of PredInst.
6876     if (isScalarWithPredication(I))
6877       return false;
6878 
6879     // If any of the instruction's operands are uniform after vectorization,
6880     // the instruction cannot be scalarized. This prevents, for example, a
6881     // masked load from being scalarized.
6882     //
6883     // We assume we will only emit a value for lane zero of an instruction
6884     // marked uniform after vectorization, rather than VF identical values.
6885     // Thus, if we scalarize an instruction that uses a uniform, we would
6886     // create uses of values corresponding to the lanes we aren't emitting code
6887     // for. This behavior can be changed by allowing getScalarValue to clone
6888     // the lane zero values for uniforms rather than asserting.
6889     for (Use &U : I->operands())
6890       if (auto *J = dyn_cast<Instruction>(U.get()))
6891         if (isUniformAfterVectorization(J, VF))
6892           return false;
6893 
6894     // Otherwise, we can scalarize the instruction.
6895     return true;
6896   };
6897 
6898   // Compute the expected cost discount from scalarizing the entire expression
6899   // feeding the predicated instruction. We currently only consider expressions
6900   // that are single-use instruction chains.
6901   Worklist.push_back(PredInst);
6902   while (!Worklist.empty()) {
6903     Instruction *I = Worklist.pop_back_val();
6904 
6905     // If we've already analyzed the instruction, there's nothing to do.
6906     if (ScalarCosts.find(I) != ScalarCosts.end())
6907       continue;
6908 
6909     // Compute the cost of the vector instruction. Note that this cost already
6910     // includes the scalarization overhead of the predicated instruction.
6911     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6912 
6913     // Compute the cost of the scalarized instruction. This cost is the cost of
6914     // the instruction as if it wasn't if-converted and instead remained in the
6915     // predicated block. We will scale this cost by block probability after
6916     // computing the scalarization overhead.
6917     InstructionCost ScalarCost =
6918         VF.getFixedValue() *
6919         getInstructionCost(I, ElementCount::getFixed(1)).first;
6920 
6921     // Compute the scalarization overhead of needed insertelement instructions
6922     // and phi nodes.
6923     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6924       ScalarCost += TTI.getScalarizationOverhead(
6925           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6926           APInt::getAllOnes(VF.getFixedValue()), true, false);
6927       ScalarCost +=
6928           VF.getFixedValue() *
6929           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6930     }
6931 
6932     // Compute the scalarization overhead of needed extractelement
6933     // instructions. For each of the instruction's operands, if the operand can
6934     // be scalarized, add it to the worklist; otherwise, account for the
6935     // overhead.
6936     for (Use &U : I->operands())
6937       if (auto *J = dyn_cast<Instruction>(U.get())) {
6938         assert(VectorType::isValidElementType(J->getType()) &&
6939                "Instruction has non-scalar type");
6940         if (canBeScalarized(J))
6941           Worklist.push_back(J);
6942         else if (needsExtract(J, VF)) {
6943           ScalarCost += TTI.getScalarizationOverhead(
6944               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6945               APInt::getAllOnes(VF.getFixedValue()), false, true);
6946         }
6947       }
6948 
6949     // Scale the total scalar cost by block probability.
6950     ScalarCost /= getReciprocalPredBlockProb();
6951 
6952     // Compute the discount. A non-negative discount means the vector version
6953     // of the instruction costs more, and scalarizing would be beneficial.
6954     Discount += VectorCost - ScalarCost;
6955     ScalarCosts[I] = ScalarCost;
6956   }
6957 
6958   return *Discount.getValue();
6959 }
6960 
6961 LoopVectorizationCostModel::VectorizationCostTy
6962 LoopVectorizationCostModel::expectedCost(
6963     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6964   VectorizationCostTy Cost;
6965 
6966   // For each block.
6967   for (BasicBlock *BB : TheLoop->blocks()) {
6968     VectorizationCostTy BlockCost;
6969 
6970     // For each instruction in the old loop.
6971     for (Instruction &I : BB->instructionsWithoutDebug()) {
6972       // Skip ignored values.
6973       if (ValuesToIgnore.count(&I) ||
6974           (VF.isVector() && VecValuesToIgnore.count(&I)))
6975         continue;
6976 
6977       VectorizationCostTy C = getInstructionCost(&I, VF);
6978 
6979       // Check if we should override the cost.
6980       if (C.first.isValid() &&
6981           ForceTargetInstructionCost.getNumOccurrences() > 0)
6982         C.first = InstructionCost(ForceTargetInstructionCost);
6983 
6984       // Keep a list of instructions with invalid costs.
6985       if (Invalid && !C.first.isValid())
6986         Invalid->emplace_back(&I, VF);
6987 
6988       BlockCost.first += C.first;
6989       BlockCost.second |= C.second;
6990       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6991                         << " for VF " << VF << " For instruction: " << I
6992                         << '\n');
6993     }
6994 
6995     // If we are vectorizing a predicated block, it will have been
6996     // if-converted. This means that the block's instructions (aside from
6997     // stores and instructions that may divide by zero) will now be
6998     // unconditionally executed. For the scalar case, we may not always execute
6999     // the predicated block, if it is an if-else block. Thus, scale the block's
7000     // cost by the probability of executing it. blockNeedsPredication from
7001     // Legal is used so as to not include all blocks in tail folded loops.
7002     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
7003       BlockCost.first /= getReciprocalPredBlockProb();
7004 
7005     Cost.first += BlockCost.first;
7006     Cost.second |= BlockCost.second;
7007   }
7008 
7009   return Cost;
7010 }
7011 
7012 /// Gets Address Access SCEV after verifying that the access pattern
7013 /// is loop invariant except the induction variable dependence.
7014 ///
7015 /// This SCEV can be sent to the Target in order to estimate the address
7016 /// calculation cost.
7017 static const SCEV *getAddressAccessSCEV(
7018               Value *Ptr,
7019               LoopVectorizationLegality *Legal,
7020               PredicatedScalarEvolution &PSE,
7021               const Loop *TheLoop) {
7022 
7023   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
7024   if (!Gep)
7025     return nullptr;
7026 
7027   // We are looking for a gep with all loop invariant indices except for one
7028   // which should be an induction variable.
7029   auto SE = PSE.getSE();
7030   unsigned NumOperands = Gep->getNumOperands();
7031   for (unsigned i = 1; i < NumOperands; ++i) {
7032     Value *Opd = Gep->getOperand(i);
7033     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
7034         !Legal->isInductionVariable(Opd))
7035       return nullptr;
7036   }
7037 
7038   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
7039   return PSE.getSCEV(Ptr);
7040 }
7041 
7042 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
7043   return Legal->hasStride(I->getOperand(0)) ||
7044          Legal->hasStride(I->getOperand(1));
7045 }
7046 
7047 InstructionCost
7048 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
7049                                                         ElementCount VF) {
7050   assert(VF.isVector() &&
7051          "Scalarization cost of instruction implies vectorization.");
7052   if (VF.isScalable())
7053     return InstructionCost::getInvalid();
7054 
7055   Type *ValTy = getLoadStoreType(I);
7056   auto SE = PSE.getSE();
7057 
7058   unsigned AS = getLoadStoreAddressSpace(I);
7059   Value *Ptr = getLoadStorePointerOperand(I);
7060   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
7061 
7062   // Figure out whether the access is strided and get the stride value
7063   // if it's known in compile time
7064   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
7065 
7066   // Get the cost of the scalar memory instruction and address computation.
7067   InstructionCost Cost =
7068       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
7069 
7070   // Don't pass *I here, since it is scalar but will actually be part of a
7071   // vectorized loop where the user of it is a vectorized instruction.
7072   const Align Alignment = getLoadStoreAlignment(I);
7073   Cost += VF.getKnownMinValue() *
7074           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
7075                               AS, TTI::TCK_RecipThroughput);
7076 
7077   // Get the overhead of the extractelement and insertelement instructions
7078   // we might create due to scalarization.
7079   Cost += getScalarizationOverhead(I, VF);
7080 
7081   // If we have a predicated load/store, it will need extra i1 extracts and
7082   // conditional branches, but may not be executed for each vector lane. Scale
7083   // the cost by the probability of executing the predicated block.
7084   if (isPredicatedInst(I)) {
7085     Cost /= getReciprocalPredBlockProb();
7086 
7087     // Add the cost of an i1 extract and a branch
7088     auto *Vec_i1Ty =
7089         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
7090     Cost += TTI.getScalarizationOverhead(
7091         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
7092         /*Insert=*/false, /*Extract=*/true);
7093     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
7094 
7095     if (useEmulatedMaskMemRefHack(I))
7096       // Artificially setting to a high enough value to practically disable
7097       // vectorization with such operations.
7098       Cost = 3000000;
7099   }
7100 
7101   return Cost;
7102 }
7103 
7104 InstructionCost
7105 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7106                                                     ElementCount VF) {
7107   Type *ValTy = getLoadStoreType(I);
7108   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7109   Value *Ptr = getLoadStorePointerOperand(I);
7110   unsigned AS = getLoadStoreAddressSpace(I);
7111   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
7112   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7113 
7114   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7115          "Stride should be 1 or -1 for consecutive memory access");
7116   const Align Alignment = getLoadStoreAlignment(I);
7117   InstructionCost Cost = 0;
7118   if (Legal->isMaskRequired(I))
7119     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7120                                       CostKind);
7121   else
7122     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7123                                 CostKind, I);
7124 
7125   bool Reverse = ConsecutiveStride < 0;
7126   if (Reverse)
7127     Cost +=
7128         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7129   return Cost;
7130 }
7131 
7132 InstructionCost
7133 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7134                                                 ElementCount VF) {
7135   assert(Legal->isUniformMemOp(*I));
7136 
7137   Type *ValTy = getLoadStoreType(I);
7138   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7139   const Align Alignment = getLoadStoreAlignment(I);
7140   unsigned AS = getLoadStoreAddressSpace(I);
7141   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7142   if (isa<LoadInst>(I)) {
7143     return TTI.getAddressComputationCost(ValTy) +
7144            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7145                                CostKind) +
7146            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7147   }
7148   StoreInst *SI = cast<StoreInst>(I);
7149 
7150   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7151   return TTI.getAddressComputationCost(ValTy) +
7152          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7153                              CostKind) +
7154          (isLoopInvariantStoreValue
7155               ? 0
7156               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7157                                        VF.getKnownMinValue() - 1));
7158 }
7159 
7160 InstructionCost
7161 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7162                                                  ElementCount VF) {
7163   Type *ValTy = getLoadStoreType(I);
7164   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7165   const Align Alignment = getLoadStoreAlignment(I);
7166   const Value *Ptr = getLoadStorePointerOperand(I);
7167 
7168   return TTI.getAddressComputationCost(VectorTy) +
7169          TTI.getGatherScatterOpCost(
7170              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7171              TargetTransformInfo::TCK_RecipThroughput, I);
7172 }
7173 
7174 InstructionCost
7175 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7176                                                    ElementCount VF) {
7177   // TODO: Once we have support for interleaving with scalable vectors
7178   // we can calculate the cost properly here.
7179   if (VF.isScalable())
7180     return InstructionCost::getInvalid();
7181 
7182   Type *ValTy = getLoadStoreType(I);
7183   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7184   unsigned AS = getLoadStoreAddressSpace(I);
7185 
7186   auto Group = getInterleavedAccessGroup(I);
7187   assert(Group && "Fail to get an interleaved access group.");
7188 
7189   unsigned InterleaveFactor = Group->getFactor();
7190   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7191 
7192   // Holds the indices of existing members in the interleaved group.
7193   SmallVector<unsigned, 4> Indices;
7194   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
7195     if (Group->getMember(IF))
7196       Indices.push_back(IF);
7197 
7198   // Calculate the cost of the whole interleaved group.
7199   bool UseMaskForGaps =
7200       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
7201       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
7202   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7203       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7204       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7205 
7206   if (Group->isReverse()) {
7207     // TODO: Add support for reversed masked interleaved access.
7208     assert(!Legal->isMaskRequired(I) &&
7209            "Reverse masked interleaved access not supported.");
7210     Cost +=
7211         Group->getNumMembers() *
7212         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7213   }
7214   return Cost;
7215 }
7216 
7217 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
7218     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7219   using namespace llvm::PatternMatch;
7220   // Early exit for no inloop reductions
7221   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7222     return None;
7223   auto *VectorTy = cast<VectorType>(Ty);
7224 
7225   // We are looking for a pattern of, and finding the minimal acceptable cost:
7226   //  reduce(mul(ext(A), ext(B))) or
7227   //  reduce(mul(A, B)) or
7228   //  reduce(ext(A)) or
7229   //  reduce(A).
7230   // The basic idea is that we walk down the tree to do that, finding the root
7231   // reduction instruction in InLoopReductionImmediateChains. From there we find
7232   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7233   // of the components. If the reduction cost is lower then we return it for the
7234   // reduction instruction and 0 for the other instructions in the pattern. If
7235   // it is not we return an invalid cost specifying the orignal cost method
7236   // should be used.
7237   Instruction *RetI = I;
7238   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
7239     if (!RetI->hasOneUser())
7240       return None;
7241     RetI = RetI->user_back();
7242   }
7243   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
7244       RetI->user_back()->getOpcode() == Instruction::Add) {
7245     if (!RetI->hasOneUser())
7246       return None;
7247     RetI = RetI->user_back();
7248   }
7249 
7250   // Test if the found instruction is a reduction, and if not return an invalid
7251   // cost specifying the parent to use the original cost modelling.
7252   if (!InLoopReductionImmediateChains.count(RetI))
7253     return None;
7254 
7255   // Find the reduction this chain is a part of and calculate the basic cost of
7256   // the reduction on its own.
7257   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7258   Instruction *ReductionPhi = LastChain;
7259   while (!isa<PHINode>(ReductionPhi))
7260     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7261 
7262   const RecurrenceDescriptor &RdxDesc =
7263       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7264 
7265   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
7266       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
7267 
7268   // If we're using ordered reductions then we can just return the base cost
7269   // here, since getArithmeticReductionCost calculates the full ordered
7270   // reduction cost when FP reassociation is not allowed.
7271   if (useOrderedReductions(RdxDesc))
7272     return BaseCost;
7273 
7274   // Get the operand that was not the reduction chain and match it to one of the
7275   // patterns, returning the better cost if it is found.
7276   Instruction *RedOp = RetI->getOperand(1) == LastChain
7277                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7278                            : dyn_cast<Instruction>(RetI->getOperand(1));
7279 
7280   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7281 
7282   Instruction *Op0, *Op1;
7283   if (RedOp &&
7284       match(RedOp,
7285             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
7286       match(Op0, m_ZExtOrSExt(m_Value())) &&
7287       Op0->getOpcode() == Op1->getOpcode() &&
7288       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7289       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
7290       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
7291 
7292     // Matched reduce(ext(mul(ext(A), ext(B)))
7293     // Note that the extend opcodes need to all match, or if A==B they will have
7294     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
7295     // which is equally fine.
7296     bool IsUnsigned = isa<ZExtInst>(Op0);
7297     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7298     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
7299 
7300     InstructionCost ExtCost =
7301         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
7302                              TTI::CastContextHint::None, CostKind, Op0);
7303     InstructionCost MulCost =
7304         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
7305     InstructionCost Ext2Cost =
7306         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
7307                              TTI::CastContextHint::None, CostKind, RedOp);
7308 
7309     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7310         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7311         CostKind);
7312 
7313     if (RedCost.isValid() &&
7314         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
7315       return I == RetI ? RedCost : 0;
7316   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
7317              !TheLoop->isLoopInvariant(RedOp)) {
7318     // Matched reduce(ext(A))
7319     bool IsUnsigned = isa<ZExtInst>(RedOp);
7320     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7321     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7322         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7323         CostKind);
7324 
7325     InstructionCost ExtCost =
7326         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7327                              TTI::CastContextHint::None, CostKind, RedOp);
7328     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7329       return I == RetI ? RedCost : 0;
7330   } else if (RedOp &&
7331              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
7332     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
7333         Op0->getOpcode() == Op1->getOpcode() &&
7334         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7335         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7336       bool IsUnsigned = isa<ZExtInst>(Op0);
7337       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7338       // Matched reduce(mul(ext, ext))
7339       InstructionCost ExtCost =
7340           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7341                                TTI::CastContextHint::None, CostKind, Op0);
7342       InstructionCost MulCost =
7343           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7344 
7345       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7346           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7347           CostKind);
7348 
7349       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7350         return I == RetI ? RedCost : 0;
7351     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
7352       // Matched reduce(mul())
7353       InstructionCost MulCost =
7354           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7355 
7356       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7357           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7358           CostKind);
7359 
7360       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7361         return I == RetI ? RedCost : 0;
7362     }
7363   }
7364 
7365   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
7366 }
7367 
7368 InstructionCost
7369 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7370                                                      ElementCount VF) {
7371   // Calculate scalar cost only. Vectorization cost should be ready at this
7372   // moment.
7373   if (VF.isScalar()) {
7374     Type *ValTy = getLoadStoreType(I);
7375     const Align Alignment = getLoadStoreAlignment(I);
7376     unsigned AS = getLoadStoreAddressSpace(I);
7377 
7378     return TTI.getAddressComputationCost(ValTy) +
7379            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7380                                TTI::TCK_RecipThroughput, I);
7381   }
7382   return getWideningCost(I, VF);
7383 }
7384 
7385 LoopVectorizationCostModel::VectorizationCostTy
7386 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7387                                                ElementCount VF) {
7388   // If we know that this instruction will remain uniform, check the cost of
7389   // the scalar version.
7390   if (isUniformAfterVectorization(I, VF))
7391     VF = ElementCount::getFixed(1);
7392 
7393   if (VF.isVector() && isProfitableToScalarize(I, VF))
7394     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7395 
7396   // Forced scalars do not have any scalarization overhead.
7397   auto ForcedScalar = ForcedScalars.find(VF);
7398   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7399     auto InstSet = ForcedScalar->second;
7400     if (InstSet.count(I))
7401       return VectorizationCostTy(
7402           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7403            VF.getKnownMinValue()),
7404           false);
7405   }
7406 
7407   Type *VectorTy;
7408   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7409 
7410   bool TypeNotScalarized =
7411       VF.isVector() && VectorTy->isVectorTy() &&
7412       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7413   return VectorizationCostTy(C, TypeNotScalarized);
7414 }
7415 
7416 InstructionCost
7417 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7418                                                      ElementCount VF) const {
7419 
7420   // There is no mechanism yet to create a scalable scalarization loop,
7421   // so this is currently Invalid.
7422   if (VF.isScalable())
7423     return InstructionCost::getInvalid();
7424 
7425   if (VF.isScalar())
7426     return 0;
7427 
7428   InstructionCost Cost = 0;
7429   Type *RetTy = ToVectorTy(I->getType(), VF);
7430   if (!RetTy->isVoidTy() &&
7431       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7432     Cost += TTI.getScalarizationOverhead(
7433         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
7434         false);
7435 
7436   // Some targets keep addresses scalar.
7437   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7438     return Cost;
7439 
7440   // Some targets support efficient element stores.
7441   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7442     return Cost;
7443 
7444   // Collect operands to consider.
7445   CallInst *CI = dyn_cast<CallInst>(I);
7446   Instruction::op_range Ops = CI ? CI->args() : I->operands();
7447 
7448   // Skip operands that do not require extraction/scalarization and do not incur
7449   // any overhead.
7450   SmallVector<Type *> Tys;
7451   for (auto *V : filterExtractingOperands(Ops, VF))
7452     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7453   return Cost + TTI.getOperandsScalarizationOverhead(
7454                     filterExtractingOperands(Ops, VF), Tys);
7455 }
7456 
7457 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7458   if (VF.isScalar())
7459     return;
7460   NumPredStores = 0;
7461   for (BasicBlock *BB : TheLoop->blocks()) {
7462     // For each instruction in the old loop.
7463     for (Instruction &I : *BB) {
7464       Value *Ptr =  getLoadStorePointerOperand(&I);
7465       if (!Ptr)
7466         continue;
7467 
7468       // TODO: We should generate better code and update the cost model for
7469       // predicated uniform stores. Today they are treated as any other
7470       // predicated store (see added test cases in
7471       // invariant-store-vectorization.ll).
7472       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7473         NumPredStores++;
7474 
7475       if (Legal->isUniformMemOp(I)) {
7476         // TODO: Avoid replicating loads and stores instead of
7477         // relying on instcombine to remove them.
7478         // Load: Scalar load + broadcast
7479         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7480         InstructionCost Cost;
7481         if (isa<StoreInst>(&I) && VF.isScalable() &&
7482             isLegalGatherOrScatter(&I)) {
7483           Cost = getGatherScatterCost(&I, VF);
7484           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7485         } else {
7486           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7487                  "Cannot yet scalarize uniform stores");
7488           Cost = getUniformMemOpCost(&I, VF);
7489           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7490         }
7491         continue;
7492       }
7493 
7494       // We assume that widening is the best solution when possible.
7495       if (memoryInstructionCanBeWidened(&I, VF)) {
7496         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7497         int ConsecutiveStride = Legal->isConsecutivePtr(
7498             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
7499         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7500                "Expected consecutive stride.");
7501         InstWidening Decision =
7502             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7503         setWideningDecision(&I, VF, Decision, Cost);
7504         continue;
7505       }
7506 
7507       // Choose between Interleaving, Gather/Scatter or Scalarization.
7508       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7509       unsigned NumAccesses = 1;
7510       if (isAccessInterleaved(&I)) {
7511         auto Group = getInterleavedAccessGroup(&I);
7512         assert(Group && "Fail to get an interleaved access group.");
7513 
7514         // Make one decision for the whole group.
7515         if (getWideningDecision(&I, VF) != CM_Unknown)
7516           continue;
7517 
7518         NumAccesses = Group->getNumMembers();
7519         if (interleavedAccessCanBeWidened(&I, VF))
7520           InterleaveCost = getInterleaveGroupCost(&I, VF);
7521       }
7522 
7523       InstructionCost GatherScatterCost =
7524           isLegalGatherOrScatter(&I)
7525               ? getGatherScatterCost(&I, VF) * NumAccesses
7526               : InstructionCost::getInvalid();
7527 
7528       InstructionCost ScalarizationCost =
7529           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7530 
7531       // Choose better solution for the current VF,
7532       // write down this decision and use it during vectorization.
7533       InstructionCost Cost;
7534       InstWidening Decision;
7535       if (InterleaveCost <= GatherScatterCost &&
7536           InterleaveCost < ScalarizationCost) {
7537         Decision = CM_Interleave;
7538         Cost = InterleaveCost;
7539       } else if (GatherScatterCost < ScalarizationCost) {
7540         Decision = CM_GatherScatter;
7541         Cost = GatherScatterCost;
7542       } else {
7543         Decision = CM_Scalarize;
7544         Cost = ScalarizationCost;
7545       }
7546       // If the instructions belongs to an interleave group, the whole group
7547       // receives the same decision. The whole group receives the cost, but
7548       // the cost will actually be assigned to one instruction.
7549       if (auto Group = getInterleavedAccessGroup(&I))
7550         setWideningDecision(Group, VF, Decision, Cost);
7551       else
7552         setWideningDecision(&I, VF, Decision, Cost);
7553     }
7554   }
7555 
7556   // Make sure that any load of address and any other address computation
7557   // remains scalar unless there is gather/scatter support. This avoids
7558   // inevitable extracts into address registers, and also has the benefit of
7559   // activating LSR more, since that pass can't optimize vectorized
7560   // addresses.
7561   if (TTI.prefersVectorizedAddressing())
7562     return;
7563 
7564   // Start with all scalar pointer uses.
7565   SmallPtrSet<Instruction *, 8> AddrDefs;
7566   for (BasicBlock *BB : TheLoop->blocks())
7567     for (Instruction &I : *BB) {
7568       Instruction *PtrDef =
7569         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7570       if (PtrDef && TheLoop->contains(PtrDef) &&
7571           getWideningDecision(&I, VF) != CM_GatherScatter)
7572         AddrDefs.insert(PtrDef);
7573     }
7574 
7575   // Add all instructions used to generate the addresses.
7576   SmallVector<Instruction *, 4> Worklist;
7577   append_range(Worklist, AddrDefs);
7578   while (!Worklist.empty()) {
7579     Instruction *I = Worklist.pop_back_val();
7580     for (auto &Op : I->operands())
7581       if (auto *InstOp = dyn_cast<Instruction>(Op))
7582         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7583             AddrDefs.insert(InstOp).second)
7584           Worklist.push_back(InstOp);
7585   }
7586 
7587   for (auto *I : AddrDefs) {
7588     if (isa<LoadInst>(I)) {
7589       // Setting the desired widening decision should ideally be handled in
7590       // by cost functions, but since this involves the task of finding out
7591       // if the loaded register is involved in an address computation, it is
7592       // instead changed here when we know this is the case.
7593       InstWidening Decision = getWideningDecision(I, VF);
7594       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7595         // Scalarize a widened load of address.
7596         setWideningDecision(
7597             I, VF, CM_Scalarize,
7598             (VF.getKnownMinValue() *
7599              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7600       else if (auto Group = getInterleavedAccessGroup(I)) {
7601         // Scalarize an interleave group of address loads.
7602         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7603           if (Instruction *Member = Group->getMember(I))
7604             setWideningDecision(
7605                 Member, VF, CM_Scalarize,
7606                 (VF.getKnownMinValue() *
7607                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7608         }
7609       }
7610     } else
7611       // Make sure I gets scalarized and a cost estimate without
7612       // scalarization overhead.
7613       ForcedScalars[VF].insert(I);
7614   }
7615 }
7616 
7617 InstructionCost
7618 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7619                                                Type *&VectorTy) {
7620   Type *RetTy = I->getType();
7621   if (canTruncateToMinimalBitwidth(I, VF))
7622     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7623   auto SE = PSE.getSE();
7624   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7625 
7626   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7627                                                 ElementCount VF) -> bool {
7628     if (VF.isScalar())
7629       return true;
7630 
7631     auto Scalarized = InstsToScalarize.find(VF);
7632     assert(Scalarized != InstsToScalarize.end() &&
7633            "VF not yet analyzed for scalarization profitability");
7634     return !Scalarized->second.count(I) &&
7635            llvm::all_of(I->users(), [&](User *U) {
7636              auto *UI = cast<Instruction>(U);
7637              return !Scalarized->second.count(UI);
7638            });
7639   };
7640   (void) hasSingleCopyAfterVectorization;
7641 
7642   if (isScalarAfterVectorization(I, VF)) {
7643     // With the exception of GEPs and PHIs, after scalarization there should
7644     // only be one copy of the instruction generated in the loop. This is
7645     // because the VF is either 1, or any instructions that need scalarizing
7646     // have already been dealt with by the the time we get here. As a result,
7647     // it means we don't have to multiply the instruction cost by VF.
7648     assert(I->getOpcode() == Instruction::GetElementPtr ||
7649            I->getOpcode() == Instruction::PHI ||
7650            (I->getOpcode() == Instruction::BitCast &&
7651             I->getType()->isPointerTy()) ||
7652            hasSingleCopyAfterVectorization(I, VF));
7653     VectorTy = RetTy;
7654   } else
7655     VectorTy = ToVectorTy(RetTy, VF);
7656 
7657   // TODO: We need to estimate the cost of intrinsic calls.
7658   switch (I->getOpcode()) {
7659   case Instruction::GetElementPtr:
7660     // We mark this instruction as zero-cost because the cost of GEPs in
7661     // vectorized code depends on whether the corresponding memory instruction
7662     // is scalarized or not. Therefore, we handle GEPs with the memory
7663     // instruction cost.
7664     return 0;
7665   case Instruction::Br: {
7666     // In cases of scalarized and predicated instructions, there will be VF
7667     // predicated blocks in the vectorized loop. Each branch around these
7668     // blocks requires also an extract of its vector compare i1 element.
7669     bool ScalarPredicatedBB = false;
7670     BranchInst *BI = cast<BranchInst>(I);
7671     if (VF.isVector() && BI->isConditional() &&
7672         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7673          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7674       ScalarPredicatedBB = true;
7675 
7676     if (ScalarPredicatedBB) {
7677       // Not possible to scalarize scalable vector with predicated instructions.
7678       if (VF.isScalable())
7679         return InstructionCost::getInvalid();
7680       // Return cost for branches around scalarized and predicated blocks.
7681       auto *Vec_i1Ty =
7682           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7683       return (
7684           TTI.getScalarizationOverhead(
7685               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7686           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7687     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7688       // The back-edge branch will remain, as will all scalar branches.
7689       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7690     else
7691       // This branch will be eliminated by if-conversion.
7692       return 0;
7693     // Note: We currently assume zero cost for an unconditional branch inside
7694     // a predicated block since it will become a fall-through, although we
7695     // may decide in the future to call TTI for all branches.
7696   }
7697   case Instruction::PHI: {
7698     auto *Phi = cast<PHINode>(I);
7699 
7700     // First-order recurrences are replaced by vector shuffles inside the loop.
7701     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7702     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7703       return TTI.getShuffleCost(
7704           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7705           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7706 
7707     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7708     // converted into select instructions. We require N - 1 selects per phi
7709     // node, where N is the number of incoming values.
7710     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7711       return (Phi->getNumIncomingValues() - 1) *
7712              TTI.getCmpSelInstrCost(
7713                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7714                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7715                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7716 
7717     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7718   }
7719   case Instruction::UDiv:
7720   case Instruction::SDiv:
7721   case Instruction::URem:
7722   case Instruction::SRem:
7723     // If we have a predicated instruction, it may not be executed for each
7724     // vector lane. Get the scalarization cost and scale this amount by the
7725     // probability of executing the predicated block. If the instruction is not
7726     // predicated, we fall through to the next case.
7727     if (VF.isVector() && isScalarWithPredication(I)) {
7728       InstructionCost Cost = 0;
7729 
7730       // These instructions have a non-void type, so account for the phi nodes
7731       // that we will create. This cost is likely to be zero. The phi node
7732       // cost, if any, should be scaled by the block probability because it
7733       // models a copy at the end of each predicated block.
7734       Cost += VF.getKnownMinValue() *
7735               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7736 
7737       // The cost of the non-predicated instruction.
7738       Cost += VF.getKnownMinValue() *
7739               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7740 
7741       // The cost of insertelement and extractelement instructions needed for
7742       // scalarization.
7743       Cost += getScalarizationOverhead(I, VF);
7744 
7745       // Scale the cost by the probability of executing the predicated blocks.
7746       // This assumes the predicated block for each vector lane is equally
7747       // likely.
7748       return Cost / getReciprocalPredBlockProb();
7749     }
7750     LLVM_FALLTHROUGH;
7751   case Instruction::Add:
7752   case Instruction::FAdd:
7753   case Instruction::Sub:
7754   case Instruction::FSub:
7755   case Instruction::Mul:
7756   case Instruction::FMul:
7757   case Instruction::FDiv:
7758   case Instruction::FRem:
7759   case Instruction::Shl:
7760   case Instruction::LShr:
7761   case Instruction::AShr:
7762   case Instruction::And:
7763   case Instruction::Or:
7764   case Instruction::Xor: {
7765     // Since we will replace the stride by 1 the multiplication should go away.
7766     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7767       return 0;
7768 
7769     // Detect reduction patterns
7770     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7771       return *RedCost;
7772 
7773     // Certain instructions can be cheaper to vectorize if they have a constant
7774     // second vector operand. One example of this are shifts on x86.
7775     Value *Op2 = I->getOperand(1);
7776     TargetTransformInfo::OperandValueProperties Op2VP;
7777     TargetTransformInfo::OperandValueKind Op2VK =
7778         TTI.getOperandInfo(Op2, Op2VP);
7779     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7780       Op2VK = TargetTransformInfo::OK_UniformValue;
7781 
7782     SmallVector<const Value *, 4> Operands(I->operand_values());
7783     return TTI.getArithmeticInstrCost(
7784         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7785         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7786   }
7787   case Instruction::FNeg: {
7788     return TTI.getArithmeticInstrCost(
7789         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7790         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7791         TargetTransformInfo::OP_None, I->getOperand(0), I);
7792   }
7793   case Instruction::Select: {
7794     SelectInst *SI = cast<SelectInst>(I);
7795     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7796     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7797 
7798     const Value *Op0, *Op1;
7799     using namespace llvm::PatternMatch;
7800     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7801                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7802       // select x, y, false --> x & y
7803       // select x, true, y --> x | y
7804       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7805       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7806       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7807       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7808       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7809               Op1->getType()->getScalarSizeInBits() == 1);
7810 
7811       SmallVector<const Value *, 2> Operands{Op0, Op1};
7812       return TTI.getArithmeticInstrCost(
7813           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7814           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7815     }
7816 
7817     Type *CondTy = SI->getCondition()->getType();
7818     if (!ScalarCond)
7819       CondTy = VectorType::get(CondTy, VF);
7820     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7821                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7822   }
7823   case Instruction::ICmp:
7824   case Instruction::FCmp: {
7825     Type *ValTy = I->getOperand(0)->getType();
7826     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7827     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7828       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7829     VectorTy = ToVectorTy(ValTy, VF);
7830     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7831                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7832   }
7833   case Instruction::Store:
7834   case Instruction::Load: {
7835     ElementCount Width = VF;
7836     if (Width.isVector()) {
7837       InstWidening Decision = getWideningDecision(I, Width);
7838       assert(Decision != CM_Unknown &&
7839              "CM decision should be taken at this point");
7840       if (Decision == CM_Scalarize)
7841         Width = ElementCount::getFixed(1);
7842     }
7843     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7844     return getMemoryInstructionCost(I, VF);
7845   }
7846   case Instruction::BitCast:
7847     if (I->getType()->isPointerTy())
7848       return 0;
7849     LLVM_FALLTHROUGH;
7850   case Instruction::ZExt:
7851   case Instruction::SExt:
7852   case Instruction::FPToUI:
7853   case Instruction::FPToSI:
7854   case Instruction::FPExt:
7855   case Instruction::PtrToInt:
7856   case Instruction::IntToPtr:
7857   case Instruction::SIToFP:
7858   case Instruction::UIToFP:
7859   case Instruction::Trunc:
7860   case Instruction::FPTrunc: {
7861     // Computes the CastContextHint from a Load/Store instruction.
7862     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7863       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7864              "Expected a load or a store!");
7865 
7866       if (VF.isScalar() || !TheLoop->contains(I))
7867         return TTI::CastContextHint::Normal;
7868 
7869       switch (getWideningDecision(I, VF)) {
7870       case LoopVectorizationCostModel::CM_GatherScatter:
7871         return TTI::CastContextHint::GatherScatter;
7872       case LoopVectorizationCostModel::CM_Interleave:
7873         return TTI::CastContextHint::Interleave;
7874       case LoopVectorizationCostModel::CM_Scalarize:
7875       case LoopVectorizationCostModel::CM_Widen:
7876         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7877                                         : TTI::CastContextHint::Normal;
7878       case LoopVectorizationCostModel::CM_Widen_Reverse:
7879         return TTI::CastContextHint::Reversed;
7880       case LoopVectorizationCostModel::CM_Unknown:
7881         llvm_unreachable("Instr did not go through cost modelling?");
7882       }
7883 
7884       llvm_unreachable("Unhandled case!");
7885     };
7886 
7887     unsigned Opcode = I->getOpcode();
7888     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7889     // For Trunc, the context is the only user, which must be a StoreInst.
7890     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7891       if (I->hasOneUse())
7892         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7893           CCH = ComputeCCH(Store);
7894     }
7895     // For Z/Sext, the context is the operand, which must be a LoadInst.
7896     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7897              Opcode == Instruction::FPExt) {
7898       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7899         CCH = ComputeCCH(Load);
7900     }
7901 
7902     // We optimize the truncation of induction variables having constant
7903     // integer steps. The cost of these truncations is the same as the scalar
7904     // operation.
7905     if (isOptimizableIVTruncate(I, VF)) {
7906       auto *Trunc = cast<TruncInst>(I);
7907       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7908                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7909     }
7910 
7911     // Detect reduction patterns
7912     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7913       return *RedCost;
7914 
7915     Type *SrcScalarTy = I->getOperand(0)->getType();
7916     Type *SrcVecTy =
7917         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7918     if (canTruncateToMinimalBitwidth(I, VF)) {
7919       // This cast is going to be shrunk. This may remove the cast or it might
7920       // turn it into slightly different cast. For example, if MinBW == 16,
7921       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7922       //
7923       // Calculate the modified src and dest types.
7924       Type *MinVecTy = VectorTy;
7925       if (Opcode == Instruction::Trunc) {
7926         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7927         VectorTy =
7928             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7929       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7930         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7931         VectorTy =
7932             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7933       }
7934     }
7935 
7936     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7937   }
7938   case Instruction::Call: {
7939     bool NeedToScalarize;
7940     CallInst *CI = cast<CallInst>(I);
7941     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7942     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7943       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7944       return std::min(CallCost, IntrinsicCost);
7945     }
7946     return CallCost;
7947   }
7948   case Instruction::ExtractValue:
7949     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7950   case Instruction::Alloca:
7951     // We cannot easily widen alloca to a scalable alloca, as
7952     // the result would need to be a vector of pointers.
7953     if (VF.isScalable())
7954       return InstructionCost::getInvalid();
7955     LLVM_FALLTHROUGH;
7956   default:
7957     // This opcode is unknown. Assume that it is the same as 'mul'.
7958     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7959   } // end of switch.
7960 }
7961 
7962 char LoopVectorize::ID = 0;
7963 
7964 static const char lv_name[] = "Loop Vectorization";
7965 
7966 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7967 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7968 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7969 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7970 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7971 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7972 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7973 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7974 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7975 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7976 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7977 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7978 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7979 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7980 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7981 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7982 
7983 namespace llvm {
7984 
7985 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7986 
7987 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7988                               bool VectorizeOnlyWhenForced) {
7989   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7990 }
7991 
7992 } // end namespace llvm
7993 
7994 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7995   // Check if the pointer operand of a load or store instruction is
7996   // consecutive.
7997   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7998     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7999   return false;
8000 }
8001 
8002 void LoopVectorizationCostModel::collectValuesToIgnore() {
8003   // Ignore ephemeral values.
8004   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
8005 
8006   // Ignore type-promoting instructions we identified during reduction
8007   // detection.
8008   for (auto &Reduction : Legal->getReductionVars()) {
8009     RecurrenceDescriptor &RedDes = Reduction.second;
8010     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
8011     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
8012   }
8013   // Ignore type-casting instructions we identified during induction
8014   // detection.
8015   for (auto &Induction : Legal->getInductionVars()) {
8016     InductionDescriptor &IndDes = Induction.second;
8017     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8018     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
8019   }
8020 }
8021 
8022 void LoopVectorizationCostModel::collectInLoopReductions() {
8023   for (auto &Reduction : Legal->getReductionVars()) {
8024     PHINode *Phi = Reduction.first;
8025     RecurrenceDescriptor &RdxDesc = Reduction.second;
8026 
8027     // We don't collect reductions that are type promoted (yet).
8028     if (RdxDesc.getRecurrenceType() != Phi->getType())
8029       continue;
8030 
8031     // If the target would prefer this reduction to happen "in-loop", then we
8032     // want to record it as such.
8033     unsigned Opcode = RdxDesc.getOpcode();
8034     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
8035         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
8036                                    TargetTransformInfo::ReductionFlags()))
8037       continue;
8038 
8039     // Check that we can correctly put the reductions into the loop, by
8040     // finding the chain of operations that leads from the phi to the loop
8041     // exit value.
8042     SmallVector<Instruction *, 4> ReductionOperations =
8043         RdxDesc.getReductionOpChain(Phi, TheLoop);
8044     bool InLoop = !ReductionOperations.empty();
8045     if (InLoop) {
8046       InLoopReductionChains[Phi] = ReductionOperations;
8047       // Add the elements to InLoopReductionImmediateChains for cost modelling.
8048       Instruction *LastChain = Phi;
8049       for (auto *I : ReductionOperations) {
8050         InLoopReductionImmediateChains[I] = LastChain;
8051         LastChain = I;
8052       }
8053     }
8054     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
8055                       << " reduction for phi: " << *Phi << "\n");
8056   }
8057 }
8058 
8059 // TODO: we could return a pair of values that specify the max VF and
8060 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
8061 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
8062 // doesn't have a cost model that can choose which plan to execute if
8063 // more than one is generated.
8064 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
8065                                  LoopVectorizationCostModel &CM) {
8066   unsigned WidestType;
8067   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
8068   return WidestVectorRegBits / WidestType;
8069 }
8070 
8071 VectorizationFactor
8072 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
8073   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
8074   ElementCount VF = UserVF;
8075   // Outer loop handling: They may require CFG and instruction level
8076   // transformations before even evaluating whether vectorization is profitable.
8077   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8078   // the vectorization pipeline.
8079   if (!OrigLoop->isInnermost()) {
8080     // If the user doesn't provide a vectorization factor, determine a
8081     // reasonable one.
8082     if (UserVF.isZero()) {
8083       VF = ElementCount::getFixed(determineVPlanVF(
8084           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
8085               .getFixedSize(),
8086           CM));
8087       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
8088 
8089       // Make sure we have a VF > 1 for stress testing.
8090       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
8091         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
8092                           << "overriding computed VF.\n");
8093         VF = ElementCount::getFixed(4);
8094       }
8095     }
8096     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8097     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
8098            "VF needs to be a power of two");
8099     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
8100                       << "VF " << VF << " to build VPlans.\n");
8101     buildVPlans(VF, VF);
8102 
8103     // For VPlan build stress testing, we bail out after VPlan construction.
8104     if (VPlanBuildStressTest)
8105       return VectorizationFactor::Disabled();
8106 
8107     return {VF, 0 /*Cost*/};
8108   }
8109 
8110   LLVM_DEBUG(
8111       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
8112                 "VPlan-native path.\n");
8113   return VectorizationFactor::Disabled();
8114 }
8115 
8116 Optional<VectorizationFactor>
8117 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
8118   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8119   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
8120   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
8121     return None;
8122 
8123   // Invalidate interleave groups if all blocks of loop will be predicated.
8124   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
8125       !useMaskedInterleavedAccesses(*TTI)) {
8126     LLVM_DEBUG(
8127         dbgs()
8128         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
8129            "which requires masked-interleaved support.\n");
8130     if (CM.InterleaveInfo.invalidateGroups())
8131       // Invalidating interleave groups also requires invalidating all decisions
8132       // based on them, which includes widening decisions and uniform and scalar
8133       // values.
8134       CM.invalidateCostModelingDecisions();
8135   }
8136 
8137   ElementCount MaxUserVF =
8138       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
8139   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
8140   if (!UserVF.isZero() && UserVFIsLegal) {
8141     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
8142            "VF needs to be a power of two");
8143     // Collect the instructions (and their associated costs) that will be more
8144     // profitable to scalarize.
8145     if (CM.selectUserVectorizationFactor(UserVF)) {
8146       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
8147       CM.collectInLoopReductions();
8148       buildVPlansWithVPRecipes(UserVF, UserVF);
8149       LLVM_DEBUG(printPlans(dbgs()));
8150       return {{UserVF, 0}};
8151     } else
8152       reportVectorizationInfo("UserVF ignored because of invalid costs.",
8153                               "InvalidCost", ORE, OrigLoop);
8154   }
8155 
8156   // Populate the set of Vectorization Factor Candidates.
8157   ElementCountSet VFCandidates;
8158   for (auto VF = ElementCount::getFixed(1);
8159        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
8160     VFCandidates.insert(VF);
8161   for (auto VF = ElementCount::getScalable(1);
8162        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
8163     VFCandidates.insert(VF);
8164 
8165   for (const auto &VF : VFCandidates) {
8166     // Collect Uniform and Scalar instructions after vectorization with VF.
8167     CM.collectUniformsAndScalars(VF);
8168 
8169     // Collect the instructions (and their associated costs) that will be more
8170     // profitable to scalarize.
8171     if (VF.isVector())
8172       CM.collectInstsToScalarize(VF);
8173   }
8174 
8175   CM.collectInLoopReductions();
8176   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
8177   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
8178 
8179   LLVM_DEBUG(printPlans(dbgs()));
8180   if (!MaxFactors.hasVector())
8181     return VectorizationFactor::Disabled();
8182 
8183   // Select the optimal vectorization factor.
8184   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
8185 
8186   // Check if it is profitable to vectorize with runtime checks.
8187   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8188   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8189     bool PragmaThresholdReached =
8190         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8191     bool ThresholdReached =
8192         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8193     if ((ThresholdReached && !Hints.allowReordering()) ||
8194         PragmaThresholdReached) {
8195       ORE->emit([&]() {
8196         return OptimizationRemarkAnalysisAliasing(
8197                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8198                    OrigLoop->getHeader())
8199                << "loop not vectorized: cannot prove it is safe to reorder "
8200                   "memory operations";
8201       });
8202       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8203       Hints.emitRemarkWithHints();
8204       return VectorizationFactor::Disabled();
8205     }
8206   }
8207   return SelectedVF;
8208 }
8209 
8210 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
8211   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
8212                     << '\n');
8213   BestVF = VF;
8214   BestUF = UF;
8215 
8216   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
8217     return !Plan->hasVF(VF);
8218   });
8219   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
8220 }
8221 
8222 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
8223                                            DominatorTree *DT) {
8224   // Perform the actual loop transformation.
8225 
8226   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8227   assert(BestVF.hasValue() && "Vectorization Factor is missing");
8228   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
8229 
8230   VPTransformState State{
8231       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
8232   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8233   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8234   State.CanonicalIV = ILV.Induction;
8235 
8236   ILV.printDebugTracesAtStart();
8237 
8238   //===------------------------------------------------===//
8239   //
8240   // Notice: any optimization or new instruction that go
8241   // into the code below should also be implemented in
8242   // the cost-model.
8243   //
8244   //===------------------------------------------------===//
8245 
8246   // 2. Copy and widen instructions from the old loop into the new loop.
8247   VPlans.front()->execute(&State);
8248 
8249   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8250   //    predication, updating analyses.
8251   ILV.fixVectorizedLoop(State);
8252 
8253   ILV.printDebugTracesAtEnd();
8254 }
8255 
8256 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8257 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8258   for (const auto &Plan : VPlans)
8259     if (PrintVPlansInDotFormat)
8260       Plan->printDOT(O);
8261     else
8262       Plan->print(O);
8263 }
8264 #endif
8265 
8266 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8267     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8268 
8269   // We create new control-flow for the vectorized loop, so the original exit
8270   // conditions will be dead after vectorization if it's only used by the
8271   // terminator
8272   SmallVector<BasicBlock*> ExitingBlocks;
8273   OrigLoop->getExitingBlocks(ExitingBlocks);
8274   for (auto *BB : ExitingBlocks) {
8275     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8276     if (!Cmp || !Cmp->hasOneUse())
8277       continue;
8278 
8279     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8280     if (!DeadInstructions.insert(Cmp).second)
8281       continue;
8282 
8283     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8284     // TODO: can recurse through operands in general
8285     for (Value *Op : Cmp->operands()) {
8286       if (isa<TruncInst>(Op) && Op->hasOneUse())
8287           DeadInstructions.insert(cast<Instruction>(Op));
8288     }
8289   }
8290 
8291   // We create new "steps" for induction variable updates to which the original
8292   // induction variables map. An original update instruction will be dead if
8293   // all its users except the induction variable are dead.
8294   auto *Latch = OrigLoop->getLoopLatch();
8295   for (auto &Induction : Legal->getInductionVars()) {
8296     PHINode *Ind = Induction.first;
8297     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8298 
8299     // If the tail is to be folded by masking, the primary induction variable,
8300     // if exists, isn't dead: it will be used for masking. Don't kill it.
8301     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8302       continue;
8303 
8304     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8305           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8306         }))
8307       DeadInstructions.insert(IndUpdate);
8308 
8309     // We record as "Dead" also the type-casting instructions we had identified
8310     // during induction analysis. We don't need any handling for them in the
8311     // vectorized loop because we have proven that, under a proper runtime
8312     // test guarding the vectorized loop, the value of the phi, and the casted
8313     // value of the phi, are the same. The last instruction in this casting chain
8314     // will get its scalar/vector/widened def from the scalar/vector/widened def
8315     // of the respective phi node. Any other casts in the induction def-use chain
8316     // have no other uses outside the phi update chain, and will be ignored.
8317     InductionDescriptor &IndDes = Induction.second;
8318     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8319     DeadInstructions.insert(Casts.begin(), Casts.end());
8320   }
8321 }
8322 
8323 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8324 
8325 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8326 
8327 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8328                                         Instruction::BinaryOps BinOp) {
8329   // When unrolling and the VF is 1, we only need to add a simple scalar.
8330   Type *Ty = Val->getType();
8331   assert(!Ty->isVectorTy() && "Val must be a scalar");
8332 
8333   if (Ty->isFloatingPointTy()) {
8334     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8335 
8336     // Floating-point operations inherit FMF via the builder's flags.
8337     Value *MulOp = Builder.CreateFMul(C, Step);
8338     return Builder.CreateBinOp(BinOp, Val, MulOp);
8339   }
8340   Constant *C = ConstantInt::get(Ty, StartIdx);
8341   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8342 }
8343 
8344 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8345   SmallVector<Metadata *, 4> MDs;
8346   // Reserve first location for self reference to the LoopID metadata node.
8347   MDs.push_back(nullptr);
8348   bool IsUnrollMetadata = false;
8349   MDNode *LoopID = L->getLoopID();
8350   if (LoopID) {
8351     // First find existing loop unrolling disable metadata.
8352     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8353       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8354       if (MD) {
8355         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8356         IsUnrollMetadata =
8357             S && S->getString().startswith("llvm.loop.unroll.disable");
8358       }
8359       MDs.push_back(LoopID->getOperand(i));
8360     }
8361   }
8362 
8363   if (!IsUnrollMetadata) {
8364     // Add runtime unroll disable metadata.
8365     LLVMContext &Context = L->getHeader()->getContext();
8366     SmallVector<Metadata *, 1> DisableOperands;
8367     DisableOperands.push_back(
8368         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8369     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8370     MDs.push_back(DisableNode);
8371     MDNode *NewLoopID = MDNode::get(Context, MDs);
8372     // Set operand 0 to refer to the loop id itself.
8373     NewLoopID->replaceOperandWith(0, NewLoopID);
8374     L->setLoopID(NewLoopID);
8375   }
8376 }
8377 
8378 //===--------------------------------------------------------------------===//
8379 // EpilogueVectorizerMainLoop
8380 //===--------------------------------------------------------------------===//
8381 
8382 /// This function is partially responsible for generating the control flow
8383 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8384 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8385   MDNode *OrigLoopID = OrigLoop->getLoopID();
8386   Loop *Lp = createVectorLoopSkeleton("");
8387 
8388   // Generate the code to check the minimum iteration count of the vector
8389   // epilogue (see below).
8390   EPI.EpilogueIterationCountCheck =
8391       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8392   EPI.EpilogueIterationCountCheck->setName("iter.check");
8393 
8394   // Generate the code to check any assumptions that we've made for SCEV
8395   // expressions.
8396   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8397 
8398   // Generate the code that checks at runtime if arrays overlap. We put the
8399   // checks into a separate block to make the more common case of few elements
8400   // faster.
8401   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8402 
8403   // Generate the iteration count check for the main loop, *after* the check
8404   // for the epilogue loop, so that the path-length is shorter for the case
8405   // that goes directly through the vector epilogue. The longer-path length for
8406   // the main loop is compensated for, by the gain from vectorizing the larger
8407   // trip count. Note: the branch will get updated later on when we vectorize
8408   // the epilogue.
8409   EPI.MainLoopIterationCountCheck =
8410       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8411 
8412   // Generate the induction variable.
8413   OldInduction = Legal->getPrimaryInduction();
8414   Type *IdxTy = Legal->getWidestInductionType();
8415   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8416   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8417   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8418   EPI.VectorTripCount = CountRoundDown;
8419   Induction =
8420       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8421                               getDebugLocFromInstOrOperands(OldInduction));
8422 
8423   // Skip induction resume value creation here because they will be created in
8424   // the second pass. If we created them here, they wouldn't be used anyway,
8425   // because the vplan in the second pass still contains the inductions from the
8426   // original loop.
8427 
8428   return completeLoopSkeleton(Lp, OrigLoopID);
8429 }
8430 
8431 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8432   LLVM_DEBUG({
8433     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8434            << "Main Loop VF:" << EPI.MainLoopVF
8435            << ", Main Loop UF:" << EPI.MainLoopUF
8436            << ", Epilogue Loop VF:" << EPI.EpilogueVF
8437            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8438   });
8439 }
8440 
8441 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8442   DEBUG_WITH_TYPE(VerboseDebug, {
8443     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8444   });
8445 }
8446 
8447 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8448     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8449   assert(L && "Expected valid Loop.");
8450   assert(Bypass && "Expected valid bypass basic block.");
8451   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
8452   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8453   Value *Count = getOrCreateTripCount(L);
8454   // Reuse existing vector loop preheader for TC checks.
8455   // Note that new preheader block is generated for vector loop.
8456   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8457   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8458 
8459   // Generate code to check if the loop's trip count is less than VF * UF of the
8460   // main vector loop.
8461   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8462       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8463 
8464   Value *CheckMinIters = Builder.CreateICmp(
8465       P, Count, getRuntimeVF(Builder, Count->getType(), VFactor * UFactor),
8466       "min.iters.check");
8467 
8468   if (!ForEpilogue)
8469     TCCheckBlock->setName("vector.main.loop.iter.check");
8470 
8471   // Create new preheader for vector loop.
8472   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8473                                    DT, LI, nullptr, "vector.ph");
8474 
8475   if (ForEpilogue) {
8476     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8477                                  DT->getNode(Bypass)->getIDom()) &&
8478            "TC check is expected to dominate Bypass");
8479 
8480     // Update dominator for Bypass & LoopExit.
8481     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8482     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8483       // For loops with multiple exits, there's no edge from the middle block
8484       // to exit blocks (as the epilogue must run) and thus no need to update
8485       // the immediate dominator of the exit blocks.
8486       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8487 
8488     LoopBypassBlocks.push_back(TCCheckBlock);
8489 
8490     // Save the trip count so we don't have to regenerate it in the
8491     // vec.epilog.iter.check. This is safe to do because the trip count
8492     // generated here dominates the vector epilog iter check.
8493     EPI.TripCount = Count;
8494   }
8495 
8496   ReplaceInstWithInst(
8497       TCCheckBlock->getTerminator(),
8498       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8499 
8500   return TCCheckBlock;
8501 }
8502 
8503 //===--------------------------------------------------------------------===//
8504 // EpilogueVectorizerEpilogueLoop
8505 //===--------------------------------------------------------------------===//
8506 
8507 /// This function is partially responsible for generating the control flow
8508 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8509 BasicBlock *
8510 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8511   MDNode *OrigLoopID = OrigLoop->getLoopID();
8512   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8513 
8514   // Now, compare the remaining count and if there aren't enough iterations to
8515   // execute the vectorized epilogue skip to the scalar part.
8516   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8517   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8518   LoopVectorPreHeader =
8519       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8520                  LI, nullptr, "vec.epilog.ph");
8521   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8522                                           VecEpilogueIterationCountCheck);
8523 
8524   // Adjust the control flow taking the state info from the main loop
8525   // vectorization into account.
8526   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8527          "expected this to be saved from the previous pass.");
8528   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8529       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8530 
8531   DT->changeImmediateDominator(LoopVectorPreHeader,
8532                                EPI.MainLoopIterationCountCheck);
8533 
8534   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8535       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8536 
8537   if (EPI.SCEVSafetyCheck)
8538     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8539         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8540   if (EPI.MemSafetyCheck)
8541     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8542         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8543 
8544   DT->changeImmediateDominator(
8545       VecEpilogueIterationCountCheck,
8546       VecEpilogueIterationCountCheck->getSinglePredecessor());
8547 
8548   DT->changeImmediateDominator(LoopScalarPreHeader,
8549                                EPI.EpilogueIterationCountCheck);
8550   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8551     // If there is an epilogue which must run, there's no edge from the
8552     // middle block to exit blocks  and thus no need to update the immediate
8553     // dominator of the exit blocks.
8554     DT->changeImmediateDominator(LoopExitBlock,
8555                                  EPI.EpilogueIterationCountCheck);
8556 
8557   // Keep track of bypass blocks, as they feed start values to the induction
8558   // phis in the scalar loop preheader.
8559   if (EPI.SCEVSafetyCheck)
8560     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8561   if (EPI.MemSafetyCheck)
8562     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8563   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8564 
8565   // Generate a resume induction for the vector epilogue and put it in the
8566   // vector epilogue preheader
8567   Type *IdxTy = Legal->getWidestInductionType();
8568   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8569                                          LoopVectorPreHeader->getFirstNonPHI());
8570   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8571   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8572                            EPI.MainLoopIterationCountCheck);
8573 
8574   // Generate the induction variable.
8575   OldInduction = Legal->getPrimaryInduction();
8576   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8577   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8578   Value *StartIdx = EPResumeVal;
8579   Induction =
8580       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8581                               getDebugLocFromInstOrOperands(OldInduction));
8582 
8583   // Generate induction resume values. These variables save the new starting
8584   // indexes for the scalar loop. They are used to test if there are any tail
8585   // iterations left once the vector loop has completed.
8586   // Note that when the vectorized epilogue is skipped due to iteration count
8587   // check, then the resume value for the induction variable comes from
8588   // the trip count of the main vector loop, hence passing the AdditionalBypass
8589   // argument.
8590   createInductionResumeValues(Lp, CountRoundDown,
8591                               {VecEpilogueIterationCountCheck,
8592                                EPI.VectorTripCount} /* AdditionalBypass */);
8593 
8594   AddRuntimeUnrollDisableMetaData(Lp);
8595   return completeLoopSkeleton(Lp, OrigLoopID);
8596 }
8597 
8598 BasicBlock *
8599 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8600     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8601 
8602   assert(EPI.TripCount &&
8603          "Expected trip count to have been safed in the first pass.");
8604   assert(
8605       (!isa<Instruction>(EPI.TripCount) ||
8606        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8607       "saved trip count does not dominate insertion point.");
8608   Value *TC = EPI.TripCount;
8609   IRBuilder<> Builder(Insert->getTerminator());
8610   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8611 
8612   // Generate code to check if the loop's trip count is less than VF * UF of the
8613   // vector epilogue loop.
8614   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8615       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8616 
8617   Value *CheckMinIters = Builder.CreateICmp(
8618       P, Count,
8619       getRuntimeVF(Builder, Count->getType(), EPI.EpilogueVF * EPI.EpilogueUF),
8620       "min.epilog.iters.check");
8621 
8622   ReplaceInstWithInst(
8623       Insert->getTerminator(),
8624       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8625 
8626   LoopBypassBlocks.push_back(Insert);
8627   return Insert;
8628 }
8629 
8630 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8631   LLVM_DEBUG({
8632     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8633            << "Epilogue Loop VF:" << EPI.EpilogueVF
8634            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8635   });
8636 }
8637 
8638 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8639   DEBUG_WITH_TYPE(VerboseDebug, {
8640     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8641   });
8642 }
8643 
8644 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8645     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8646   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8647   bool PredicateAtRangeStart = Predicate(Range.Start);
8648 
8649   for (ElementCount TmpVF = Range.Start * 2;
8650        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8651     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8652       Range.End = TmpVF;
8653       break;
8654     }
8655 
8656   return PredicateAtRangeStart;
8657 }
8658 
8659 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8660 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8661 /// of VF's starting at a given VF and extending it as much as possible. Each
8662 /// vectorization decision can potentially shorten this sub-range during
8663 /// buildVPlan().
8664 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8665                                            ElementCount MaxVF) {
8666   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8667   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8668     VFRange SubRange = {VF, MaxVFPlusOne};
8669     VPlans.push_back(buildVPlan(SubRange));
8670     VF = SubRange.End;
8671   }
8672 }
8673 
8674 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8675                                          VPlanPtr &Plan) {
8676   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8677 
8678   // Look for cached value.
8679   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8680   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8681   if (ECEntryIt != EdgeMaskCache.end())
8682     return ECEntryIt->second;
8683 
8684   VPValue *SrcMask = createBlockInMask(Src, Plan);
8685 
8686   // The terminator has to be a branch inst!
8687   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8688   assert(BI && "Unexpected terminator found");
8689 
8690   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8691     return EdgeMaskCache[Edge] = SrcMask;
8692 
8693   // If source is an exiting block, we know the exit edge is dynamically dead
8694   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8695   // adding uses of an otherwise potentially dead instruction.
8696   if (OrigLoop->isLoopExiting(Src))
8697     return EdgeMaskCache[Edge] = SrcMask;
8698 
8699   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8700   assert(EdgeMask && "No Edge Mask found for condition");
8701 
8702   if (BI->getSuccessor(0) != Dst)
8703     EdgeMask = Builder.createNot(EdgeMask);
8704 
8705   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8706     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8707     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8708     // The select version does not introduce new UB if SrcMask is false and
8709     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8710     VPValue *False = Plan->getOrAddVPValue(
8711         ConstantInt::getFalse(BI->getCondition()->getType()));
8712     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8713   }
8714 
8715   return EdgeMaskCache[Edge] = EdgeMask;
8716 }
8717 
8718 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8719   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8720 
8721   // Look for cached value.
8722   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8723   if (BCEntryIt != BlockMaskCache.end())
8724     return BCEntryIt->second;
8725 
8726   // All-one mask is modelled as no-mask following the convention for masked
8727   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8728   VPValue *BlockMask = nullptr;
8729 
8730   if (OrigLoop->getHeader() == BB) {
8731     if (!CM.blockNeedsPredication(BB))
8732       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8733 
8734     // Create the block in mask as the first non-phi instruction in the block.
8735     VPBuilder::InsertPointGuard Guard(Builder);
8736     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8737     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8738 
8739     // Introduce the early-exit compare IV <= BTC to form header block mask.
8740     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8741     // Start by constructing the desired canonical IV.
8742     VPValue *IV = nullptr;
8743     if (Legal->getPrimaryInduction())
8744       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8745     else {
8746       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8747       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8748       IV = IVRecipe->getVPSingleValue();
8749     }
8750     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8751     bool TailFolded = !CM.isScalarEpilogueAllowed();
8752 
8753     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8754       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8755       // as a second argument, we only pass the IV here and extract the
8756       // tripcount from the transform state where codegen of the VP instructions
8757       // happen.
8758       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8759     } else {
8760       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8761     }
8762     return BlockMaskCache[BB] = BlockMask;
8763   }
8764 
8765   // This is the block mask. We OR all incoming edges.
8766   for (auto *Predecessor : predecessors(BB)) {
8767     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8768     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8769       return BlockMaskCache[BB] = EdgeMask;
8770 
8771     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8772       BlockMask = EdgeMask;
8773       continue;
8774     }
8775 
8776     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8777   }
8778 
8779   return BlockMaskCache[BB] = BlockMask;
8780 }
8781 
8782 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8783                                                 ArrayRef<VPValue *> Operands,
8784                                                 VFRange &Range,
8785                                                 VPlanPtr &Plan) {
8786   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8787          "Must be called with either a load or store");
8788 
8789   auto willWiden = [&](ElementCount VF) -> bool {
8790     if (VF.isScalar())
8791       return false;
8792     LoopVectorizationCostModel::InstWidening Decision =
8793         CM.getWideningDecision(I, VF);
8794     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8795            "CM decision should be taken at this point.");
8796     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8797       return true;
8798     if (CM.isScalarAfterVectorization(I, VF) ||
8799         CM.isProfitableToScalarize(I, VF))
8800       return false;
8801     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8802   };
8803 
8804   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8805     return nullptr;
8806 
8807   VPValue *Mask = nullptr;
8808   if (Legal->isMaskRequired(I))
8809     Mask = createBlockInMask(I->getParent(), Plan);
8810 
8811   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8812     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8813 
8814   StoreInst *Store = cast<StoreInst>(I);
8815   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8816                                             Mask);
8817 }
8818 
8819 VPWidenIntOrFpInductionRecipe *
8820 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8821                                            ArrayRef<VPValue *> Operands) const {
8822   // Check if this is an integer or fp induction. If so, build the recipe that
8823   // produces its scalar and vector values.
8824   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8825   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8826       II.getKind() == InductionDescriptor::IK_FpInduction) {
8827     assert(II.getStartValue() ==
8828            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8829     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8830     return new VPWidenIntOrFpInductionRecipe(
8831         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8832   }
8833 
8834   return nullptr;
8835 }
8836 
8837 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8838     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8839     VPlan &Plan) const {
8840   // Optimize the special case where the source is a constant integer
8841   // induction variable. Notice that we can only optimize the 'trunc' case
8842   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8843   // (c) other casts depend on pointer size.
8844 
8845   // Determine whether \p K is a truncation based on an induction variable that
8846   // can be optimized.
8847   auto isOptimizableIVTruncate =
8848       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8849     return [=](ElementCount VF) -> bool {
8850       return CM.isOptimizableIVTruncate(K, VF);
8851     };
8852   };
8853 
8854   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8855           isOptimizableIVTruncate(I), Range)) {
8856 
8857     InductionDescriptor II =
8858         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8859     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8860     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8861                                              Start, nullptr, I);
8862   }
8863   return nullptr;
8864 }
8865 
8866 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8867                                                 ArrayRef<VPValue *> Operands,
8868                                                 VPlanPtr &Plan) {
8869   // If all incoming values are equal, the incoming VPValue can be used directly
8870   // instead of creating a new VPBlendRecipe.
8871   VPValue *FirstIncoming = Operands[0];
8872   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8873         return FirstIncoming == Inc;
8874       })) {
8875     return Operands[0];
8876   }
8877 
8878   // We know that all PHIs in non-header blocks are converted into selects, so
8879   // we don't have to worry about the insertion order and we can just use the
8880   // builder. At this point we generate the predication tree. There may be
8881   // duplications since this is a simple recursive scan, but future
8882   // optimizations will clean it up.
8883   SmallVector<VPValue *, 2> OperandsWithMask;
8884   unsigned NumIncoming = Phi->getNumIncomingValues();
8885 
8886   for (unsigned In = 0; In < NumIncoming; In++) {
8887     VPValue *EdgeMask =
8888       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8889     assert((EdgeMask || NumIncoming == 1) &&
8890            "Multiple predecessors with one having a full mask");
8891     OperandsWithMask.push_back(Operands[In]);
8892     if (EdgeMask)
8893       OperandsWithMask.push_back(EdgeMask);
8894   }
8895   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8896 }
8897 
8898 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8899                                                    ArrayRef<VPValue *> Operands,
8900                                                    VFRange &Range) const {
8901 
8902   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8903       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8904       Range);
8905 
8906   if (IsPredicated)
8907     return nullptr;
8908 
8909   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8910   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8911              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8912              ID == Intrinsic::pseudoprobe ||
8913              ID == Intrinsic::experimental_noalias_scope_decl))
8914     return nullptr;
8915 
8916   auto willWiden = [&](ElementCount VF) -> bool {
8917     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8918     // The following case may be scalarized depending on the VF.
8919     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8920     // version of the instruction.
8921     // Is it beneficial to perform intrinsic call compared to lib call?
8922     bool NeedToScalarize = false;
8923     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8924     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8925     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8926     return UseVectorIntrinsic || !NeedToScalarize;
8927   };
8928 
8929   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8930     return nullptr;
8931 
8932   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8933   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8934 }
8935 
8936 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8937   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8938          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8939   // Instruction should be widened, unless it is scalar after vectorization,
8940   // scalarization is profitable or it is predicated.
8941   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8942     return CM.isScalarAfterVectorization(I, VF) ||
8943            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8944   };
8945   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8946                                                              Range);
8947 }
8948 
8949 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8950                                            ArrayRef<VPValue *> Operands) const {
8951   auto IsVectorizableOpcode = [](unsigned Opcode) {
8952     switch (Opcode) {
8953     case Instruction::Add:
8954     case Instruction::And:
8955     case Instruction::AShr:
8956     case Instruction::BitCast:
8957     case Instruction::FAdd:
8958     case Instruction::FCmp:
8959     case Instruction::FDiv:
8960     case Instruction::FMul:
8961     case Instruction::FNeg:
8962     case Instruction::FPExt:
8963     case Instruction::FPToSI:
8964     case Instruction::FPToUI:
8965     case Instruction::FPTrunc:
8966     case Instruction::FRem:
8967     case Instruction::FSub:
8968     case Instruction::ICmp:
8969     case Instruction::IntToPtr:
8970     case Instruction::LShr:
8971     case Instruction::Mul:
8972     case Instruction::Or:
8973     case Instruction::PtrToInt:
8974     case Instruction::SDiv:
8975     case Instruction::Select:
8976     case Instruction::SExt:
8977     case Instruction::Shl:
8978     case Instruction::SIToFP:
8979     case Instruction::SRem:
8980     case Instruction::Sub:
8981     case Instruction::Trunc:
8982     case Instruction::UDiv:
8983     case Instruction::UIToFP:
8984     case Instruction::URem:
8985     case Instruction::Xor:
8986     case Instruction::ZExt:
8987       return true;
8988     }
8989     return false;
8990   };
8991 
8992   if (!IsVectorizableOpcode(I->getOpcode()))
8993     return nullptr;
8994 
8995   // Success: widen this instruction.
8996   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8997 }
8998 
8999 void VPRecipeBuilder::fixHeaderPhis() {
9000   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
9001   for (VPWidenPHIRecipe *R : PhisToFix) {
9002     auto *PN = cast<PHINode>(R->getUnderlyingValue());
9003     VPRecipeBase *IncR =
9004         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
9005     R->addOperand(IncR->getVPSingleValue());
9006   }
9007 }
9008 
9009 VPBasicBlock *VPRecipeBuilder::handleReplication(
9010     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
9011     VPlanPtr &Plan) {
9012   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
9013       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
9014       Range);
9015 
9016   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
9017       [&](ElementCount VF) { return CM.isPredicatedInst(I); }, Range);
9018 
9019   // Even if the instruction is not marked as uniform, there are certain
9020   // intrinsic calls that can be effectively treated as such, so we check for
9021   // them here. Conservatively, we only do this for scalable vectors, since
9022   // for fixed-width VFs we can always fall back on full scalarization.
9023   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
9024     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
9025     case Intrinsic::assume:
9026     case Intrinsic::lifetime_start:
9027     case Intrinsic::lifetime_end:
9028       // For scalable vectors if one of the operands is variant then we still
9029       // want to mark as uniform, which will generate one instruction for just
9030       // the first lane of the vector. We can't scalarize the call in the same
9031       // way as for fixed-width vectors because we don't know how many lanes
9032       // there are.
9033       //
9034       // The reasons for doing it this way for scalable vectors are:
9035       //   1. For the assume intrinsic generating the instruction for the first
9036       //      lane is still be better than not generating any at all. For
9037       //      example, the input may be a splat across all lanes.
9038       //   2. For the lifetime start/end intrinsics the pointer operand only
9039       //      does anything useful when the input comes from a stack object,
9040       //      which suggests it should always be uniform. For non-stack objects
9041       //      the effect is to poison the object, which still allows us to
9042       //      remove the call.
9043       IsUniform = true;
9044       break;
9045     default:
9046       break;
9047     }
9048   }
9049 
9050   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
9051                                        IsUniform, IsPredicated);
9052   setRecipe(I, Recipe);
9053   Plan->addVPValue(I, Recipe);
9054 
9055   // Find if I uses a predicated instruction. If so, it will use its scalar
9056   // value. Avoid hoisting the insert-element which packs the scalar value into
9057   // a vector value, as that happens iff all users use the vector value.
9058   for (VPValue *Op : Recipe->operands()) {
9059     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
9060     if (!PredR)
9061       continue;
9062     auto *RepR =
9063         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
9064     assert(RepR->isPredicated() &&
9065            "expected Replicate recipe to be predicated");
9066     RepR->setAlsoPack(false);
9067   }
9068 
9069   // Finalize the recipe for Instr, first if it is not predicated.
9070   if (!IsPredicated) {
9071     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
9072     VPBB->appendRecipe(Recipe);
9073     return VPBB;
9074   }
9075   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
9076   assert(VPBB->getSuccessors().empty() &&
9077          "VPBB has successors when handling predicated replication.");
9078   // Record predicated instructions for above packing optimizations.
9079   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
9080   VPBlockUtils::insertBlockAfter(Region, VPBB);
9081   auto *RegSucc = new VPBasicBlock();
9082   VPBlockUtils::insertBlockAfter(RegSucc, Region);
9083   return RegSucc;
9084 }
9085 
9086 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
9087                                                       VPRecipeBase *PredRecipe,
9088                                                       VPlanPtr &Plan) {
9089   // Instructions marked for predication are replicated and placed under an
9090   // if-then construct to prevent side-effects.
9091 
9092   // Generate recipes to compute the block mask for this region.
9093   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
9094 
9095   // Build the triangular if-then region.
9096   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
9097   assert(Instr->getParent() && "Predicated instruction not in any basic block");
9098   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
9099   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
9100   auto *PHIRecipe = Instr->getType()->isVoidTy()
9101                         ? nullptr
9102                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
9103   if (PHIRecipe) {
9104     Plan->removeVPValueFor(Instr);
9105     Plan->addVPValue(Instr, PHIRecipe);
9106   }
9107   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
9108   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
9109   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
9110 
9111   // Note: first set Entry as region entry and then connect successors starting
9112   // from it in order, to propagate the "parent" of each VPBasicBlock.
9113   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
9114   VPBlockUtils::connectBlocks(Pred, Exit);
9115 
9116   return Region;
9117 }
9118 
9119 VPRecipeOrVPValueTy
9120 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
9121                                         ArrayRef<VPValue *> Operands,
9122                                         VFRange &Range, VPlanPtr &Plan) {
9123   // First, check for specific widening recipes that deal with calls, memory
9124   // operations, inductions and Phi nodes.
9125   if (auto *CI = dyn_cast<CallInst>(Instr))
9126     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
9127 
9128   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
9129     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
9130 
9131   VPRecipeBase *Recipe;
9132   if (auto Phi = dyn_cast<PHINode>(Instr)) {
9133     if (Phi->getParent() != OrigLoop->getHeader())
9134       return tryToBlend(Phi, Operands, Plan);
9135     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
9136       return toVPRecipeResult(Recipe);
9137 
9138     VPWidenPHIRecipe *PhiRecipe = nullptr;
9139     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
9140       VPValue *StartV = Operands[0];
9141       if (Legal->isReductionVariable(Phi)) {
9142         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9143         assert(RdxDesc.getRecurrenceStartValue() ==
9144                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
9145         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
9146                                              CM.isInLoopReduction(Phi),
9147                                              CM.useOrderedReductions(RdxDesc));
9148       } else {
9149         PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
9150       }
9151 
9152       // Record the incoming value from the backedge, so we can add the incoming
9153       // value from the backedge after all recipes have been created.
9154       recordRecipeOf(cast<Instruction>(
9155           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
9156       PhisToFix.push_back(PhiRecipe);
9157     } else {
9158       // TODO: record start and backedge value for remaining pointer induction
9159       // phis.
9160       assert(Phi->getType()->isPointerTy() &&
9161              "only pointer phis should be handled here");
9162       PhiRecipe = new VPWidenPHIRecipe(Phi);
9163     }
9164 
9165     return toVPRecipeResult(PhiRecipe);
9166   }
9167 
9168   if (isa<TruncInst>(Instr) &&
9169       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
9170                                                Range, *Plan)))
9171     return toVPRecipeResult(Recipe);
9172 
9173   if (!shouldWiden(Instr, Range))
9174     return nullptr;
9175 
9176   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
9177     return toVPRecipeResult(new VPWidenGEPRecipe(
9178         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
9179 
9180   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
9181     bool InvariantCond =
9182         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
9183     return toVPRecipeResult(new VPWidenSelectRecipe(
9184         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
9185   }
9186 
9187   return toVPRecipeResult(tryToWiden(Instr, Operands));
9188 }
9189 
9190 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
9191                                                         ElementCount MaxVF) {
9192   assert(OrigLoop->isInnermost() && "Inner loop expected.");
9193 
9194   // Collect instructions from the original loop that will become trivially dead
9195   // in the vectorized loop. We don't need to vectorize these instructions. For
9196   // example, original induction update instructions can become dead because we
9197   // separately emit induction "steps" when generating code for the new loop.
9198   // Similarly, we create a new latch condition when setting up the structure
9199   // of the new loop, so the old one can become dead.
9200   SmallPtrSet<Instruction *, 4> DeadInstructions;
9201   collectTriviallyDeadInstructions(DeadInstructions);
9202 
9203   // Add assume instructions we need to drop to DeadInstructions, to prevent
9204   // them from being added to the VPlan.
9205   // TODO: We only need to drop assumes in blocks that get flattend. If the
9206   // control flow is preserved, we should keep them.
9207   auto &ConditionalAssumes = Legal->getConditionalAssumes();
9208   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
9209 
9210   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
9211   // Dead instructions do not need sinking. Remove them from SinkAfter.
9212   for (Instruction *I : DeadInstructions)
9213     SinkAfter.erase(I);
9214 
9215   // Cannot sink instructions after dead instructions (there won't be any
9216   // recipes for them). Instead, find the first non-dead previous instruction.
9217   for (auto &P : Legal->getSinkAfter()) {
9218     Instruction *SinkTarget = P.second;
9219     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
9220     (void)FirstInst;
9221     while (DeadInstructions.contains(SinkTarget)) {
9222       assert(
9223           SinkTarget != FirstInst &&
9224           "Must find a live instruction (at least the one feeding the "
9225           "first-order recurrence PHI) before reaching beginning of the block");
9226       SinkTarget = SinkTarget->getPrevNode();
9227       assert(SinkTarget != P.first &&
9228              "sink source equals target, no sinking required");
9229     }
9230     P.second = SinkTarget;
9231   }
9232 
9233   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9234   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9235     VFRange SubRange = {VF, MaxVFPlusOne};
9236     VPlans.push_back(
9237         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9238     VF = SubRange.End;
9239   }
9240 }
9241 
9242 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9243     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9244     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9245 
9246   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9247 
9248   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9249 
9250   // ---------------------------------------------------------------------------
9251   // Pre-construction: record ingredients whose recipes we'll need to further
9252   // process after constructing the initial VPlan.
9253   // ---------------------------------------------------------------------------
9254 
9255   // Mark instructions we'll need to sink later and their targets as
9256   // ingredients whose recipe we'll need to record.
9257   for (auto &Entry : SinkAfter) {
9258     RecipeBuilder.recordRecipeOf(Entry.first);
9259     RecipeBuilder.recordRecipeOf(Entry.second);
9260   }
9261   for (auto &Reduction : CM.getInLoopReductionChains()) {
9262     PHINode *Phi = Reduction.first;
9263     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9264     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9265 
9266     RecipeBuilder.recordRecipeOf(Phi);
9267     for (auto &R : ReductionOperations) {
9268       RecipeBuilder.recordRecipeOf(R);
9269       // For min/max reducitons, where we have a pair of icmp/select, we also
9270       // need to record the ICmp recipe, so it can be removed later.
9271       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9272              "Only min/max recurrences allowed for inloop reductions");
9273       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9274         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9275     }
9276   }
9277 
9278   // For each interleave group which is relevant for this (possibly trimmed)
9279   // Range, add it to the set of groups to be later applied to the VPlan and add
9280   // placeholders for its members' Recipes which we'll be replacing with a
9281   // single VPInterleaveRecipe.
9282   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9283     auto applyIG = [IG, this](ElementCount VF) -> bool {
9284       return (VF.isVector() && // Query is illegal for VF == 1
9285               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9286                   LoopVectorizationCostModel::CM_Interleave);
9287     };
9288     if (!getDecisionAndClampRange(applyIG, Range))
9289       continue;
9290     InterleaveGroups.insert(IG);
9291     for (unsigned i = 0; i < IG->getFactor(); i++)
9292       if (Instruction *Member = IG->getMember(i))
9293         RecipeBuilder.recordRecipeOf(Member);
9294   };
9295 
9296   // ---------------------------------------------------------------------------
9297   // Build initial VPlan: Scan the body of the loop in a topological order to
9298   // visit each basic block after having visited its predecessor basic blocks.
9299   // ---------------------------------------------------------------------------
9300 
9301   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
9302   auto Plan = std::make_unique<VPlan>();
9303   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
9304   Plan->setEntry(VPBB);
9305 
9306   // Scan the body of the loop in a topological order to visit each basic block
9307   // after having visited its predecessor basic blocks.
9308   LoopBlocksDFS DFS(OrigLoop);
9309   DFS.perform(LI);
9310 
9311   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9312     // Relevant instructions from basic block BB will be grouped into VPRecipe
9313     // ingredients and fill a new VPBasicBlock.
9314     unsigned VPBBsForBB = 0;
9315     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9316     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9317     VPBB = FirstVPBBForBB;
9318     Builder.setInsertPoint(VPBB);
9319 
9320     // Introduce each ingredient into VPlan.
9321     // TODO: Model and preserve debug instrinsics in VPlan.
9322     for (Instruction &I : BB->instructionsWithoutDebug()) {
9323       Instruction *Instr = &I;
9324 
9325       // First filter out irrelevant instructions, to ensure no recipes are
9326       // built for them.
9327       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9328         continue;
9329 
9330       SmallVector<VPValue *, 4> Operands;
9331       auto *Phi = dyn_cast<PHINode>(Instr);
9332       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9333         Operands.push_back(Plan->getOrAddVPValue(
9334             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9335       } else {
9336         auto OpRange = Plan->mapToVPValues(Instr->operands());
9337         Operands = {OpRange.begin(), OpRange.end()};
9338       }
9339       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9340               Instr, Operands, Range, Plan)) {
9341         // If Instr can be simplified to an existing VPValue, use it.
9342         if (RecipeOrValue.is<VPValue *>()) {
9343           auto *VPV = RecipeOrValue.get<VPValue *>();
9344           Plan->addVPValue(Instr, VPV);
9345           // If the re-used value is a recipe, register the recipe for the
9346           // instruction, in case the recipe for Instr needs to be recorded.
9347           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9348             RecipeBuilder.setRecipe(Instr, R);
9349           continue;
9350         }
9351         // Otherwise, add the new recipe.
9352         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9353         for (auto *Def : Recipe->definedValues()) {
9354           auto *UV = Def->getUnderlyingValue();
9355           Plan->addVPValue(UV, Def);
9356         }
9357 
9358         RecipeBuilder.setRecipe(Instr, Recipe);
9359         VPBB->appendRecipe(Recipe);
9360         continue;
9361       }
9362 
9363       // Otherwise, if all widening options failed, Instruction is to be
9364       // replicated. This may create a successor for VPBB.
9365       VPBasicBlock *NextVPBB =
9366           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9367       if (NextVPBB != VPBB) {
9368         VPBB = NextVPBB;
9369         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9370                                     : "");
9371       }
9372     }
9373   }
9374 
9375   RecipeBuilder.fixHeaderPhis();
9376 
9377   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
9378   // may also be empty, such as the last one VPBB, reflecting original
9379   // basic-blocks with no recipes.
9380   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9381   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9382   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9383   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9384   delete PreEntry;
9385 
9386   // ---------------------------------------------------------------------------
9387   // Transform initial VPlan: Apply previously taken decisions, in order, to
9388   // bring the VPlan to its final state.
9389   // ---------------------------------------------------------------------------
9390 
9391   // Apply Sink-After legal constraints.
9392   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9393     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9394     if (Region && Region->isReplicator()) {
9395       assert(Region->getNumSuccessors() == 1 &&
9396              Region->getNumPredecessors() == 1 && "Expected SESE region!");
9397       assert(R->getParent()->size() == 1 &&
9398              "A recipe in an original replicator region must be the only "
9399              "recipe in its block");
9400       return Region;
9401     }
9402     return nullptr;
9403   };
9404   for (auto &Entry : SinkAfter) {
9405     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9406     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9407 
9408     auto *TargetRegion = GetReplicateRegion(Target);
9409     auto *SinkRegion = GetReplicateRegion(Sink);
9410     if (!SinkRegion) {
9411       // If the sink source is not a replicate region, sink the recipe directly.
9412       if (TargetRegion) {
9413         // The target is in a replication region, make sure to move Sink to
9414         // the block after it, not into the replication region itself.
9415         VPBasicBlock *NextBlock =
9416             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9417         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9418       } else
9419         Sink->moveAfter(Target);
9420       continue;
9421     }
9422 
9423     // The sink source is in a replicate region. Unhook the region from the CFG.
9424     auto *SinkPred = SinkRegion->getSinglePredecessor();
9425     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9426     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9427     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9428     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9429 
9430     if (TargetRegion) {
9431       // The target recipe is also in a replicate region, move the sink region
9432       // after the target region.
9433       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9434       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9435       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9436       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9437     } else {
9438       // The sink source is in a replicate region, we need to move the whole
9439       // replicate region, which should only contain a single recipe in the
9440       // main block.
9441       auto *SplitBlock =
9442           Target->getParent()->splitAt(std::next(Target->getIterator()));
9443 
9444       auto *SplitPred = SplitBlock->getSinglePredecessor();
9445 
9446       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9447       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9448       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9449       if (VPBB == SplitPred)
9450         VPBB = SplitBlock;
9451     }
9452   }
9453 
9454   // Adjust the recipes for any inloop reductions.
9455   adjustRecipesForReductions(VPBB, Plan, RecipeBuilder, Range.Start);
9456 
9457   // Introduce a recipe to combine the incoming and previous values of a
9458   // first-order recurrence.
9459   for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9460     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
9461     if (!RecurPhi)
9462       continue;
9463 
9464     auto *RecurSplice = cast<VPInstruction>(
9465         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
9466                              {RecurPhi, RecurPhi->getBackedgeValue()}));
9467 
9468     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
9469     if (auto *Region = GetReplicateRegion(PrevRecipe)) {
9470       VPBasicBlock *Succ = cast<VPBasicBlock>(Region->getSingleSuccessor());
9471       RecurSplice->moveBefore(*Succ, Succ->getFirstNonPhi());
9472     } else
9473       RecurSplice->moveAfter(PrevRecipe);
9474     RecurPhi->replaceAllUsesWith(RecurSplice);
9475     // Set the first operand of RecurSplice to RecurPhi again, after replacing
9476     // all users.
9477     RecurSplice->setOperand(0, RecurPhi);
9478   }
9479 
9480   // Interleave memory: for each Interleave Group we marked earlier as relevant
9481   // for this VPlan, replace the Recipes widening its memory instructions with a
9482   // single VPInterleaveRecipe at its insertion point.
9483   for (auto IG : InterleaveGroups) {
9484     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9485         RecipeBuilder.getRecipe(IG->getInsertPos()));
9486     SmallVector<VPValue *, 4> StoredValues;
9487     for (unsigned i = 0; i < IG->getFactor(); ++i)
9488       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9489         auto *StoreR =
9490             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9491         StoredValues.push_back(StoreR->getStoredValue());
9492       }
9493 
9494     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9495                                         Recipe->getMask());
9496     VPIG->insertBefore(Recipe);
9497     unsigned J = 0;
9498     for (unsigned i = 0; i < IG->getFactor(); ++i)
9499       if (Instruction *Member = IG->getMember(i)) {
9500         if (!Member->getType()->isVoidTy()) {
9501           VPValue *OriginalV = Plan->getVPValue(Member);
9502           Plan->removeVPValueFor(Member);
9503           Plan->addVPValue(Member, VPIG->getVPValue(J));
9504           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9505           J++;
9506         }
9507         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9508       }
9509   }
9510 
9511   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9512   // in ways that accessing values using original IR values is incorrect.
9513   Plan->disableValue2VPValue();
9514 
9515   VPlanTransforms::sinkScalarOperands(*Plan);
9516   VPlanTransforms::mergeReplicateRegions(*Plan);
9517 
9518   std::string PlanName;
9519   raw_string_ostream RSO(PlanName);
9520   ElementCount VF = Range.Start;
9521   Plan->addVF(VF);
9522   RSO << "Initial VPlan for VF={" << VF;
9523   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9524     Plan->addVF(VF);
9525     RSO << "," << VF;
9526   }
9527   RSO << "},UF>=1";
9528   RSO.flush();
9529   Plan->setName(PlanName);
9530 
9531   return Plan;
9532 }
9533 
9534 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9535   // Outer loop handling: They may require CFG and instruction level
9536   // transformations before even evaluating whether vectorization is profitable.
9537   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9538   // the vectorization pipeline.
9539   assert(!OrigLoop->isInnermost());
9540   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9541 
9542   // Create new empty VPlan
9543   auto Plan = std::make_unique<VPlan>();
9544 
9545   // Build hierarchical CFG
9546   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9547   HCFGBuilder.buildHierarchicalCFG();
9548 
9549   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9550        VF *= 2)
9551     Plan->addVF(VF);
9552 
9553   if (EnableVPlanPredication) {
9554     VPlanPredicator VPP(*Plan);
9555     VPP.predicate();
9556 
9557     // Avoid running transformation to recipes until masked code generation in
9558     // VPlan-native path is in place.
9559     return Plan;
9560   }
9561 
9562   SmallPtrSet<Instruction *, 1> DeadInstructions;
9563   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9564                                              Legal->getInductionVars(),
9565                                              DeadInstructions, *PSE.getSE());
9566   return Plan;
9567 }
9568 
9569 // Adjust the recipes for reductions. For in-loop reductions the chain of
9570 // instructions leading from the loop exit instr to the phi need to be converted
9571 // to reductions, with one operand being vector and the other being the scalar
9572 // reduction chain. For other reductions, a select is introduced between the phi
9573 // and live-out recipes when folding the tail.
9574 void LoopVectorizationPlanner::adjustRecipesForReductions(
9575     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9576     ElementCount MinVF) {
9577   for (auto &Reduction : CM.getInLoopReductionChains()) {
9578     PHINode *Phi = Reduction.first;
9579     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9580     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9581 
9582     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9583       continue;
9584 
9585     // ReductionOperations are orders top-down from the phi's use to the
9586     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9587     // which of the two operands will remain scalar and which will be reduced.
9588     // For minmax the chain will be the select instructions.
9589     Instruction *Chain = Phi;
9590     for (Instruction *R : ReductionOperations) {
9591       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9592       RecurKind Kind = RdxDesc.getRecurrenceKind();
9593 
9594       VPValue *ChainOp = Plan->getVPValue(Chain);
9595       unsigned FirstOpId;
9596       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9597              "Only min/max recurrences allowed for inloop reductions");
9598       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9599         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9600                "Expected to replace a VPWidenSelectSC");
9601         FirstOpId = 1;
9602       } else {
9603         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe)) &&
9604                "Expected to replace a VPWidenSC");
9605         FirstOpId = 0;
9606       }
9607       unsigned VecOpId =
9608           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9609       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9610 
9611       auto *CondOp = CM.foldTailByMasking()
9612                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9613                          : nullptr;
9614       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9615           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9616       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9617       Plan->removeVPValueFor(R);
9618       Plan->addVPValue(R, RedRecipe);
9619       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9620       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9621       WidenRecipe->eraseFromParent();
9622 
9623       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9624         VPRecipeBase *CompareRecipe =
9625             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9626         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9627                "Expected to replace a VPWidenSC");
9628         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9629                "Expected no remaining users");
9630         CompareRecipe->eraseFromParent();
9631       }
9632       Chain = R;
9633     }
9634   }
9635 
9636   // If tail is folded by masking, introduce selects between the phi
9637   // and the live-out instruction of each reduction, at the end of the latch.
9638   if (CM.foldTailByMasking()) {
9639     for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9640       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9641       if (!PhiR || PhiR->isInLoop())
9642         continue;
9643       Builder.setInsertPoint(LatchVPBB);
9644       VPValue *Cond =
9645           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9646       VPValue *Red = PhiR->getBackedgeValue();
9647       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9648     }
9649   }
9650 }
9651 
9652 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9653 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9654                                VPSlotTracker &SlotTracker) const {
9655   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9656   IG->getInsertPos()->printAsOperand(O, false);
9657   O << ", ";
9658   getAddr()->printAsOperand(O, SlotTracker);
9659   VPValue *Mask = getMask();
9660   if (Mask) {
9661     O << ", ";
9662     Mask->printAsOperand(O, SlotTracker);
9663   }
9664 
9665   unsigned OpIdx = 0;
9666   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9667     if (!IG->getMember(i))
9668       continue;
9669     if (getNumStoreOperands() > 0) {
9670       O << "\n" << Indent << "  store ";
9671       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9672       O << " to index " << i;
9673     } else {
9674       O << "\n" << Indent << "  ";
9675       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9676       O << " = load from index " << i;
9677     }
9678     ++OpIdx;
9679   }
9680 }
9681 #endif
9682 
9683 void VPWidenCallRecipe::execute(VPTransformState &State) {
9684   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9685                                   *this, State);
9686 }
9687 
9688 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9689   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9690                                     this, *this, InvariantCond, State);
9691 }
9692 
9693 void VPWidenRecipe::execute(VPTransformState &State) {
9694   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9695 }
9696 
9697 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9698   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9699                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9700                       IsIndexLoopInvariant, State);
9701 }
9702 
9703 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9704   assert(!State.Instance && "Int or FP induction being replicated.");
9705   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9706                                    getTruncInst(), getVPValue(0),
9707                                    getCastValue(), State);
9708 }
9709 
9710 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9711   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9712                                  State);
9713 }
9714 
9715 void VPBlendRecipe::execute(VPTransformState &State) {
9716   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9717   // We know that all PHIs in non-header blocks are converted into
9718   // selects, so we don't have to worry about the insertion order and we
9719   // can just use the builder.
9720   // At this point we generate the predication tree. There may be
9721   // duplications since this is a simple recursive scan, but future
9722   // optimizations will clean it up.
9723 
9724   unsigned NumIncoming = getNumIncomingValues();
9725 
9726   // Generate a sequence of selects of the form:
9727   // SELECT(Mask3, In3,
9728   //        SELECT(Mask2, In2,
9729   //               SELECT(Mask1, In1,
9730   //                      In0)))
9731   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9732   // are essentially undef are taken from In0.
9733   InnerLoopVectorizer::VectorParts Entry(State.UF);
9734   for (unsigned In = 0; In < NumIncoming; ++In) {
9735     for (unsigned Part = 0; Part < State.UF; ++Part) {
9736       // We might have single edge PHIs (blocks) - use an identity
9737       // 'select' for the first PHI operand.
9738       Value *In0 = State.get(getIncomingValue(In), Part);
9739       if (In == 0)
9740         Entry[Part] = In0; // Initialize with the first incoming value.
9741       else {
9742         // Select between the current value and the previous incoming edge
9743         // based on the incoming mask.
9744         Value *Cond = State.get(getMask(In), Part);
9745         Entry[Part] =
9746             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9747       }
9748     }
9749   }
9750   for (unsigned Part = 0; Part < State.UF; ++Part)
9751     State.set(this, Entry[Part], Part);
9752 }
9753 
9754 void VPInterleaveRecipe::execute(VPTransformState &State) {
9755   assert(!State.Instance && "Interleave group being replicated.");
9756   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9757                                       getStoredValues(), getMask());
9758 }
9759 
9760 void VPReductionRecipe::execute(VPTransformState &State) {
9761   assert(!State.Instance && "Reduction being replicated.");
9762   Value *PrevInChain = State.get(getChainOp(), 0);
9763   for (unsigned Part = 0; Part < State.UF; ++Part) {
9764     RecurKind Kind = RdxDesc->getRecurrenceKind();
9765     bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9766     Value *NewVecOp = State.get(getVecOp(), Part);
9767     if (VPValue *Cond = getCondOp()) {
9768       Value *NewCond = State.get(Cond, Part);
9769       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9770       Value *Iden = RdxDesc->getRecurrenceIdentity(
9771           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9772       Value *IdenVec =
9773           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9774       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9775       NewVecOp = Select;
9776     }
9777     Value *NewRed;
9778     Value *NextInChain;
9779     if (IsOrdered) {
9780       if (State.VF.isVector())
9781         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9782                                         PrevInChain);
9783       else
9784         NewRed = State.Builder.CreateBinOp(
9785             (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(),
9786             PrevInChain, NewVecOp);
9787       PrevInChain = NewRed;
9788     } else {
9789       PrevInChain = State.get(getChainOp(), Part);
9790       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9791     }
9792     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9793       NextInChain =
9794           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9795                          NewRed, PrevInChain);
9796     } else if (IsOrdered)
9797       NextInChain = NewRed;
9798     else {
9799       NextInChain = State.Builder.CreateBinOp(
9800           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9801           PrevInChain);
9802     }
9803     State.set(this, NextInChain, Part);
9804   }
9805 }
9806 
9807 void VPReplicateRecipe::execute(VPTransformState &State) {
9808   if (State.Instance) { // Generate a single instance.
9809     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9810     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9811                                     *State.Instance, IsPredicated, State);
9812     // Insert scalar instance packing it into a vector.
9813     if (AlsoPack && State.VF.isVector()) {
9814       // If we're constructing lane 0, initialize to start from poison.
9815       if (State.Instance->Lane.isFirstLane()) {
9816         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9817         Value *Poison = PoisonValue::get(
9818             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9819         State.set(this, Poison, State.Instance->Part);
9820       }
9821       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9822     }
9823     return;
9824   }
9825 
9826   // Generate scalar instances for all VF lanes of all UF parts, unless the
9827   // instruction is uniform inwhich case generate only the first lane for each
9828   // of the UF parts.
9829   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9830   assert((!State.VF.isScalable() || IsUniform) &&
9831          "Can't scalarize a scalable vector");
9832   for (unsigned Part = 0; Part < State.UF; ++Part)
9833     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9834       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9835                                       VPIteration(Part, Lane), IsPredicated,
9836                                       State);
9837 }
9838 
9839 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9840   assert(State.Instance && "Branch on Mask works only on single instance.");
9841 
9842   unsigned Part = State.Instance->Part;
9843   unsigned Lane = State.Instance->Lane.getKnownLane();
9844 
9845   Value *ConditionBit = nullptr;
9846   VPValue *BlockInMask = getMask();
9847   if (BlockInMask) {
9848     ConditionBit = State.get(BlockInMask, Part);
9849     if (ConditionBit->getType()->isVectorTy())
9850       ConditionBit = State.Builder.CreateExtractElement(
9851           ConditionBit, State.Builder.getInt32(Lane));
9852   } else // Block in mask is all-one.
9853     ConditionBit = State.Builder.getTrue();
9854 
9855   // Replace the temporary unreachable terminator with a new conditional branch,
9856   // whose two destinations will be set later when they are created.
9857   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9858   assert(isa<UnreachableInst>(CurrentTerminator) &&
9859          "Expected to replace unreachable terminator with conditional branch.");
9860   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9861   CondBr->setSuccessor(0, nullptr);
9862   ReplaceInstWithInst(CurrentTerminator, CondBr);
9863 }
9864 
9865 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9866   assert(State.Instance && "Predicated instruction PHI works per instance.");
9867   Instruction *ScalarPredInst =
9868       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9869   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9870   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9871   assert(PredicatingBB && "Predicated block has no single predecessor.");
9872   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9873          "operand must be VPReplicateRecipe");
9874 
9875   // By current pack/unpack logic we need to generate only a single phi node: if
9876   // a vector value for the predicated instruction exists at this point it means
9877   // the instruction has vector users only, and a phi for the vector value is
9878   // needed. In this case the recipe of the predicated instruction is marked to
9879   // also do that packing, thereby "hoisting" the insert-element sequence.
9880   // Otherwise, a phi node for the scalar value is needed.
9881   unsigned Part = State.Instance->Part;
9882   if (State.hasVectorValue(getOperand(0), Part)) {
9883     Value *VectorValue = State.get(getOperand(0), Part);
9884     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9885     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9886     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9887     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9888     if (State.hasVectorValue(this, Part))
9889       State.reset(this, VPhi, Part);
9890     else
9891       State.set(this, VPhi, Part);
9892     // NOTE: Currently we need to update the value of the operand, so the next
9893     // predicated iteration inserts its generated value in the correct vector.
9894     State.reset(getOperand(0), VPhi, Part);
9895   } else {
9896     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9897     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9898     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9899                      PredicatingBB);
9900     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9901     if (State.hasScalarValue(this, *State.Instance))
9902       State.reset(this, Phi, *State.Instance);
9903     else
9904       State.set(this, Phi, *State.Instance);
9905     // NOTE: Currently we need to update the value of the operand, so the next
9906     // predicated iteration inserts its generated value in the correct vector.
9907     State.reset(getOperand(0), Phi, *State.Instance);
9908   }
9909 }
9910 
9911 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9912   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9913   State.ILV->vectorizeMemoryInstruction(
9914       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9915       StoredValue, getMask());
9916 }
9917 
9918 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9919 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9920 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9921 // for predication.
9922 static ScalarEpilogueLowering getScalarEpilogueLowering(
9923     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9924     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9925     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9926     LoopVectorizationLegality &LVL) {
9927   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9928   // don't look at hints or options, and don't request a scalar epilogue.
9929   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9930   // LoopAccessInfo (due to code dependency and not being able to reliably get
9931   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9932   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9933   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9934   // back to the old way and vectorize with versioning when forced. See D81345.)
9935   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9936                                                       PGSOQueryType::IRPass) &&
9937                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9938     return CM_ScalarEpilogueNotAllowedOptSize;
9939 
9940   // 2) If set, obey the directives
9941   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9942     switch (PreferPredicateOverEpilogue) {
9943     case PreferPredicateTy::ScalarEpilogue:
9944       return CM_ScalarEpilogueAllowed;
9945     case PreferPredicateTy::PredicateElseScalarEpilogue:
9946       return CM_ScalarEpilogueNotNeededUsePredicate;
9947     case PreferPredicateTy::PredicateOrDontVectorize:
9948       return CM_ScalarEpilogueNotAllowedUsePredicate;
9949     };
9950   }
9951 
9952   // 3) If set, obey the hints
9953   switch (Hints.getPredicate()) {
9954   case LoopVectorizeHints::FK_Enabled:
9955     return CM_ScalarEpilogueNotNeededUsePredicate;
9956   case LoopVectorizeHints::FK_Disabled:
9957     return CM_ScalarEpilogueAllowed;
9958   };
9959 
9960   // 4) if the TTI hook indicates this is profitable, request predication.
9961   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9962                                        LVL.getLAI()))
9963     return CM_ScalarEpilogueNotNeededUsePredicate;
9964 
9965   return CM_ScalarEpilogueAllowed;
9966 }
9967 
9968 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9969   // If Values have been set for this Def return the one relevant for \p Part.
9970   if (hasVectorValue(Def, Part))
9971     return Data.PerPartOutput[Def][Part];
9972 
9973   if (!hasScalarValue(Def, {Part, 0})) {
9974     Value *IRV = Def->getLiveInIRValue();
9975     Value *B = ILV->getBroadcastInstrs(IRV);
9976     set(Def, B, Part);
9977     return B;
9978   }
9979 
9980   Value *ScalarValue = get(Def, {Part, 0});
9981   // If we aren't vectorizing, we can just copy the scalar map values over
9982   // to the vector map.
9983   if (VF.isScalar()) {
9984     set(Def, ScalarValue, Part);
9985     return ScalarValue;
9986   }
9987 
9988   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9989   bool IsUniform = RepR && RepR->isUniform();
9990 
9991   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9992   // Check if there is a scalar value for the selected lane.
9993   if (!hasScalarValue(Def, {Part, LastLane})) {
9994     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9995     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9996            "unexpected recipe found to be invariant");
9997     IsUniform = true;
9998     LastLane = 0;
9999   }
10000 
10001   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10002   // Set the insert point after the last scalarized instruction or after the
10003   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10004   // will directly follow the scalar definitions.
10005   auto OldIP = Builder.saveIP();
10006   auto NewIP =
10007       isa<PHINode>(LastInst)
10008           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10009           : std::next(BasicBlock::iterator(LastInst));
10010   Builder.SetInsertPoint(&*NewIP);
10011 
10012   // However, if we are vectorizing, we need to construct the vector values.
10013   // If the value is known to be uniform after vectorization, we can just
10014   // broadcast the scalar value corresponding to lane zero for each unroll
10015   // iteration. Otherwise, we construct the vector values using
10016   // insertelement instructions. Since the resulting vectors are stored in
10017   // State, we will only generate the insertelements once.
10018   Value *VectorValue = nullptr;
10019   if (IsUniform) {
10020     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10021     set(Def, VectorValue, Part);
10022   } else {
10023     // Initialize packing with insertelements to start from undef.
10024     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10025     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10026     set(Def, Undef, Part);
10027     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10028       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10029     VectorValue = get(Def, Part);
10030   }
10031   Builder.restoreIP(OldIP);
10032   return VectorValue;
10033 }
10034 
10035 // Process the loop in the VPlan-native vectorization path. This path builds
10036 // VPlan upfront in the vectorization pipeline, which allows to apply
10037 // VPlan-to-VPlan transformations from the very beginning without modifying the
10038 // input LLVM IR.
10039 static bool processLoopInVPlanNativePath(
10040     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10041     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10042     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10043     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10044     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10045     LoopVectorizationRequirements &Requirements) {
10046 
10047   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10048     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10049     return false;
10050   }
10051   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10052   Function *F = L->getHeader()->getParent();
10053   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10054 
10055   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10056       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10057 
10058   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10059                                 &Hints, IAI);
10060   // Use the planner for outer loop vectorization.
10061   // TODO: CM is not used at this point inside the planner. Turn CM into an
10062   // optional argument if we don't need it in the future.
10063   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10064                                Requirements, ORE);
10065 
10066   // Get user vectorization factor.
10067   ElementCount UserVF = Hints.getWidth();
10068 
10069   CM.collectElementTypesForWidening();
10070 
10071   // Plan how to best vectorize, return the best VF and its cost.
10072   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10073 
10074   // If we are stress testing VPlan builds, do not attempt to generate vector
10075   // code. Masked vector code generation support will follow soon.
10076   // Also, do not attempt to vectorize if no vector code will be produced.
10077   if (VPlanBuildStressTest || EnableVPlanPredication ||
10078       VectorizationFactor::Disabled() == VF)
10079     return false;
10080 
10081   LVP.setBestPlan(VF.Width, 1);
10082 
10083   {
10084     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10085                              F->getParent()->getDataLayout());
10086     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10087                            &CM, BFI, PSI, Checks);
10088     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10089                       << L->getHeader()->getParent()->getName() << "\"\n");
10090     LVP.executePlan(LB, DT);
10091   }
10092 
10093   // Mark the loop as already vectorized to avoid vectorizing again.
10094   Hints.setAlreadyVectorized();
10095   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10096   return true;
10097 }
10098 
10099 // Emit a remark if there are stores to floats that required a floating point
10100 // extension. If the vectorized loop was generated with floating point there
10101 // will be a performance penalty from the conversion overhead and the change in
10102 // the vector width.
10103 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10104   SmallVector<Instruction *, 4> Worklist;
10105   for (BasicBlock *BB : L->getBlocks()) {
10106     for (Instruction &Inst : *BB) {
10107       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10108         if (S->getValueOperand()->getType()->isFloatTy())
10109           Worklist.push_back(S);
10110       }
10111     }
10112   }
10113 
10114   // Traverse the floating point stores upwards searching, for floating point
10115   // conversions.
10116   SmallPtrSet<const Instruction *, 4> Visited;
10117   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10118   while (!Worklist.empty()) {
10119     auto *I = Worklist.pop_back_val();
10120     if (!L->contains(I))
10121       continue;
10122     if (!Visited.insert(I).second)
10123       continue;
10124 
10125     // Emit a remark if the floating point store required a floating
10126     // point conversion.
10127     // TODO: More work could be done to identify the root cause such as a
10128     // constant or a function return type and point the user to it.
10129     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10130       ORE->emit([&]() {
10131         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10132                                           I->getDebugLoc(), L->getHeader())
10133                << "floating point conversion changes vector width. "
10134                << "Mixed floating point precision requires an up/down "
10135                << "cast that will negatively impact performance.";
10136       });
10137 
10138     for (Use &Op : I->operands())
10139       if (auto *OpI = dyn_cast<Instruction>(Op))
10140         Worklist.push_back(OpI);
10141   }
10142 }
10143 
10144 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10145     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10146                                !EnableLoopInterleaving),
10147       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10148                               !EnableLoopVectorization) {}
10149 
10150 bool LoopVectorizePass::processLoop(Loop *L) {
10151   assert((EnableVPlanNativePath || L->isInnermost()) &&
10152          "VPlan-native path is not enabled. Only process inner loops.");
10153 
10154 #ifndef NDEBUG
10155   const std::string DebugLocStr = getDebugLocString(L);
10156 #endif /* NDEBUG */
10157 
10158   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
10159                     << L->getHeader()->getParent()->getName() << "\" from "
10160                     << DebugLocStr << "\n");
10161 
10162   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
10163 
10164   LLVM_DEBUG(
10165       dbgs() << "LV: Loop hints:"
10166              << " force="
10167              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10168                      ? "disabled"
10169                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10170                             ? "enabled"
10171                             : "?"))
10172              << " width=" << Hints.getWidth()
10173              << " interleave=" << Hints.getInterleave() << "\n");
10174 
10175   // Function containing loop
10176   Function *F = L->getHeader()->getParent();
10177 
10178   // Looking at the diagnostic output is the only way to determine if a loop
10179   // was vectorized (other than looking at the IR or machine code), so it
10180   // is important to generate an optimization remark for each loop. Most of
10181   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10182   // generated as OptimizationRemark and OptimizationRemarkMissed are
10183   // less verbose reporting vectorized loops and unvectorized loops that may
10184   // benefit from vectorization, respectively.
10185 
10186   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10187     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10188     return false;
10189   }
10190 
10191   PredicatedScalarEvolution PSE(*SE, *L);
10192 
10193   // Check if it is legal to vectorize the loop.
10194   LoopVectorizationRequirements Requirements;
10195   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10196                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10197   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10198     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10199     Hints.emitRemarkWithHints();
10200     return false;
10201   }
10202 
10203   // Check the function attributes and profiles to find out if this function
10204   // should be optimized for size.
10205   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10206       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10207 
10208   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10209   // here. They may require CFG and instruction level transformations before
10210   // even evaluating whether vectorization is profitable. Since we cannot modify
10211   // the incoming IR, we need to build VPlan upfront in the vectorization
10212   // pipeline.
10213   if (!L->isInnermost())
10214     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10215                                         ORE, BFI, PSI, Hints, Requirements);
10216 
10217   assert(L->isInnermost() && "Inner loop expected.");
10218 
10219   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10220   // count by optimizing for size, to minimize overheads.
10221   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10222   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10223     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10224                       << "This loop is worth vectorizing only if no scalar "
10225                       << "iteration overheads are incurred.");
10226     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10227       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10228     else {
10229       LLVM_DEBUG(dbgs() << "\n");
10230       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10231     }
10232   }
10233 
10234   // Check the function attributes to see if implicit floats are allowed.
10235   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10236   // an integer loop and the vector instructions selected are purely integer
10237   // vector instructions?
10238   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10239     reportVectorizationFailure(
10240         "Can't vectorize when the NoImplicitFloat attribute is used",
10241         "loop not vectorized due to NoImplicitFloat attribute",
10242         "NoImplicitFloat", ORE, L);
10243     Hints.emitRemarkWithHints();
10244     return false;
10245   }
10246 
10247   // Check if the target supports potentially unsafe FP vectorization.
10248   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10249   // for the target we're vectorizing for, to make sure none of the
10250   // additional fp-math flags can help.
10251   if (Hints.isPotentiallyUnsafe() &&
10252       TTI->isFPVectorizationPotentiallyUnsafe()) {
10253     reportVectorizationFailure(
10254         "Potentially unsafe FP op prevents vectorization",
10255         "loop not vectorized due to unsafe FP support.",
10256         "UnsafeFP", ORE, L);
10257     Hints.emitRemarkWithHints();
10258     return false;
10259   }
10260 
10261   bool AllowOrderedReductions;
10262   // If the flag is set, use that instead and override the TTI behaviour.
10263   if (ForceOrderedReductions.getNumOccurrences() > 0)
10264     AllowOrderedReductions = ForceOrderedReductions;
10265   else
10266     AllowOrderedReductions = TTI->enableOrderedReductions();
10267   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10268     ORE->emit([&]() {
10269       auto *ExactFPMathInst = Requirements.getExactFPInst();
10270       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10271                                                  ExactFPMathInst->getDebugLoc(),
10272                                                  ExactFPMathInst->getParent())
10273              << "loop not vectorized: cannot prove it is safe to reorder "
10274                 "floating-point operations";
10275     });
10276     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10277                          "reorder floating-point operations\n");
10278     Hints.emitRemarkWithHints();
10279     return false;
10280   }
10281 
10282   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10283   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10284 
10285   // If an override option has been passed in for interleaved accesses, use it.
10286   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10287     UseInterleaved = EnableInterleavedMemAccesses;
10288 
10289   // Analyze interleaved memory accesses.
10290   if (UseInterleaved) {
10291     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10292   }
10293 
10294   // Use the cost model.
10295   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10296                                 F, &Hints, IAI);
10297   CM.collectValuesToIgnore();
10298   CM.collectElementTypesForWidening();
10299 
10300   // Use the planner for vectorization.
10301   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10302                                Requirements, ORE);
10303 
10304   // Get user vectorization factor and interleave count.
10305   ElementCount UserVF = Hints.getWidth();
10306   unsigned UserIC = Hints.getInterleave();
10307 
10308   // Plan how to best vectorize, return the best VF and its cost.
10309   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10310 
10311   VectorizationFactor VF = VectorizationFactor::Disabled();
10312   unsigned IC = 1;
10313 
10314   if (MaybeVF) {
10315     VF = *MaybeVF;
10316     // Select the interleave count.
10317     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10318   }
10319 
10320   // Identify the diagnostic messages that should be produced.
10321   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10322   bool VectorizeLoop = true, InterleaveLoop = true;
10323   if (VF.Width.isScalar()) {
10324     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10325     VecDiagMsg = std::make_pair(
10326         "VectorizationNotBeneficial",
10327         "the cost-model indicates that vectorization is not beneficial");
10328     VectorizeLoop = false;
10329   }
10330 
10331   if (!MaybeVF && UserIC > 1) {
10332     // Tell the user interleaving was avoided up-front, despite being explicitly
10333     // requested.
10334     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10335                          "interleaving should be avoided up front\n");
10336     IntDiagMsg = std::make_pair(
10337         "InterleavingAvoided",
10338         "Ignoring UserIC, because interleaving was avoided up front");
10339     InterleaveLoop = false;
10340   } else if (IC == 1 && UserIC <= 1) {
10341     // Tell the user interleaving is not beneficial.
10342     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10343     IntDiagMsg = std::make_pair(
10344         "InterleavingNotBeneficial",
10345         "the cost-model indicates that interleaving is not beneficial");
10346     InterleaveLoop = false;
10347     if (UserIC == 1) {
10348       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10349       IntDiagMsg.second +=
10350           " and is explicitly disabled or interleave count is set to 1";
10351     }
10352   } else if (IC > 1 && UserIC == 1) {
10353     // Tell the user interleaving is beneficial, but it explicitly disabled.
10354     LLVM_DEBUG(
10355         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10356     IntDiagMsg = std::make_pair(
10357         "InterleavingBeneficialButDisabled",
10358         "the cost-model indicates that interleaving is beneficial "
10359         "but is explicitly disabled or interleave count is set to 1");
10360     InterleaveLoop = false;
10361   }
10362 
10363   // Override IC if user provided an interleave count.
10364   IC = UserIC > 0 ? UserIC : IC;
10365 
10366   // Emit diagnostic messages, if any.
10367   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10368   if (!VectorizeLoop && !InterleaveLoop) {
10369     // Do not vectorize or interleaving the loop.
10370     ORE->emit([&]() {
10371       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10372                                       L->getStartLoc(), L->getHeader())
10373              << VecDiagMsg.second;
10374     });
10375     ORE->emit([&]() {
10376       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10377                                       L->getStartLoc(), L->getHeader())
10378              << IntDiagMsg.second;
10379     });
10380     return false;
10381   } else if (!VectorizeLoop && InterleaveLoop) {
10382     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10383     ORE->emit([&]() {
10384       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10385                                         L->getStartLoc(), L->getHeader())
10386              << VecDiagMsg.second;
10387     });
10388   } else if (VectorizeLoop && !InterleaveLoop) {
10389     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10390                       << ") in " << DebugLocStr << '\n');
10391     ORE->emit([&]() {
10392       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10393                                         L->getStartLoc(), L->getHeader())
10394              << IntDiagMsg.second;
10395     });
10396   } else if (VectorizeLoop && InterleaveLoop) {
10397     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10398                       << ") in " << DebugLocStr << '\n');
10399     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10400   }
10401 
10402   bool DisableRuntimeUnroll = false;
10403   MDNode *OrigLoopID = L->getLoopID();
10404   {
10405     // Optimistically generate runtime checks. Drop them if they turn out to not
10406     // be profitable. Limit the scope of Checks, so the cleanup happens
10407     // immediately after vector codegeneration is done.
10408     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10409                              F->getParent()->getDataLayout());
10410     if (!VF.Width.isScalar() || IC > 1)
10411       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10412     LVP.setBestPlan(VF.Width, IC);
10413 
10414     using namespace ore;
10415     if (!VectorizeLoop) {
10416       assert(IC > 1 && "interleave count should not be 1 or 0");
10417       // If we decided that it is not legal to vectorize the loop, then
10418       // interleave it.
10419       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10420                                  &CM, BFI, PSI, Checks);
10421       LVP.executePlan(Unroller, DT);
10422 
10423       ORE->emit([&]() {
10424         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10425                                   L->getHeader())
10426                << "interleaved loop (interleaved count: "
10427                << NV("InterleaveCount", IC) << ")";
10428       });
10429     } else {
10430       // If we decided that it is *legal* to vectorize the loop, then do it.
10431 
10432       // Consider vectorizing the epilogue too if it's profitable.
10433       VectorizationFactor EpilogueVF =
10434           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10435       if (EpilogueVF.Width.isVector()) {
10436 
10437         // The first pass vectorizes the main loop and creates a scalar epilogue
10438         // to be vectorized by executing the plan (potentially with a different
10439         // factor) again shortly afterwards.
10440         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10441         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10442                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10443 
10444         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
10445         LVP.executePlan(MainILV, DT);
10446         ++LoopsVectorized;
10447 
10448         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10449         formLCSSARecursively(*L, *DT, LI, SE);
10450 
10451         // Second pass vectorizes the epilogue and adjusts the control flow
10452         // edges from the first pass.
10453         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
10454         EPI.MainLoopVF = EPI.EpilogueVF;
10455         EPI.MainLoopUF = EPI.EpilogueUF;
10456         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10457                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10458                                                  Checks);
10459         LVP.executePlan(EpilogILV, DT);
10460         ++LoopsEpilogueVectorized;
10461 
10462         if (!MainILV.areSafetyChecksAdded())
10463           DisableRuntimeUnroll = true;
10464       } else {
10465         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10466                                &LVL, &CM, BFI, PSI, Checks);
10467         LVP.executePlan(LB, DT);
10468         ++LoopsVectorized;
10469 
10470         // Add metadata to disable runtime unrolling a scalar loop when there
10471         // are no runtime checks about strides and memory. A scalar loop that is
10472         // rarely used is not worth unrolling.
10473         if (!LB.areSafetyChecksAdded())
10474           DisableRuntimeUnroll = true;
10475       }
10476       // Report the vectorization decision.
10477       ORE->emit([&]() {
10478         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10479                                   L->getHeader())
10480                << "vectorized loop (vectorization width: "
10481                << NV("VectorizationFactor", VF.Width)
10482                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10483       });
10484     }
10485 
10486     if (ORE->allowExtraAnalysis(LV_NAME))
10487       checkMixedPrecision(L, ORE);
10488   }
10489 
10490   Optional<MDNode *> RemainderLoopID =
10491       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10492                                       LLVMLoopVectorizeFollowupEpilogue});
10493   if (RemainderLoopID.hasValue()) {
10494     L->setLoopID(RemainderLoopID.getValue());
10495   } else {
10496     if (DisableRuntimeUnroll)
10497       AddRuntimeUnrollDisableMetaData(L);
10498 
10499     // Mark the loop as already vectorized to avoid vectorizing again.
10500     Hints.setAlreadyVectorized();
10501   }
10502 
10503   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10504   return true;
10505 }
10506 
10507 LoopVectorizeResult LoopVectorizePass::runImpl(
10508     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10509     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10510     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10511     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10512     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10513   SE = &SE_;
10514   LI = &LI_;
10515   TTI = &TTI_;
10516   DT = &DT_;
10517   BFI = &BFI_;
10518   TLI = TLI_;
10519   AA = &AA_;
10520   AC = &AC_;
10521   GetLAA = &GetLAA_;
10522   DB = &DB_;
10523   ORE = &ORE_;
10524   PSI = PSI_;
10525 
10526   // Don't attempt if
10527   // 1. the target claims to have no vector registers, and
10528   // 2. interleaving won't help ILP.
10529   //
10530   // The second condition is necessary because, even if the target has no
10531   // vector registers, loop vectorization may still enable scalar
10532   // interleaving.
10533   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10534       TTI->getMaxInterleaveFactor(1) < 2)
10535     return LoopVectorizeResult(false, false);
10536 
10537   bool Changed = false, CFGChanged = false;
10538 
10539   // The vectorizer requires loops to be in simplified form.
10540   // Since simplification may add new inner loops, it has to run before the
10541   // legality and profitability checks. This means running the loop vectorizer
10542   // will simplify all loops, regardless of whether anything end up being
10543   // vectorized.
10544   for (auto &L : *LI)
10545     Changed |= CFGChanged |=
10546         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10547 
10548   // Build up a worklist of inner-loops to vectorize. This is necessary as
10549   // the act of vectorizing or partially unrolling a loop creates new loops
10550   // and can invalidate iterators across the loops.
10551   SmallVector<Loop *, 8> Worklist;
10552 
10553   for (Loop *L : *LI)
10554     collectSupportedLoops(*L, LI, ORE, Worklist);
10555 
10556   LoopsAnalyzed += Worklist.size();
10557 
10558   // Now walk the identified inner loops.
10559   while (!Worklist.empty()) {
10560     Loop *L = Worklist.pop_back_val();
10561 
10562     // For the inner loops we actually process, form LCSSA to simplify the
10563     // transform.
10564     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10565 
10566     Changed |= CFGChanged |= processLoop(L);
10567   }
10568 
10569   // Process each loop nest in the function.
10570   return LoopVectorizeResult(Changed, CFGChanged);
10571 }
10572 
10573 PreservedAnalyses LoopVectorizePass::run(Function &F,
10574                                          FunctionAnalysisManager &AM) {
10575     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10576     auto &LI = AM.getResult<LoopAnalysis>(F);
10577     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10578     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10579     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10580     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10581     auto &AA = AM.getResult<AAManager>(F);
10582     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10583     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10584     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10585 
10586     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10587     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10588         [&](Loop &L) -> const LoopAccessInfo & {
10589       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10590                                         TLI, TTI, nullptr, nullptr, nullptr};
10591       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10592     };
10593     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10594     ProfileSummaryInfo *PSI =
10595         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10596     LoopVectorizeResult Result =
10597         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10598     if (!Result.MadeAnyChange)
10599       return PreservedAnalyses::all();
10600     PreservedAnalyses PA;
10601 
10602     // We currently do not preserve loopinfo/dominator analyses with outer loop
10603     // vectorization. Until this is addressed, mark these analyses as preserved
10604     // only for non-VPlan-native path.
10605     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10606     if (!EnableVPlanNativePath) {
10607       PA.preserve<LoopAnalysis>();
10608       PA.preserve<DominatorTreeAnalysis>();
10609     }
10610     if (!Result.MadeCFGChange)
10611       PA.preserveSet<CFGAnalyses>();
10612     return PA;
10613 }
10614 
10615 void LoopVectorizePass::printPipeline(
10616     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10617   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10618       OS, MapClassName2PassName);
10619 
10620   OS << "<";
10621   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10622   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10623   OS << ">";
10624 }
10625