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/MemorySSA.h"
91 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
92 #include "llvm/Analysis/ProfileSummaryInfo.h"
93 #include "llvm/Analysis/ScalarEvolution.h"
94 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
95 #include "llvm/Analysis/TargetLibraryInfo.h"
96 #include "llvm/Analysis/TargetTransformInfo.h"
97 #include "llvm/Analysis/VectorUtils.h"
98 #include "llvm/IR/Attributes.h"
99 #include "llvm/IR/BasicBlock.h"
100 #include "llvm/IR/CFG.h"
101 #include "llvm/IR/Constant.h"
102 #include "llvm/IR/Constants.h"
103 #include "llvm/IR/DataLayout.h"
104 #include "llvm/IR/DebugInfoMetadata.h"
105 #include "llvm/IR/DebugLoc.h"
106 #include "llvm/IR/DerivedTypes.h"
107 #include "llvm/IR/DiagnosticInfo.h"
108 #include "llvm/IR/Dominators.h"
109 #include "llvm/IR/Function.h"
110 #include "llvm/IR/IRBuilder.h"
111 #include "llvm/IR/InstrTypes.h"
112 #include "llvm/IR/Instruction.h"
113 #include "llvm/IR/Instructions.h"
114 #include "llvm/IR/IntrinsicInst.h"
115 #include "llvm/IR/Intrinsics.h"
116 #include "llvm/IR/LLVMContext.h"
117 #include "llvm/IR/Metadata.h"
118 #include "llvm/IR/Module.h"
119 #include "llvm/IR/Operator.h"
120 #include "llvm/IR/PatternMatch.h"
121 #include "llvm/IR/Type.h"
122 #include "llvm/IR/Use.h"
123 #include "llvm/IR/User.h"
124 #include "llvm/IR/Value.h"
125 #include "llvm/IR/ValueHandle.h"
126 #include "llvm/IR/Verifier.h"
127 #include "llvm/InitializePasses.h"
128 #include "llvm/Pass.h"
129 #include "llvm/Support/Casting.h"
130 #include "llvm/Support/CommandLine.h"
131 #include "llvm/Support/Compiler.h"
132 #include "llvm/Support/Debug.h"
133 #include "llvm/Support/ErrorHandling.h"
134 #include "llvm/Support/InstructionCost.h"
135 #include "llvm/Support/MathExtras.h"
136 #include "llvm/Support/raw_ostream.h"
137 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
138 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
139 #include "llvm/Transforms/Utils/LoopSimplify.h"
140 #include "llvm/Transforms/Utils/LoopUtils.h"
141 #include "llvm/Transforms/Utils/LoopVersioning.h"
142 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
143 #include "llvm/Transforms/Utils/SizeOpts.h"
144 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
145 #include <algorithm>
146 #include <cassert>
147 #include <cstdint>
148 #include <cstdlib>
149 #include <functional>
150 #include <iterator>
151 #include <limits>
152 #include <memory>
153 #include <string>
154 #include <tuple>
155 #include <utility>
156 
157 using namespace llvm;
158 
159 #define LV_NAME "loop-vectorize"
160 #define DEBUG_TYPE LV_NAME
161 
162 #ifndef NDEBUG
163 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
164 #endif
165 
166 /// @{
167 /// Metadata attribute names
168 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
169 const char LLVMLoopVectorizeFollowupVectorized[] =
170     "llvm.loop.vectorize.followup_vectorized";
171 const char LLVMLoopVectorizeFollowupEpilogue[] =
172     "llvm.loop.vectorize.followup_epilogue";
173 /// @}
174 
175 STATISTIC(LoopsVectorized, "Number of loops vectorized");
176 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
177 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
178 
179 static cl::opt<bool> EnableEpilogueVectorization(
180     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
181     cl::desc("Enable vectorization of epilogue loops."));
182 
183 static cl::opt<unsigned> EpilogueVectorizationForceVF(
184     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
185     cl::desc("When epilogue vectorization is enabled, and a value greater than "
186              "1 is specified, forces the given VF for all applicable epilogue "
187              "loops."));
188 
189 static cl::opt<unsigned> EpilogueVectorizationMinVF(
190     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
191     cl::desc("Only loops with vectorization factor equal to or larger than "
192              "the specified value are considered for epilogue vectorization."));
193 
194 /// Loops with a known constant trip count below this number are vectorized only
195 /// if no scalar iteration overheads are incurred.
196 static cl::opt<unsigned> TinyTripCountVectorThreshold(
197     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
198     cl::desc("Loops with a constant trip count that is smaller than this "
199              "value are vectorized only if no scalar iteration overheads "
200              "are incurred."));
201 
202 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
203     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
204     cl::desc("The maximum allowed number of runtime memory checks with a "
205              "vectorize(enable) pragma."));
206 
207 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
208 // that predication is preferred, and this lists all options. I.e., the
209 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
210 // and predicate the instructions accordingly. If tail-folding fails, there are
211 // different fallback strategies depending on these values:
212 namespace PreferPredicateTy {
213   enum Option {
214     ScalarEpilogue = 0,
215     PredicateElseScalarEpilogue,
216     PredicateOrDontVectorize
217   };
218 } // namespace PreferPredicateTy
219 
220 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
221     "prefer-predicate-over-epilogue",
222     cl::init(PreferPredicateTy::ScalarEpilogue),
223     cl::Hidden,
224     cl::desc("Tail-folding and predication preferences over creating a scalar "
225              "epilogue loop."),
226     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
227                          "scalar-epilogue",
228                          "Don't tail-predicate loops, create scalar epilogue"),
229               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
230                          "predicate-else-scalar-epilogue",
231                          "prefer tail-folding, create scalar epilogue if tail "
232                          "folding fails."),
233               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
234                          "predicate-dont-vectorize",
235                          "prefers tail-folding, don't attempt vectorization if "
236                          "tail-folding fails.")));
237 
238 static cl::opt<bool> MaximizeBandwidth(
239     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
240     cl::desc("Maximize bandwidth when selecting vectorization factor which "
241              "will be determined by the smallest type in loop."));
242 
243 static cl::opt<bool> EnableInterleavedMemAccesses(
244     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
245     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
246 
247 /// An interleave-group may need masking if it resides in a block that needs
248 /// predication, or in order to mask away gaps.
249 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
250     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
251     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
252 
253 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
254     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
255     cl::desc("We don't interleave loops with a estimated constant trip count "
256              "below this number"));
257 
258 static cl::opt<unsigned> ForceTargetNumScalarRegs(
259     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
260     cl::desc("A flag that overrides the target's number of scalar registers."));
261 
262 static cl::opt<unsigned> ForceTargetNumVectorRegs(
263     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
264     cl::desc("A flag that overrides the target's number of vector registers."));
265 
266 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
267     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
268     cl::desc("A flag that overrides the target's max interleave factor for "
269              "scalar loops."));
270 
271 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
272     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
273     cl::desc("A flag that overrides the target's max interleave factor for "
274              "vectorized loops."));
275 
276 static cl::opt<unsigned> ForceTargetInstructionCost(
277     "force-target-instruction-cost", cl::init(0), cl::Hidden,
278     cl::desc("A flag that overrides the target's expected cost for "
279              "an instruction to a single constant value. Mostly "
280              "useful for getting consistent testing."));
281 
282 static cl::opt<bool> ForceTargetSupportsScalableVectors(
283     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
284     cl::desc(
285         "Pretend that scalable vectors are supported, even if the target does "
286         "not support them. This flag should only be used for testing."));
287 
288 static cl::opt<unsigned> SmallLoopCost(
289     "small-loop-cost", cl::init(20), cl::Hidden,
290     cl::desc(
291         "The cost of a loop that is considered 'small' by the interleaver."));
292 
293 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
294     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
295     cl::desc("Enable the use of the block frequency analysis to access PGO "
296              "heuristics minimizing code growth in cold regions and being more "
297              "aggressive in hot regions."));
298 
299 // Runtime interleave loops for load/store throughput.
300 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
301     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
302     cl::desc(
303         "Enable runtime interleaving until load/store ports are saturated"));
304 
305 /// Interleave small loops with scalar reductions.
306 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
307     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
308     cl::desc("Enable interleaving for loops with small iteration counts that "
309              "contain scalar reductions to expose ILP."));
310 
311 /// The number of stores in a loop that are allowed to need predication.
312 static cl::opt<unsigned> NumberOfStoresToPredicate(
313     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
314     cl::desc("Max number of stores to be predicated behind an if."));
315 
316 static cl::opt<bool> EnableIndVarRegisterHeur(
317     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
318     cl::desc("Count the induction variable only once when interleaving"));
319 
320 static cl::opt<bool> EnableCondStoresVectorization(
321     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
322     cl::desc("Enable if predication of stores during vectorization."));
323 
324 static cl::opt<unsigned> MaxNestedScalarReductionIC(
325     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
326     cl::desc("The maximum interleave count to use when interleaving a scalar "
327              "reduction in a nested loop."));
328 
329 static cl::opt<bool>
330     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
331                            cl::Hidden,
332                            cl::desc("Prefer in-loop vector reductions, "
333                                     "overriding the targets preference."));
334 
335 cl::opt<bool> EnableStrictReductions(
336     "enable-strict-reductions", cl::init(false), cl::Hidden,
337     cl::desc("Enable the vectorisation of loops with in-order (strict) "
338              "FP reductions"));
339 
340 static cl::opt<bool> PreferPredicatedReductionSelect(
341     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
342     cl::desc(
343         "Prefer predicating a reduction operation over an after loop select."));
344 
345 cl::opt<bool> EnableVPlanNativePath(
346     "enable-vplan-native-path", cl::init(false), cl::Hidden,
347     cl::desc("Enable VPlan-native vectorization path with "
348              "support for outer loop vectorization."));
349 
350 // FIXME: Remove this switch once we have divergence analysis. Currently we
351 // assume divergent non-backedge branches when this switch is true.
352 cl::opt<bool> EnableVPlanPredication(
353     "enable-vplan-predication", cl::init(false), cl::Hidden,
354     cl::desc("Enable VPlan-native vectorization path predicator with "
355              "support for outer loop vectorization."));
356 
357 // This flag enables the stress testing of the VPlan H-CFG construction in the
358 // VPlan-native vectorization path. It must be used in conjuction with
359 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
360 // verification of the H-CFGs built.
361 static cl::opt<bool> VPlanBuildStressTest(
362     "vplan-build-stress-test", cl::init(false), cl::Hidden,
363     cl::desc(
364         "Build VPlan for every supported loop nest in the function and bail "
365         "out right after the build (stress test the VPlan H-CFG construction "
366         "in the VPlan-native vectorization path)."));
367 
368 cl::opt<bool> llvm::EnableLoopInterleaving(
369     "interleave-loops", cl::init(true), cl::Hidden,
370     cl::desc("Enable loop interleaving in Loop vectorization passes"));
371 cl::opt<bool> llvm::EnableLoopVectorization(
372     "vectorize-loops", cl::init(true), cl::Hidden,
373     cl::desc("Run the Loop vectorization passes"));
374 
375 cl::opt<bool> PrintVPlansInDotFormat(
376     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
377     cl::desc("Use dot format instead of plain text when dumping VPlans"));
378 
379 /// A helper function that returns true if the given type is irregular. The
380 /// type is irregular if its allocated size doesn't equal the store size of an
381 /// element of the corresponding vector type.
382 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
383   // Determine if an array of N elements of type Ty is "bitcast compatible"
384   // with a <N x Ty> vector.
385   // This is only true if there is no padding between the array elements.
386   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
387 }
388 
389 /// A helper function that returns the reciprocal of the block probability of
390 /// predicated blocks. If we return X, we are assuming the predicated block
391 /// will execute once for every X iterations of the loop header.
392 ///
393 /// TODO: We should use actual block probability here, if available. Currently,
394 ///       we always assume predicated blocks have a 50% chance of executing.
395 static unsigned getReciprocalPredBlockProb() { return 2; }
396 
397 /// A helper function that returns an integer or floating-point constant with
398 /// value C.
399 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
400   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
401                            : ConstantFP::get(Ty, C);
402 }
403 
404 /// Returns "best known" trip count for the specified loop \p L as defined by
405 /// the following procedure:
406 ///   1) Returns exact trip count if it is known.
407 ///   2) Returns expected trip count according to profile data if any.
408 ///   3) Returns upper bound estimate if it is known.
409 ///   4) Returns None if all of the above failed.
410 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
411   // Check if exact trip count is known.
412   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
413     return ExpectedTC;
414 
415   // Check if there is an expected trip count available from profile data.
416   if (LoopVectorizeWithBlockFrequency)
417     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
418       return EstimatedTC;
419 
420   // Check if upper bound estimate is known.
421   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
422     return ExpectedTC;
423 
424   return None;
425 }
426 
427 // Forward declare GeneratedRTChecks.
428 class GeneratedRTChecks;
429 
430 namespace llvm {
431 
432 /// InnerLoopVectorizer vectorizes loops which contain only one basic
433 /// block to a specified vectorization factor (VF).
434 /// This class performs the widening of scalars into vectors, or multiple
435 /// scalars. This class also implements the following features:
436 /// * It inserts an epilogue loop for handling loops that don't have iteration
437 ///   counts that are known to be a multiple of the vectorization factor.
438 /// * It handles the code generation for reduction variables.
439 /// * Scalarization (implementation using scalars) of un-vectorizable
440 ///   instructions.
441 /// InnerLoopVectorizer does not perform any vectorization-legality
442 /// checks, and relies on the caller to check for the different legality
443 /// aspects. The InnerLoopVectorizer relies on the
444 /// LoopVectorizationLegality class to provide information about the induction
445 /// and reduction variables that were found to a given vectorization factor.
446 class InnerLoopVectorizer {
447 public:
448   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
449                       LoopInfo *LI, DominatorTree *DT,
450                       const TargetLibraryInfo *TLI,
451                       const TargetTransformInfo *TTI, AssumptionCache *AC,
452                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
453                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
454                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
455                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
456       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
457         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
458         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
459         PSI(PSI), RTChecks(RTChecks) {
460     // Query this against the original loop and save it here because the profile
461     // of the original loop header may change as the transformation happens.
462     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
463         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
464   }
465 
466   virtual ~InnerLoopVectorizer() = default;
467 
468   /// Create a new empty loop that will contain vectorized instructions later
469   /// on, while the old loop will be used as the scalar remainder. Control flow
470   /// is generated around the vectorized (and scalar epilogue) loops consisting
471   /// of various checks and bypasses. Return the pre-header block of the new
472   /// loop.
473   /// In the case of epilogue vectorization, this function is overriden to
474   /// handle the more complex control flow around the loops.
475   virtual BasicBlock *createVectorizedLoopSkeleton();
476 
477   /// Widen a single instruction within the innermost loop.
478   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
479                         VPTransformState &State);
480 
481   /// Widen a single call instruction within the innermost loop.
482   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
483                             VPTransformState &State);
484 
485   /// Widen a single select instruction within the innermost loop.
486   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
487                               bool InvariantCond, VPTransformState &State);
488 
489   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
490   void fixVectorizedLoop(VPTransformState &State);
491 
492   // Return true if any runtime check is added.
493   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
494 
495   /// A type for vectorized values in the new loop. Each value from the
496   /// original loop, when vectorized, is represented by UF vector values in the
497   /// new unrolled loop, where UF is the unroll factor.
498   using VectorParts = SmallVector<Value *, 2>;
499 
500   /// Vectorize a single GetElementPtrInst based on information gathered and
501   /// decisions taken during planning.
502   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
503                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
504                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
505 
506   /// Vectorize a single first-order recurrence or pointer induction PHINode in
507   /// a block. This method handles the induction variable canonicalization. It
508   /// supports both VF = 1 for unrolled loops and arbitrary length vectors.
509   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
510                            VPTransformState &State);
511 
512   /// A helper function to scalarize a single Instruction in the innermost loop.
513   /// Generates a sequence of scalar instances for each lane between \p MinLane
514   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
515   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
516   /// Instr's operands.
517   void scalarizeInstruction(Instruction *Instr, VPValue *Def, VPUser &Operands,
518                             const VPIteration &Instance, bool IfPredicateInstr,
519                             VPTransformState &State);
520 
521   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
522   /// is provided, the integer induction variable will first be truncated to
523   /// the corresponding type.
524   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
525                              VPValue *Def, VPValue *CastDef,
526                              VPTransformState &State);
527 
528   /// Construct the vector value of a scalarized value \p V one lane at a time.
529   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
530                                  VPTransformState &State);
531 
532   /// Try to vectorize interleaved access group \p Group with the base address
533   /// given in \p Addr, optionally masking the vector operations if \p
534   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
535   /// values in the vectorized loop.
536   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
537                                 ArrayRef<VPValue *> VPDefs,
538                                 VPTransformState &State, VPValue *Addr,
539                                 ArrayRef<VPValue *> StoredValues,
540                                 VPValue *BlockInMask = nullptr);
541 
542   /// Vectorize Load and Store instructions with the base address given in \p
543   /// Addr, optionally masking the vector operations if \p BlockInMask is
544   /// non-null. Use \p State to translate given VPValues to IR values in the
545   /// vectorized loop.
546   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
547                                   VPValue *Def, VPValue *Addr,
548                                   VPValue *StoredValue, VPValue *BlockInMask);
549 
550   /// Set the debug location in the builder \p Ptr using the debug location in
551   /// \p V. If \p Ptr is None then it uses the class member's Builder.
552   void setDebugLocFromInst(const Value *V,
553                            Optional<IRBuilder<> *> CustomBuilder = None);
554 
555   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
556   void fixNonInductionPHIs(VPTransformState &State);
557 
558   /// Returns true if the reordering of FP operations is not allowed, but we are
559   /// able to vectorize with strict in-order reductions for the given RdxDesc.
560   bool useOrderedReductions(RecurrenceDescriptor &RdxDesc);
561 
562   /// Create a broadcast instruction. This method generates a broadcast
563   /// instruction (shuffle) for loop invariant values and for the induction
564   /// value. If this is the induction variable then we extend it to N, N+1, ...
565   /// this is needed because each iteration in the loop corresponds to a SIMD
566   /// element.
567   virtual Value *getBroadcastInstrs(Value *V);
568 
569 protected:
570   friend class LoopVectorizationPlanner;
571 
572   /// A small list of PHINodes.
573   using PhiVector = SmallVector<PHINode *, 4>;
574 
575   /// A type for scalarized values in the new loop. Each value from the
576   /// original loop, when scalarized, is represented by UF x VF scalar values
577   /// in the new unrolled loop, where UF is the unroll factor and VF is the
578   /// vectorization factor.
579   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
580 
581   /// Set up the values of the IVs correctly when exiting the vector loop.
582   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
583                     Value *CountRoundDown, Value *EndValue,
584                     BasicBlock *MiddleBlock);
585 
586   /// Create a new induction variable inside L.
587   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
588                                    Value *Step, Instruction *DL);
589 
590   /// Handle all cross-iteration phis in the header.
591   void fixCrossIterationPHIs(VPTransformState &State);
592 
593   /// Fix a first-order recurrence. This is the second phase of vectorizing
594   /// this phi node.
595   void fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR, VPTransformState &State);
596 
597   /// Fix a reduction cross-iteration phi. This is the second phase of
598   /// vectorizing this phi node.
599   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
600 
601   /// Clear NSW/NUW flags from reduction instructions if necessary.
602   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
603                                VPTransformState &State);
604 
605   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
606   /// means we need to add the appropriate incoming value from the middle
607   /// block as exiting edges from the scalar epilogue loop (if present) are
608   /// already in place, and we exit the vector loop exclusively to the middle
609   /// block.
610   void fixLCSSAPHIs(VPTransformState &State);
611 
612   /// Iteratively sink the scalarized operands of a predicated instruction into
613   /// the block that was created for it.
614   void sinkScalarOperands(Instruction *PredInst);
615 
616   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
617   /// represented as.
618   void truncateToMinimalBitwidths(VPTransformState &State);
619 
620   /// This function adds
621   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
622   /// to each vector element of Val. The sequence starts at StartIndex.
623   /// \p Opcode is relevant for FP induction variable.
624   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
625                                Instruction::BinaryOps Opcode =
626                                Instruction::BinaryOpsEnd);
627 
628   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
629   /// variable on which to base the steps, \p Step is the size of the step, and
630   /// \p EntryVal is the value from the original loop that maps to the steps.
631   /// Note that \p EntryVal doesn't have to be an induction variable - it
632   /// can also be a truncate instruction.
633   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
634                         const InductionDescriptor &ID, VPValue *Def,
635                         VPValue *CastDef, VPTransformState &State);
636 
637   /// Create a vector induction phi node based on an existing scalar one. \p
638   /// EntryVal is the value from the original loop that maps to the vector phi
639   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
640   /// truncate instruction, instead of widening the original IV, we widen a
641   /// version of the IV truncated to \p EntryVal's type.
642   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
643                                        Value *Step, Value *Start,
644                                        Instruction *EntryVal, VPValue *Def,
645                                        VPValue *CastDef,
646                                        VPTransformState &State);
647 
648   /// Returns true if an instruction \p I should be scalarized instead of
649   /// vectorized for the chosen vectorization factor.
650   bool shouldScalarizeInstruction(Instruction *I) const;
651 
652   /// Returns true if we should generate a scalar version of \p IV.
653   bool needsScalarInduction(Instruction *IV) const;
654 
655   /// If there is a cast involved in the induction variable \p ID, which should
656   /// be ignored in the vectorized loop body, this function records the
657   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
658   /// cast. We had already proved that the casted Phi is equal to the uncasted
659   /// Phi in the vectorized loop (under a runtime guard), and therefore
660   /// there is no need to vectorize the cast - the same value can be used in the
661   /// vector loop for both the Phi and the cast.
662   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
663   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
664   ///
665   /// \p EntryVal is the value from the original loop that maps to the vector
666   /// phi node and is used to distinguish what is the IV currently being
667   /// processed - original one (if \p EntryVal is a phi corresponding to the
668   /// original IV) or the "newly-created" one based on the proof mentioned above
669   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
670   /// latter case \p EntryVal is a TruncInst and we must not record anything for
671   /// that IV, but it's error-prone to expect callers of this routine to care
672   /// about that, hence this explicit parameter.
673   void recordVectorLoopValueForInductionCast(
674       const InductionDescriptor &ID, const Instruction *EntryVal,
675       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
676       unsigned Part, unsigned Lane = UINT_MAX);
677 
678   /// Generate a shuffle sequence that will reverse the vector Vec.
679   virtual Value *reverseVector(Value *Vec);
680 
681   /// Returns (and creates if needed) the original loop trip count.
682   Value *getOrCreateTripCount(Loop *NewLoop);
683 
684   /// Returns (and creates if needed) the trip count of the widened loop.
685   Value *getOrCreateVectorTripCount(Loop *NewLoop);
686 
687   /// Returns a bitcasted value to the requested vector type.
688   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
689   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
690                                 const DataLayout &DL);
691 
692   /// Emit a bypass check to see if the vector trip count is zero, including if
693   /// it overflows.
694   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
695 
696   /// Emit a bypass check to see if all of the SCEV assumptions we've
697   /// had to make are correct. Returns the block containing the checks or
698   /// nullptr if no checks have been added.
699   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
700 
701   /// Emit bypass checks to check any memory assumptions we may have made.
702   /// Returns the block containing the checks or nullptr if no checks have been
703   /// added.
704   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
705 
706   /// Compute the transformed value of Index at offset StartValue using step
707   /// StepValue.
708   /// For integer induction, returns StartValue + Index * StepValue.
709   /// For pointer induction, returns StartValue[Index * StepValue].
710   /// FIXME: The newly created binary instructions should contain nsw/nuw
711   /// flags, which can be found from the original scalar operations.
712   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
713                               const DataLayout &DL,
714                               const InductionDescriptor &ID) const;
715 
716   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
717   /// vector loop preheader, middle block and scalar preheader. Also
718   /// allocate a loop object for the new vector loop and return it.
719   Loop *createVectorLoopSkeleton(StringRef Prefix);
720 
721   /// Create new phi nodes for the induction variables to resume iteration count
722   /// in the scalar epilogue, from where the vectorized loop left off (given by
723   /// \p VectorTripCount).
724   /// In cases where the loop skeleton is more complicated (eg. epilogue
725   /// vectorization) and the resume values can come from an additional bypass
726   /// block, the \p AdditionalBypass pair provides information about the bypass
727   /// block and the end value on the edge from bypass to this loop.
728   void createInductionResumeValues(
729       Loop *L, Value *VectorTripCount,
730       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
731 
732   /// Complete the loop skeleton by adding debug MDs, creating appropriate
733   /// conditional branches in the middle block, preparing the builder and
734   /// running the verifier. Take in the vector loop \p L as argument, and return
735   /// the preheader of the completed vector loop.
736   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
737 
738   /// Add additional metadata to \p To that was not present on \p Orig.
739   ///
740   /// Currently this is used to add the noalias annotations based on the
741   /// inserted memchecks.  Use this for instructions that are *cloned* into the
742   /// vector loop.
743   void addNewMetadata(Instruction *To, const Instruction *Orig);
744 
745   /// Add metadata from one instruction to another.
746   ///
747   /// This includes both the original MDs from \p From and additional ones (\see
748   /// addNewMetadata).  Use this for *newly created* instructions in the vector
749   /// loop.
750   void addMetadata(Instruction *To, Instruction *From);
751 
752   /// Similar to the previous function but it adds the metadata to a
753   /// vector of instructions.
754   void addMetadata(ArrayRef<Value *> To, Instruction *From);
755 
756   /// Allow subclasses to override and print debug traces before/after vplan
757   /// execution, when trace information is requested.
758   virtual void printDebugTracesAtStart(){};
759   virtual void printDebugTracesAtEnd(){};
760 
761   /// The original loop.
762   Loop *OrigLoop;
763 
764   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
765   /// dynamic knowledge to simplify SCEV expressions and converts them to a
766   /// more usable form.
767   PredicatedScalarEvolution &PSE;
768 
769   /// Loop Info.
770   LoopInfo *LI;
771 
772   /// Dominator Tree.
773   DominatorTree *DT;
774 
775   /// Alias Analysis.
776   AAResults *AA;
777 
778   /// Target Library Info.
779   const TargetLibraryInfo *TLI;
780 
781   /// Target Transform Info.
782   const TargetTransformInfo *TTI;
783 
784   /// Assumption Cache.
785   AssumptionCache *AC;
786 
787   /// Interface to emit optimization remarks.
788   OptimizationRemarkEmitter *ORE;
789 
790   /// LoopVersioning.  It's only set up (non-null) if memchecks were
791   /// used.
792   ///
793   /// This is currently only used to add no-alias metadata based on the
794   /// memchecks.  The actually versioning is performed manually.
795   std::unique_ptr<LoopVersioning> LVer;
796 
797   /// The vectorization SIMD factor to use. Each vector will have this many
798   /// vector elements.
799   ElementCount VF;
800 
801   /// The vectorization unroll factor to use. Each scalar is vectorized to this
802   /// many different vector instructions.
803   unsigned UF;
804 
805   /// The builder that we use
806   IRBuilder<> Builder;
807 
808   // --- Vectorization state ---
809 
810   /// The vector-loop preheader.
811   BasicBlock *LoopVectorPreHeader;
812 
813   /// The scalar-loop preheader.
814   BasicBlock *LoopScalarPreHeader;
815 
816   /// Middle Block between the vector and the scalar.
817   BasicBlock *LoopMiddleBlock;
818 
819   /// The unique ExitBlock of the scalar loop if one exists.  Note that
820   /// there can be multiple exiting edges reaching this block.
821   BasicBlock *LoopExitBlock;
822 
823   /// The vector loop body.
824   BasicBlock *LoopVectorBody;
825 
826   /// The scalar loop body.
827   BasicBlock *LoopScalarBody;
828 
829   /// A list of all bypass blocks. The first block is the entry of the loop.
830   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
831 
832   /// The new Induction variable which was added to the new block.
833   PHINode *Induction = nullptr;
834 
835   /// The induction variable of the old basic block.
836   PHINode *OldInduction = nullptr;
837 
838   /// Store instructions that were predicated.
839   SmallVector<Instruction *, 4> PredicatedInstructions;
840 
841   /// Trip count of the original loop.
842   Value *TripCount = nullptr;
843 
844   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
845   Value *VectorTripCount = nullptr;
846 
847   /// The legality analysis.
848   LoopVectorizationLegality *Legal;
849 
850   /// The profitablity analysis.
851   LoopVectorizationCostModel *Cost;
852 
853   // Record whether runtime checks are added.
854   bool AddedSafetyChecks = false;
855 
856   // Holds the end values for each induction variable. We save the end values
857   // so we can later fix-up the external users of the induction variables.
858   DenseMap<PHINode *, Value *> IVEndValues;
859 
860   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
861   // fixed up at the end of vector code generation.
862   SmallVector<PHINode *, 8> OrigPHIsToFix;
863 
864   /// BFI and PSI are used to check for profile guided size optimizations.
865   BlockFrequencyInfo *BFI;
866   ProfileSummaryInfo *PSI;
867 
868   // Whether this loop should be optimized for size based on profile guided size
869   // optimizatios.
870   bool OptForSizeBasedOnProfile;
871 
872   /// Structure to hold information about generated runtime checks, responsible
873   /// for cleaning the checks, if vectorization turns out unprofitable.
874   GeneratedRTChecks &RTChecks;
875 };
876 
877 class InnerLoopUnroller : public InnerLoopVectorizer {
878 public:
879   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
880                     LoopInfo *LI, DominatorTree *DT,
881                     const TargetLibraryInfo *TLI,
882                     const TargetTransformInfo *TTI, AssumptionCache *AC,
883                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
884                     LoopVectorizationLegality *LVL,
885                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
886                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
887       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
888                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
889                             BFI, PSI, Check) {}
890 
891 private:
892   Value *getBroadcastInstrs(Value *V) override;
893   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
894                        Instruction::BinaryOps Opcode =
895                        Instruction::BinaryOpsEnd) override;
896   Value *reverseVector(Value *Vec) override;
897 };
898 
899 /// Encapsulate information regarding vectorization of a loop and its epilogue.
900 /// This information is meant to be updated and used across two stages of
901 /// epilogue vectorization.
902 struct EpilogueLoopVectorizationInfo {
903   ElementCount MainLoopVF = ElementCount::getFixed(0);
904   unsigned MainLoopUF = 0;
905   ElementCount EpilogueVF = ElementCount::getFixed(0);
906   unsigned EpilogueUF = 0;
907   BasicBlock *MainLoopIterationCountCheck = nullptr;
908   BasicBlock *EpilogueIterationCountCheck = nullptr;
909   BasicBlock *SCEVSafetyCheck = nullptr;
910   BasicBlock *MemSafetyCheck = nullptr;
911   Value *TripCount = nullptr;
912   Value *VectorTripCount = nullptr;
913 
914   EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
915                                 unsigned EUF)
916       : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
917         EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
918     assert(EUF == 1 &&
919            "A high UF for the epilogue loop is likely not beneficial.");
920   }
921 };
922 
923 /// An extension of the inner loop vectorizer that creates a skeleton for a
924 /// vectorized loop that has its epilogue (residual) also vectorized.
925 /// The idea is to run the vplan on a given loop twice, firstly to setup the
926 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
927 /// from the first step and vectorize the epilogue.  This is achieved by
928 /// deriving two concrete strategy classes from this base class and invoking
929 /// them in succession from the loop vectorizer planner.
930 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
931 public:
932   InnerLoopAndEpilogueVectorizer(
933       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
934       DominatorTree *DT, const TargetLibraryInfo *TLI,
935       const TargetTransformInfo *TTI, AssumptionCache *AC,
936       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
937       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
938       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
939       GeneratedRTChecks &Checks)
940       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
941                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
942                             Checks),
943         EPI(EPI) {}
944 
945   // Override this function to handle the more complex control flow around the
946   // three loops.
947   BasicBlock *createVectorizedLoopSkeleton() final override {
948     return createEpilogueVectorizedLoopSkeleton();
949   }
950 
951   /// The interface for creating a vectorized skeleton using one of two
952   /// different strategies, each corresponding to one execution of the vplan
953   /// as described above.
954   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
955 
956   /// Holds and updates state information required to vectorize the main loop
957   /// and its epilogue in two separate passes. This setup helps us avoid
958   /// regenerating and recomputing runtime safety checks. It also helps us to
959   /// shorten the iteration-count-check path length for the cases where the
960   /// iteration count of the loop is so small that the main vector loop is
961   /// completely skipped.
962   EpilogueLoopVectorizationInfo &EPI;
963 };
964 
965 /// A specialized derived class of inner loop vectorizer that performs
966 /// vectorization of *main* loops in the process of vectorizing loops and their
967 /// epilogues.
968 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
969 public:
970   EpilogueVectorizerMainLoop(
971       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
972       DominatorTree *DT, const TargetLibraryInfo *TLI,
973       const TargetTransformInfo *TTI, AssumptionCache *AC,
974       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
975       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
976       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
977       GeneratedRTChecks &Check)
978       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
979                                        EPI, LVL, CM, BFI, PSI, Check) {}
980   /// Implements the interface for creating a vectorized skeleton using the
981   /// *main loop* strategy (ie the first pass of vplan execution).
982   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
983 
984 protected:
985   /// Emits an iteration count bypass check once for the main loop (when \p
986   /// ForEpilogue is false) and once for the epilogue loop (when \p
987   /// ForEpilogue is true).
988   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
989                                              bool ForEpilogue);
990   void printDebugTracesAtStart() override;
991   void printDebugTracesAtEnd() override;
992 };
993 
994 // A specialized derived class of inner loop vectorizer that performs
995 // vectorization of *epilogue* loops in the process of vectorizing loops and
996 // their epilogues.
997 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
998 public:
999   EpilogueVectorizerEpilogueLoop(
1000       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
1001       DominatorTree *DT, const TargetLibraryInfo *TLI,
1002       const TargetTransformInfo *TTI, AssumptionCache *AC,
1003       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1004       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1005       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1006       GeneratedRTChecks &Checks)
1007       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1008                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1009   /// Implements the interface for creating a vectorized skeleton using the
1010   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1011   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1012 
1013 protected:
1014   /// Emits an iteration count bypass check after the main vector loop has
1015   /// finished to see if there are any iterations left to execute by either
1016   /// the vector epilogue or the scalar epilogue.
1017   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1018                                                       BasicBlock *Bypass,
1019                                                       BasicBlock *Insert);
1020   void printDebugTracesAtStart() override;
1021   void printDebugTracesAtEnd() override;
1022 };
1023 } // end namespace llvm
1024 
1025 /// Look for a meaningful debug location on the instruction or it's
1026 /// operands.
1027 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1028   if (!I)
1029     return I;
1030 
1031   DebugLoc Empty;
1032   if (I->getDebugLoc() != Empty)
1033     return I;
1034 
1035   for (Use &Op : I->operands()) {
1036     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1037       if (OpInst->getDebugLoc() != Empty)
1038         return OpInst;
1039   }
1040 
1041   return I;
1042 }
1043 
1044 void InnerLoopVectorizer::setDebugLocFromInst(
1045     const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
1046   IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
1047   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
1048     const DILocation *DIL = Inst->getDebugLoc();
1049 
1050     // When a FSDiscriminator is enabled, we don't need to add the multiply
1051     // factors to the discriminators.
1052     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1053         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1054       // FIXME: For scalable vectors, assume vscale=1.
1055       auto NewDIL =
1056           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1057       if (NewDIL)
1058         B->SetCurrentDebugLocation(NewDIL.getValue());
1059       else
1060         LLVM_DEBUG(dbgs()
1061                    << "Failed to create new discriminator: "
1062                    << DIL->getFilename() << " Line: " << DIL->getLine());
1063     } else
1064       B->SetCurrentDebugLocation(DIL);
1065   } else
1066     B->SetCurrentDebugLocation(DebugLoc());
1067 }
1068 
1069 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1070 /// is passed, the message relates to that particular instruction.
1071 #ifndef NDEBUG
1072 static void debugVectorizationMessage(const StringRef Prefix,
1073                                       const StringRef DebugMsg,
1074                                       Instruction *I) {
1075   dbgs() << "LV: " << Prefix << DebugMsg;
1076   if (I != nullptr)
1077     dbgs() << " " << *I;
1078   else
1079     dbgs() << '.';
1080   dbgs() << '\n';
1081 }
1082 #endif
1083 
1084 /// Create an analysis remark that explains why vectorization failed
1085 ///
1086 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1087 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1088 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1089 /// the location of the remark.  \return the remark object that can be
1090 /// streamed to.
1091 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1092     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1093   Value *CodeRegion = TheLoop->getHeader();
1094   DebugLoc DL = TheLoop->getStartLoc();
1095 
1096   if (I) {
1097     CodeRegion = I->getParent();
1098     // If there is no debug location attached to the instruction, revert back to
1099     // using the loop's.
1100     if (I->getDebugLoc())
1101       DL = I->getDebugLoc();
1102   }
1103 
1104   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1105 }
1106 
1107 /// Return a value for Step multiplied by VF.
1108 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1109   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1110   Constant *StepVal = ConstantInt::get(
1111       Step->getType(),
1112       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1113   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1114 }
1115 
1116 namespace llvm {
1117 
1118 /// Return the runtime value for VF.
1119 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1120   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1121   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1122 }
1123 
1124 void reportVectorizationFailure(const StringRef DebugMsg,
1125                                 const StringRef OREMsg, const StringRef ORETag,
1126                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1127                                 Instruction *I) {
1128   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1129   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1130   ORE->emit(
1131       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1132       << "loop not vectorized: " << OREMsg);
1133 }
1134 
1135 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1136                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1137                              Instruction *I) {
1138   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1139   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1140   ORE->emit(
1141       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1142       << Msg);
1143 }
1144 
1145 } // end namespace llvm
1146 
1147 #ifndef NDEBUG
1148 /// \return string containing a file name and a line # for the given loop.
1149 static std::string getDebugLocString(const Loop *L) {
1150   std::string Result;
1151   if (L) {
1152     raw_string_ostream OS(Result);
1153     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1154       LoopDbgLoc.print(OS);
1155     else
1156       // Just print the module name.
1157       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1158     OS.flush();
1159   }
1160   return Result;
1161 }
1162 #endif
1163 
1164 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1165                                          const Instruction *Orig) {
1166   // If the loop was versioned with memchecks, add the corresponding no-alias
1167   // metadata.
1168   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1169     LVer->annotateInstWithNoAlias(To, Orig);
1170 }
1171 
1172 void InnerLoopVectorizer::addMetadata(Instruction *To,
1173                                       Instruction *From) {
1174   propagateMetadata(To, From);
1175   addNewMetadata(To, From);
1176 }
1177 
1178 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1179                                       Instruction *From) {
1180   for (Value *V : To) {
1181     if (Instruction *I = dyn_cast<Instruction>(V))
1182       addMetadata(I, From);
1183   }
1184 }
1185 
1186 namespace llvm {
1187 
1188 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1189 // lowered.
1190 enum ScalarEpilogueLowering {
1191 
1192   // The default: allowing scalar epilogues.
1193   CM_ScalarEpilogueAllowed,
1194 
1195   // Vectorization with OptForSize: don't allow epilogues.
1196   CM_ScalarEpilogueNotAllowedOptSize,
1197 
1198   // A special case of vectorisation with OptForSize: loops with a very small
1199   // trip count are considered for vectorization under OptForSize, thereby
1200   // making sure the cost of their loop body is dominant, free of runtime
1201   // guards and scalar iteration overheads.
1202   CM_ScalarEpilogueNotAllowedLowTripLoop,
1203 
1204   // Loop hint predicate indicating an epilogue is undesired.
1205   CM_ScalarEpilogueNotNeededUsePredicate,
1206 
1207   // Directive indicating we must either tail fold or not vectorize
1208   CM_ScalarEpilogueNotAllowedUsePredicate
1209 };
1210 
1211 /// ElementCountComparator creates a total ordering for ElementCount
1212 /// for the purposes of using it in a set structure.
1213 struct ElementCountComparator {
1214   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1215     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1216            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1217   }
1218 };
1219 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1220 
1221 /// LoopVectorizationCostModel - estimates the expected speedups due to
1222 /// vectorization.
1223 /// In many cases vectorization is not profitable. This can happen because of
1224 /// a number of reasons. In this class we mainly attempt to predict the
1225 /// expected speedup/slowdowns due to the supported instruction set. We use the
1226 /// TargetTransformInfo to query the different backends for the cost of
1227 /// different operations.
1228 class LoopVectorizationCostModel {
1229 public:
1230   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1231                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1232                              LoopVectorizationLegality *Legal,
1233                              const TargetTransformInfo &TTI,
1234                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1235                              AssumptionCache *AC,
1236                              OptimizationRemarkEmitter *ORE, const Function *F,
1237                              const LoopVectorizeHints *Hints,
1238                              InterleavedAccessInfo &IAI)
1239       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1240         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1241         Hints(Hints), InterleaveInfo(IAI) {}
1242 
1243   /// \return An upper bound for the vectorization factors (both fixed and
1244   /// scalable). If the factors are 0, vectorization and interleaving should be
1245   /// avoided up front.
1246   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1247 
1248   /// \return True if runtime checks are required for vectorization, and false
1249   /// otherwise.
1250   bool runtimeChecksRequired();
1251 
1252   /// \return The most profitable vectorization factor and the cost of that VF.
1253   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1254   /// then this vectorization factor will be selected if vectorization is
1255   /// possible.
1256   VectorizationFactor
1257   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1258 
1259   VectorizationFactor
1260   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1261                                     const LoopVectorizationPlanner &LVP);
1262 
1263   /// Setup cost-based decisions for user vectorization factor.
1264   /// \return true if the UserVF is a feasible VF to be chosen.
1265   bool selectUserVectorizationFactor(ElementCount UserVF) {
1266     collectUniformsAndScalars(UserVF);
1267     collectInstsToScalarize(UserVF);
1268     return expectedCost(UserVF).first.isValid();
1269   }
1270 
1271   /// \return The size (in bits) of the smallest and widest types in the code
1272   /// that needs to be vectorized. We ignore values that remain scalar such as
1273   /// 64 bit loop indices.
1274   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1275 
1276   /// \return The desired interleave count.
1277   /// If interleave count has been specified by metadata it will be returned.
1278   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1279   /// are the selected vectorization factor and the cost of the selected VF.
1280   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1281 
1282   /// Memory access instruction may be vectorized in more than one way.
1283   /// Form of instruction after vectorization depends on cost.
1284   /// This function takes cost-based decisions for Load/Store instructions
1285   /// and collects them in a map. This decisions map is used for building
1286   /// the lists of loop-uniform and loop-scalar instructions.
1287   /// The calculated cost is saved with widening decision in order to
1288   /// avoid redundant calculations.
1289   void setCostBasedWideningDecision(ElementCount VF);
1290 
1291   /// A struct that represents some properties of the register usage
1292   /// of a loop.
1293   struct RegisterUsage {
1294     /// Holds the number of loop invariant values that are used in the loop.
1295     /// The key is ClassID of target-provided register class.
1296     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1297     /// Holds the maximum number of concurrent live intervals in the loop.
1298     /// The key is ClassID of target-provided register class.
1299     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1300   };
1301 
1302   /// \return Returns information about the register usages of the loop for the
1303   /// given vectorization factors.
1304   SmallVector<RegisterUsage, 8>
1305   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1306 
1307   /// Collect values we want to ignore in the cost model.
1308   void collectValuesToIgnore();
1309 
1310   /// Collect all element types in the loop for which widening is needed.
1311   void collectElementTypesForWidening();
1312 
1313   /// Split reductions into those that happen in the loop, and those that happen
1314   /// outside. In loop reductions are collected into InLoopReductionChains.
1315   void collectInLoopReductions();
1316 
1317   /// Returns true if we should use strict in-order reductions for the given
1318   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1319   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1320   /// of FP operations.
1321   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1322     return EnableStrictReductions && !Hints->allowReordering() &&
1323            RdxDesc.isOrdered();
1324   }
1325 
1326   /// \returns The smallest bitwidth each instruction can be represented with.
1327   /// The vector equivalents of these instructions should be truncated to this
1328   /// type.
1329   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1330     return MinBWs;
1331   }
1332 
1333   /// \returns True if it is more profitable to scalarize instruction \p I for
1334   /// vectorization factor \p VF.
1335   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1336     assert(VF.isVector() &&
1337            "Profitable to scalarize relevant only for VF > 1.");
1338 
1339     // Cost model is not run in the VPlan-native path - return conservative
1340     // result until this changes.
1341     if (EnableVPlanNativePath)
1342       return false;
1343 
1344     auto Scalars = InstsToScalarize.find(VF);
1345     assert(Scalars != InstsToScalarize.end() &&
1346            "VF not yet analyzed for scalarization profitability");
1347     return Scalars->second.find(I) != Scalars->second.end();
1348   }
1349 
1350   /// Returns true if \p I is known to be uniform after vectorization.
1351   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1352     if (VF.isScalar())
1353       return true;
1354 
1355     // Cost model is not run in the VPlan-native path - return conservative
1356     // result until this changes.
1357     if (EnableVPlanNativePath)
1358       return false;
1359 
1360     auto UniformsPerVF = Uniforms.find(VF);
1361     assert(UniformsPerVF != Uniforms.end() &&
1362            "VF not yet analyzed for uniformity");
1363     return UniformsPerVF->second.count(I);
1364   }
1365 
1366   /// Returns true if \p I is known to be scalar after vectorization.
1367   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1368     if (VF.isScalar())
1369       return true;
1370 
1371     // Cost model is not run in the VPlan-native path - return conservative
1372     // result until this changes.
1373     if (EnableVPlanNativePath)
1374       return false;
1375 
1376     auto ScalarsPerVF = Scalars.find(VF);
1377     assert(ScalarsPerVF != Scalars.end() &&
1378            "Scalar values are not calculated for VF");
1379     return ScalarsPerVF->second.count(I);
1380   }
1381 
1382   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1383   /// for vectorization factor \p VF.
1384   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1385     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1386            !isProfitableToScalarize(I, VF) &&
1387            !isScalarAfterVectorization(I, VF);
1388   }
1389 
1390   /// Decision that was taken during cost calculation for memory instruction.
1391   enum InstWidening {
1392     CM_Unknown,
1393     CM_Widen,         // For consecutive accesses with stride +1.
1394     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1395     CM_Interleave,
1396     CM_GatherScatter,
1397     CM_Scalarize
1398   };
1399 
1400   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1401   /// instruction \p I and vector width \p VF.
1402   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1403                            InstructionCost Cost) {
1404     assert(VF.isVector() && "Expected VF >=2");
1405     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1406   }
1407 
1408   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1409   /// interleaving group \p Grp and vector width \p VF.
1410   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1411                            ElementCount VF, InstWidening W,
1412                            InstructionCost Cost) {
1413     assert(VF.isVector() && "Expected VF >=2");
1414     /// Broadcast this decicion to all instructions inside the group.
1415     /// But the cost will be assigned to one instruction only.
1416     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1417       if (auto *I = Grp->getMember(i)) {
1418         if (Grp->getInsertPos() == I)
1419           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1420         else
1421           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1422       }
1423     }
1424   }
1425 
1426   /// Return the cost model decision for the given instruction \p I and vector
1427   /// width \p VF. Return CM_Unknown if this instruction did not pass
1428   /// through the cost modeling.
1429   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1430     assert(VF.isVector() && "Expected VF to be a vector VF");
1431     // Cost model is not run in the VPlan-native path - return conservative
1432     // result until this changes.
1433     if (EnableVPlanNativePath)
1434       return CM_GatherScatter;
1435 
1436     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1437     auto Itr = WideningDecisions.find(InstOnVF);
1438     if (Itr == WideningDecisions.end())
1439       return CM_Unknown;
1440     return Itr->second.first;
1441   }
1442 
1443   /// Return the vectorization cost for the given instruction \p I and vector
1444   /// width \p VF.
1445   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1446     assert(VF.isVector() && "Expected VF >=2");
1447     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1448     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1449            "The cost is not calculated");
1450     return WideningDecisions[InstOnVF].second;
1451   }
1452 
1453   /// Return True if instruction \p I is an optimizable truncate whose operand
1454   /// is an induction variable. Such a truncate will be removed by adding a new
1455   /// induction variable with the destination type.
1456   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1457     // If the instruction is not a truncate, return false.
1458     auto *Trunc = dyn_cast<TruncInst>(I);
1459     if (!Trunc)
1460       return false;
1461 
1462     // Get the source and destination types of the truncate.
1463     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1464     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1465 
1466     // If the truncate is free for the given types, return false. Replacing a
1467     // free truncate with an induction variable would add an induction variable
1468     // update instruction to each iteration of the loop. We exclude from this
1469     // check the primary induction variable since it will need an update
1470     // instruction regardless.
1471     Value *Op = Trunc->getOperand(0);
1472     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1473       return false;
1474 
1475     // If the truncated value is not an induction variable, return false.
1476     return Legal->isInductionPhi(Op);
1477   }
1478 
1479   /// Collects the instructions to scalarize for each predicated instruction in
1480   /// the loop.
1481   void collectInstsToScalarize(ElementCount VF);
1482 
1483   /// Collect Uniform and Scalar values for the given \p VF.
1484   /// The sets depend on CM decision for Load/Store instructions
1485   /// that may be vectorized as interleave, gather-scatter or scalarized.
1486   void collectUniformsAndScalars(ElementCount VF) {
1487     // Do the analysis once.
1488     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1489       return;
1490     setCostBasedWideningDecision(VF);
1491     collectLoopUniforms(VF);
1492     collectLoopScalars(VF);
1493   }
1494 
1495   /// Returns true if the target machine supports masked store operation
1496   /// for the given \p DataType and kind of access to \p Ptr.
1497   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1498     return Legal->isConsecutivePtr(Ptr) &&
1499            TTI.isLegalMaskedStore(DataType, Alignment);
1500   }
1501 
1502   /// Returns true if the target machine supports masked load operation
1503   /// for the given \p DataType and kind of access to \p Ptr.
1504   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1505     return Legal->isConsecutivePtr(Ptr) &&
1506            TTI.isLegalMaskedLoad(DataType, Alignment);
1507   }
1508 
1509   /// Returns true if the target machine can represent \p V as a masked gather
1510   /// or scatter operation.
1511   bool isLegalGatherOrScatter(Value *V) {
1512     bool LI = isa<LoadInst>(V);
1513     bool SI = isa<StoreInst>(V);
1514     if (!LI && !SI)
1515       return false;
1516     auto *Ty = getLoadStoreType(V);
1517     Align Align = getLoadStoreAlignment(V);
1518     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1519            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1520   }
1521 
1522   /// Returns true if the target machine supports all of the reduction
1523   /// variables found for the given VF.
1524   bool canVectorizeReductions(ElementCount VF) const {
1525     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1526       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1527       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1528     }));
1529   }
1530 
1531   /// Returns true if \p I is an instruction that will be scalarized with
1532   /// predication. Such instructions include conditional stores and
1533   /// instructions that may divide by zero.
1534   /// If a non-zero VF has been calculated, we check if I will be scalarized
1535   /// predication for that VF.
1536   bool isScalarWithPredication(Instruction *I) const;
1537 
1538   // Returns true if \p I is an instruction that will be predicated either
1539   // through scalar predication or masked load/store or masked gather/scatter.
1540   // Superset of instructions that return true for isScalarWithPredication.
1541   bool isPredicatedInst(Instruction *I) {
1542     if (!blockNeedsPredication(I->getParent()))
1543       return false;
1544     // Loads and stores that need some form of masked operation are predicated
1545     // instructions.
1546     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1547       return Legal->isMaskRequired(I);
1548     return isScalarWithPredication(I);
1549   }
1550 
1551   /// Returns true if \p I is a memory instruction with consecutive memory
1552   /// access that can be widened.
1553   bool
1554   memoryInstructionCanBeWidened(Instruction *I,
1555                                 ElementCount VF = ElementCount::getFixed(1));
1556 
1557   /// Returns true if \p I is a memory instruction in an interleaved-group
1558   /// of memory accesses that can be vectorized with wide vector loads/stores
1559   /// and shuffles.
1560   bool
1561   interleavedAccessCanBeWidened(Instruction *I,
1562                                 ElementCount VF = ElementCount::getFixed(1));
1563 
1564   /// Check if \p Instr belongs to any interleaved access group.
1565   bool isAccessInterleaved(Instruction *Instr) {
1566     return InterleaveInfo.isInterleaved(Instr);
1567   }
1568 
1569   /// Get the interleaved access group that \p Instr belongs to.
1570   const InterleaveGroup<Instruction> *
1571   getInterleavedAccessGroup(Instruction *Instr) {
1572     return InterleaveInfo.getInterleaveGroup(Instr);
1573   }
1574 
1575   /// Returns true if we're required to use a scalar epilogue for at least
1576   /// the final iteration of the original loop.
1577   bool requiresScalarEpilogue(ElementCount VF) const {
1578     if (!isScalarEpilogueAllowed())
1579       return false;
1580     // If we might exit from anywhere but the latch, must run the exiting
1581     // iteration in scalar form.
1582     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1583       return true;
1584     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1585   }
1586 
1587   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1588   /// loop hint annotation.
1589   bool isScalarEpilogueAllowed() const {
1590     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1591   }
1592 
1593   /// Returns true if all loop blocks should be masked to fold tail loop.
1594   bool foldTailByMasking() const { return FoldTailByMasking; }
1595 
1596   bool blockNeedsPredication(BasicBlock *BB) const {
1597     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1598   }
1599 
1600   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1601   /// nodes to the chain of instructions representing the reductions. Uses a
1602   /// MapVector to ensure deterministic iteration order.
1603   using ReductionChainMap =
1604       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1605 
1606   /// Return the chain of instructions representing an inloop reduction.
1607   const ReductionChainMap &getInLoopReductionChains() const {
1608     return InLoopReductionChains;
1609   }
1610 
1611   /// Returns true if the Phi is part of an inloop reduction.
1612   bool isInLoopReduction(PHINode *Phi) const {
1613     return InLoopReductionChains.count(Phi);
1614   }
1615 
1616   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1617   /// with factor VF.  Return the cost of the instruction, including
1618   /// scalarization overhead if it's needed.
1619   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1620 
1621   /// Estimate cost of a call instruction CI if it were vectorized with factor
1622   /// VF. Return the cost of the instruction, including scalarization overhead
1623   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1624   /// scalarized -
1625   /// i.e. either vector version isn't available, or is too expensive.
1626   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1627                                     bool &NeedToScalarize) const;
1628 
1629   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1630   /// that of B.
1631   bool isMoreProfitable(const VectorizationFactor &A,
1632                         const VectorizationFactor &B) const;
1633 
1634   /// Invalidates decisions already taken by the cost model.
1635   void invalidateCostModelingDecisions() {
1636     WideningDecisions.clear();
1637     Uniforms.clear();
1638     Scalars.clear();
1639   }
1640 
1641 private:
1642   unsigned NumPredStores = 0;
1643 
1644   /// \return An upper bound for the vectorization factors for both
1645   /// fixed and scalable vectorization, where the minimum-known number of
1646   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1647   /// disabled or unsupported, then the scalable part will be equal to
1648   /// ElementCount::getScalable(0).
1649   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1650                                            ElementCount UserVF);
1651 
1652   /// \return the maximized element count based on the targets vector
1653   /// registers and the loop trip-count, but limited to a maximum safe VF.
1654   /// This is a helper function of computeFeasibleMaxVF.
1655   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1656   /// issue that occurred on one of the buildbots which cannot be reproduced
1657   /// without having access to the properietary compiler (see comments on
1658   /// D98509). The issue is currently under investigation and this workaround
1659   /// will be removed as soon as possible.
1660   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1661                                        unsigned SmallestType,
1662                                        unsigned WidestType,
1663                                        const ElementCount &MaxSafeVF);
1664 
1665   /// \return the maximum legal scalable VF, based on the safe max number
1666   /// of elements.
1667   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1668 
1669   /// The vectorization cost is a combination of the cost itself and a boolean
1670   /// indicating whether any of the contributing operations will actually
1671   /// operate on vector values after type legalization in the backend. If this
1672   /// latter value is false, then all operations will be scalarized (i.e. no
1673   /// vectorization has actually taken place).
1674   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1675 
1676   /// Returns the expected execution cost. The unit of the cost does
1677   /// not matter because we use the 'cost' units to compare different
1678   /// vector widths. The cost that is returned is *not* normalized by
1679   /// the factor width. If \p Invalid is not nullptr, this function
1680   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1681   /// each instruction that has an Invalid cost for the given VF.
1682   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1683   VectorizationCostTy
1684   expectedCost(ElementCount VF,
1685                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1686 
1687   /// Returns the execution time cost of an instruction for a given vector
1688   /// width. Vector width of one means scalar.
1689   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1690 
1691   /// The cost-computation logic from getInstructionCost which provides
1692   /// the vector type as an output parameter.
1693   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1694                                      Type *&VectorTy);
1695 
1696   /// Return the cost of instructions in an inloop reduction pattern, if I is
1697   /// part of that pattern.
1698   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1699                                           Type *VectorTy,
1700                                           TTI::TargetCostKind CostKind);
1701 
1702   /// Calculate vectorization cost of memory instruction \p I.
1703   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1704 
1705   /// The cost computation for scalarized memory instruction.
1706   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1707 
1708   /// The cost computation for interleaving group of memory instructions.
1709   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1710 
1711   /// The cost computation for Gather/Scatter instruction.
1712   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1713 
1714   /// The cost computation for widening instruction \p I with consecutive
1715   /// memory access.
1716   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1717 
1718   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1719   /// Load: scalar load + broadcast.
1720   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1721   /// element)
1722   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1723 
1724   /// Estimate the overhead of scalarizing an instruction. This is a
1725   /// convenience wrapper for the type-based getScalarizationOverhead API.
1726   InstructionCost getScalarizationOverhead(Instruction *I,
1727                                            ElementCount VF) const;
1728 
1729   /// Returns whether the instruction is a load or store and will be a emitted
1730   /// as a vector operation.
1731   bool isConsecutiveLoadOrStore(Instruction *I);
1732 
1733   /// Returns true if an artificially high cost for emulated masked memrefs
1734   /// should be used.
1735   bool useEmulatedMaskMemRefHack(Instruction *I);
1736 
1737   /// Map of scalar integer values to the smallest bitwidth they can be legally
1738   /// represented as. The vector equivalents of these values should be truncated
1739   /// to this type.
1740   MapVector<Instruction *, uint64_t> MinBWs;
1741 
1742   /// A type representing the costs for instructions if they were to be
1743   /// scalarized rather than vectorized. The entries are Instruction-Cost
1744   /// pairs.
1745   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1746 
1747   /// A set containing all BasicBlocks that are known to present after
1748   /// vectorization as a predicated block.
1749   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1750 
1751   /// Records whether it is allowed to have the original scalar loop execute at
1752   /// least once. This may be needed as a fallback loop in case runtime
1753   /// aliasing/dependence checks fail, or to handle the tail/remainder
1754   /// iterations when the trip count is unknown or doesn't divide by the VF,
1755   /// or as a peel-loop to handle gaps in interleave-groups.
1756   /// Under optsize and when the trip count is very small we don't allow any
1757   /// iterations to execute in the scalar loop.
1758   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1759 
1760   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1761   bool FoldTailByMasking = false;
1762 
1763   /// A map holding scalar costs for different vectorization factors. The
1764   /// presence of a cost for an instruction in the mapping indicates that the
1765   /// instruction will be scalarized when vectorizing with the associated
1766   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1767   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1768 
1769   /// Holds the instructions known to be uniform after vectorization.
1770   /// The data is collected per VF.
1771   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1772 
1773   /// Holds the instructions known to be scalar after vectorization.
1774   /// The data is collected per VF.
1775   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1776 
1777   /// Holds the instructions (address computations) that are forced to be
1778   /// scalarized.
1779   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1780 
1781   /// PHINodes of the reductions that should be expanded in-loop along with
1782   /// their associated chains of reduction operations, in program order from top
1783   /// (PHI) to bottom
1784   ReductionChainMap InLoopReductionChains;
1785 
1786   /// A Map of inloop reduction operations and their immediate chain operand.
1787   /// FIXME: This can be removed once reductions can be costed correctly in
1788   /// vplan. This was added to allow quick lookup to the inloop operations,
1789   /// without having to loop through InLoopReductionChains.
1790   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1791 
1792   /// Returns the expected difference in cost from scalarizing the expression
1793   /// feeding a predicated instruction \p PredInst. The instructions to
1794   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1795   /// non-negative return value implies the expression will be scalarized.
1796   /// Currently, only single-use chains are considered for scalarization.
1797   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1798                               ElementCount VF);
1799 
1800   /// Collect the instructions that are uniform after vectorization. An
1801   /// instruction is uniform if we represent it with a single scalar value in
1802   /// the vectorized loop corresponding to each vector iteration. Examples of
1803   /// uniform instructions include pointer operands of consecutive or
1804   /// interleaved memory accesses. Note that although uniformity implies an
1805   /// instruction will be scalar, the reverse is not true. In general, a
1806   /// scalarized instruction will be represented by VF scalar values in the
1807   /// vectorized loop, each corresponding to an iteration of the original
1808   /// scalar loop.
1809   void collectLoopUniforms(ElementCount VF);
1810 
1811   /// Collect the instructions that are scalar after vectorization. An
1812   /// instruction is scalar if it is known to be uniform or will be scalarized
1813   /// during vectorization. Non-uniform scalarized instructions will be
1814   /// represented by VF values in the vectorized loop, each corresponding to an
1815   /// iteration of the original scalar loop.
1816   void collectLoopScalars(ElementCount VF);
1817 
1818   /// Keeps cost model vectorization decision and cost for instructions.
1819   /// Right now it is used for memory instructions only.
1820   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1821                                 std::pair<InstWidening, InstructionCost>>;
1822 
1823   DecisionList WideningDecisions;
1824 
1825   /// Returns true if \p V is expected to be vectorized and it needs to be
1826   /// extracted.
1827   bool needsExtract(Value *V, ElementCount VF) const {
1828     Instruction *I = dyn_cast<Instruction>(V);
1829     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1830         TheLoop->isLoopInvariant(I))
1831       return false;
1832 
1833     // Assume we can vectorize V (and hence we need extraction) if the
1834     // scalars are not computed yet. This can happen, because it is called
1835     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1836     // the scalars are collected. That should be a safe assumption in most
1837     // cases, because we check if the operands have vectorizable types
1838     // beforehand in LoopVectorizationLegality.
1839     return Scalars.find(VF) == Scalars.end() ||
1840            !isScalarAfterVectorization(I, VF);
1841   };
1842 
1843   /// Returns a range containing only operands needing to be extracted.
1844   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1845                                                    ElementCount VF) const {
1846     return SmallVector<Value *, 4>(make_filter_range(
1847         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1848   }
1849 
1850   /// Determines if we have the infrastructure to vectorize loop \p L and its
1851   /// epilogue, assuming the main loop is vectorized by \p VF.
1852   bool isCandidateForEpilogueVectorization(const Loop &L,
1853                                            const ElementCount VF) const;
1854 
1855   /// Returns true if epilogue vectorization is considered profitable, and
1856   /// false otherwise.
1857   /// \p VF is the vectorization factor chosen for the original loop.
1858   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1859 
1860 public:
1861   /// The loop that we evaluate.
1862   Loop *TheLoop;
1863 
1864   /// Predicated scalar evolution analysis.
1865   PredicatedScalarEvolution &PSE;
1866 
1867   /// Loop Info analysis.
1868   LoopInfo *LI;
1869 
1870   /// Vectorization legality.
1871   LoopVectorizationLegality *Legal;
1872 
1873   /// Vector target information.
1874   const TargetTransformInfo &TTI;
1875 
1876   /// Target Library Info.
1877   const TargetLibraryInfo *TLI;
1878 
1879   /// Demanded bits analysis.
1880   DemandedBits *DB;
1881 
1882   /// Assumption cache.
1883   AssumptionCache *AC;
1884 
1885   /// Interface to emit optimization remarks.
1886   OptimizationRemarkEmitter *ORE;
1887 
1888   const Function *TheFunction;
1889 
1890   /// Loop Vectorize Hint.
1891   const LoopVectorizeHints *Hints;
1892 
1893   /// The interleave access information contains groups of interleaved accesses
1894   /// with the same stride and close to each other.
1895   InterleavedAccessInfo &InterleaveInfo;
1896 
1897   /// Values to ignore in the cost model.
1898   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1899 
1900   /// Values to ignore in the cost model when VF > 1.
1901   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1902 
1903   /// All element types found in the loop.
1904   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1905 
1906   /// Profitable vector factors.
1907   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1908 };
1909 } // end namespace llvm
1910 
1911 /// Helper struct to manage generating runtime checks for vectorization.
1912 ///
1913 /// The runtime checks are created up-front in temporary blocks to allow better
1914 /// estimating the cost and un-linked from the existing IR. After deciding to
1915 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1916 /// temporary blocks are completely removed.
1917 class GeneratedRTChecks {
1918   /// Basic block which contains the generated SCEV checks, if any.
1919   BasicBlock *SCEVCheckBlock = nullptr;
1920 
1921   /// The value representing the result of the generated SCEV checks. If it is
1922   /// nullptr, either no SCEV checks have been generated or they have been used.
1923   Value *SCEVCheckCond = nullptr;
1924 
1925   /// Basic block which contains the generated memory runtime checks, if any.
1926   BasicBlock *MemCheckBlock = nullptr;
1927 
1928   /// The value representing the result of the generated memory runtime checks.
1929   /// If it is nullptr, either no memory runtime checks have been generated or
1930   /// they have been used.
1931   Instruction *MemRuntimeCheckCond = nullptr;
1932 
1933   DominatorTree *DT;
1934   LoopInfo *LI;
1935 
1936   SCEVExpander SCEVExp;
1937   SCEVExpander MemCheckExp;
1938 
1939 public:
1940   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1941                     const DataLayout &DL)
1942       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1943         MemCheckExp(SE, DL, "scev.check") {}
1944 
1945   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1946   /// accurately estimate the cost of the runtime checks. The blocks are
1947   /// un-linked from the IR and is added back during vector code generation. If
1948   /// there is no vector code generation, the check blocks are removed
1949   /// completely.
1950   void Create(Loop *L, const LoopAccessInfo &LAI,
1951               const SCEVUnionPredicate &UnionPred) {
1952 
1953     BasicBlock *LoopHeader = L->getHeader();
1954     BasicBlock *Preheader = L->getLoopPreheader();
1955 
1956     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1957     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1958     // may be used by SCEVExpander. The blocks will be un-linked from their
1959     // predecessors and removed from LI & DT at the end of the function.
1960     if (!UnionPred.isAlwaysTrue()) {
1961       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1962                                   nullptr, "vector.scevcheck");
1963 
1964       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1965           &UnionPred, SCEVCheckBlock->getTerminator());
1966     }
1967 
1968     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1969     if (RtPtrChecking.Need) {
1970       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1971       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1972                                  "vector.memcheck");
1973 
1974       std::tie(std::ignore, MemRuntimeCheckCond) =
1975           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1976                            RtPtrChecking.getChecks(), MemCheckExp);
1977       assert(MemRuntimeCheckCond &&
1978              "no RT checks generated although RtPtrChecking "
1979              "claimed checks are required");
1980     }
1981 
1982     if (!MemCheckBlock && !SCEVCheckBlock)
1983       return;
1984 
1985     // Unhook the temporary block with the checks, update various places
1986     // accordingly.
1987     if (SCEVCheckBlock)
1988       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1989     if (MemCheckBlock)
1990       MemCheckBlock->replaceAllUsesWith(Preheader);
1991 
1992     if (SCEVCheckBlock) {
1993       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1994       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1995       Preheader->getTerminator()->eraseFromParent();
1996     }
1997     if (MemCheckBlock) {
1998       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1999       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2000       Preheader->getTerminator()->eraseFromParent();
2001     }
2002 
2003     DT->changeImmediateDominator(LoopHeader, Preheader);
2004     if (MemCheckBlock) {
2005       DT->eraseNode(MemCheckBlock);
2006       LI->removeBlock(MemCheckBlock);
2007     }
2008     if (SCEVCheckBlock) {
2009       DT->eraseNode(SCEVCheckBlock);
2010       LI->removeBlock(SCEVCheckBlock);
2011     }
2012   }
2013 
2014   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2015   /// unused.
2016   ~GeneratedRTChecks() {
2017     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2018     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2019     if (!SCEVCheckCond)
2020       SCEVCleaner.markResultUsed();
2021 
2022     if (!MemRuntimeCheckCond)
2023       MemCheckCleaner.markResultUsed();
2024 
2025     if (MemRuntimeCheckCond) {
2026       auto &SE = *MemCheckExp.getSE();
2027       // Memory runtime check generation creates compares that use expanded
2028       // values. Remove them before running the SCEVExpanderCleaners.
2029       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2030         if (MemCheckExp.isInsertedInstruction(&I))
2031           continue;
2032         SE.forgetValue(&I);
2033         SE.eraseValueFromMap(&I);
2034         I.eraseFromParent();
2035       }
2036     }
2037     MemCheckCleaner.cleanup();
2038     SCEVCleaner.cleanup();
2039 
2040     if (SCEVCheckCond)
2041       SCEVCheckBlock->eraseFromParent();
2042     if (MemRuntimeCheckCond)
2043       MemCheckBlock->eraseFromParent();
2044   }
2045 
2046   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2047   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2048   /// depending on the generated condition.
2049   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2050                              BasicBlock *LoopVectorPreHeader,
2051                              BasicBlock *LoopExitBlock) {
2052     if (!SCEVCheckCond)
2053       return nullptr;
2054     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2055       if (C->isZero())
2056         return nullptr;
2057 
2058     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2059 
2060     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2061     // Create new preheader for vector loop.
2062     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2063       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2064 
2065     SCEVCheckBlock->getTerminator()->eraseFromParent();
2066     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2067     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2068                                                 SCEVCheckBlock);
2069 
2070     DT->addNewBlock(SCEVCheckBlock, Pred);
2071     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2072 
2073     ReplaceInstWithInst(
2074         SCEVCheckBlock->getTerminator(),
2075         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2076     // Mark the check as used, to prevent it from being removed during cleanup.
2077     SCEVCheckCond = nullptr;
2078     return SCEVCheckBlock;
2079   }
2080 
2081   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2082   /// the branches to branch to the vector preheader or \p Bypass, depending on
2083   /// the generated condition.
2084   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2085                                    BasicBlock *LoopVectorPreHeader) {
2086     // Check if we generated code that checks in runtime if arrays overlap.
2087     if (!MemRuntimeCheckCond)
2088       return nullptr;
2089 
2090     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2091     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2092                                                 MemCheckBlock);
2093 
2094     DT->addNewBlock(MemCheckBlock, Pred);
2095     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2096     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2097 
2098     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2099       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2100 
2101     ReplaceInstWithInst(
2102         MemCheckBlock->getTerminator(),
2103         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2104     MemCheckBlock->getTerminator()->setDebugLoc(
2105         Pred->getTerminator()->getDebugLoc());
2106 
2107     // Mark the check as used, to prevent it from being removed during cleanup.
2108     MemRuntimeCheckCond = nullptr;
2109     return MemCheckBlock;
2110   }
2111 };
2112 
2113 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2114 // vectorization. The loop needs to be annotated with #pragma omp simd
2115 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2116 // vector length information is not provided, vectorization is not considered
2117 // explicit. Interleave hints are not allowed either. These limitations will be
2118 // relaxed in the future.
2119 // Please, note that we are currently forced to abuse the pragma 'clang
2120 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2121 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2122 // provides *explicit vectorization hints* (LV can bypass legal checks and
2123 // assume that vectorization is legal). However, both hints are implemented
2124 // using the same metadata (llvm.loop.vectorize, processed by
2125 // LoopVectorizeHints). This will be fixed in the future when the native IR
2126 // representation for pragma 'omp simd' is introduced.
2127 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2128                                    OptimizationRemarkEmitter *ORE) {
2129   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2130   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2131 
2132   // Only outer loops with an explicit vectorization hint are supported.
2133   // Unannotated outer loops are ignored.
2134   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2135     return false;
2136 
2137   Function *Fn = OuterLp->getHeader()->getParent();
2138   if (!Hints.allowVectorization(Fn, OuterLp,
2139                                 true /*VectorizeOnlyWhenForced*/)) {
2140     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2141     return false;
2142   }
2143 
2144   if (Hints.getInterleave() > 1) {
2145     // TODO: Interleave support is future work.
2146     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2147                          "outer loops.\n");
2148     Hints.emitRemarkWithHints();
2149     return false;
2150   }
2151 
2152   return true;
2153 }
2154 
2155 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2156                                   OptimizationRemarkEmitter *ORE,
2157                                   SmallVectorImpl<Loop *> &V) {
2158   // Collect inner loops and outer loops without irreducible control flow. For
2159   // now, only collect outer loops that have explicit vectorization hints. If we
2160   // are stress testing the VPlan H-CFG construction, we collect the outermost
2161   // loop of every loop nest.
2162   if (L.isInnermost() || VPlanBuildStressTest ||
2163       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2164     LoopBlocksRPO RPOT(&L);
2165     RPOT.perform(LI);
2166     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2167       V.push_back(&L);
2168       // TODO: Collect inner loops inside marked outer loops in case
2169       // vectorization fails for the outer loop. Do not invoke
2170       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2171       // already known to be reducible. We can use an inherited attribute for
2172       // that.
2173       return;
2174     }
2175   }
2176   for (Loop *InnerL : L)
2177     collectSupportedLoops(*InnerL, LI, ORE, V);
2178 }
2179 
2180 namespace {
2181 
2182 /// The LoopVectorize Pass.
2183 struct LoopVectorize : public FunctionPass {
2184   /// Pass identification, replacement for typeid
2185   static char ID;
2186 
2187   LoopVectorizePass Impl;
2188 
2189   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2190                          bool VectorizeOnlyWhenForced = false)
2191       : FunctionPass(ID),
2192         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2193     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2194   }
2195 
2196   bool runOnFunction(Function &F) override {
2197     if (skipFunction(F))
2198       return false;
2199 
2200     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2201     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2202     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2203     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2204     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2205     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2206     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2207     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2208     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2209     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2210     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2211     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2212     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2213 
2214     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2215         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2216 
2217     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2218                         GetLAA, *ORE, PSI).MadeAnyChange;
2219   }
2220 
2221   void getAnalysisUsage(AnalysisUsage &AU) const override {
2222     AU.addRequired<AssumptionCacheTracker>();
2223     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2224     AU.addRequired<DominatorTreeWrapperPass>();
2225     AU.addRequired<LoopInfoWrapperPass>();
2226     AU.addRequired<ScalarEvolutionWrapperPass>();
2227     AU.addRequired<TargetTransformInfoWrapperPass>();
2228     AU.addRequired<AAResultsWrapperPass>();
2229     AU.addRequired<LoopAccessLegacyAnalysis>();
2230     AU.addRequired<DemandedBitsWrapperPass>();
2231     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2232     AU.addRequired<InjectTLIMappingsLegacy>();
2233 
2234     // We currently do not preserve loopinfo/dominator analyses with outer loop
2235     // vectorization. Until this is addressed, mark these analyses as preserved
2236     // only for non-VPlan-native path.
2237     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2238     if (!EnableVPlanNativePath) {
2239       AU.addPreserved<LoopInfoWrapperPass>();
2240       AU.addPreserved<DominatorTreeWrapperPass>();
2241     }
2242 
2243     AU.addPreserved<BasicAAWrapperPass>();
2244     AU.addPreserved<GlobalsAAWrapperPass>();
2245     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2246   }
2247 };
2248 
2249 } // end anonymous namespace
2250 
2251 //===----------------------------------------------------------------------===//
2252 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2253 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2254 //===----------------------------------------------------------------------===//
2255 
2256 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2257   // We need to place the broadcast of invariant variables outside the loop,
2258   // but only if it's proven safe to do so. Else, broadcast will be inside
2259   // vector loop body.
2260   Instruction *Instr = dyn_cast<Instruction>(V);
2261   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2262                      (!Instr ||
2263                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2264   // Place the code for broadcasting invariant variables in the new preheader.
2265   IRBuilder<>::InsertPointGuard Guard(Builder);
2266   if (SafeToHoist)
2267     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2268 
2269   // Broadcast the scalar into all locations in the vector.
2270   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2271 
2272   return Shuf;
2273 }
2274 
2275 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2276     const InductionDescriptor &II, Value *Step, Value *Start,
2277     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2278     VPTransformState &State) {
2279   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2280          "Expected either an induction phi-node or a truncate of it!");
2281 
2282   // Construct the initial value of the vector IV in the vector loop preheader
2283   auto CurrIP = Builder.saveIP();
2284   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2285   if (isa<TruncInst>(EntryVal)) {
2286     assert(Start->getType()->isIntegerTy() &&
2287            "Truncation requires an integer type");
2288     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2289     Step = Builder.CreateTrunc(Step, TruncType);
2290     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2291   }
2292   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2293   Value *SteppedStart =
2294       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2295 
2296   // We create vector phi nodes for both integer and floating-point induction
2297   // variables. Here, we determine the kind of arithmetic we will perform.
2298   Instruction::BinaryOps AddOp;
2299   Instruction::BinaryOps MulOp;
2300   if (Step->getType()->isIntegerTy()) {
2301     AddOp = Instruction::Add;
2302     MulOp = Instruction::Mul;
2303   } else {
2304     AddOp = II.getInductionOpcode();
2305     MulOp = Instruction::FMul;
2306   }
2307 
2308   // Multiply the vectorization factor by the step using integer or
2309   // floating-point arithmetic as appropriate.
2310   Type *StepType = Step->getType();
2311   if (Step->getType()->isFloatingPointTy())
2312     StepType = IntegerType::get(StepType->getContext(),
2313                                 StepType->getScalarSizeInBits());
2314   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2315   if (Step->getType()->isFloatingPointTy())
2316     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2317   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2318 
2319   // Create a vector splat to use in the induction update.
2320   //
2321   // FIXME: If the step is non-constant, we create the vector splat with
2322   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2323   //        handle a constant vector splat.
2324   Value *SplatVF = isa<Constant>(Mul)
2325                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2326                        : Builder.CreateVectorSplat(VF, Mul);
2327   Builder.restoreIP(CurrIP);
2328 
2329   // We may need to add the step a number of times, depending on the unroll
2330   // factor. The last of those goes into the PHI.
2331   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2332                                     &*LoopVectorBody->getFirstInsertionPt());
2333   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2334   Instruction *LastInduction = VecInd;
2335   for (unsigned Part = 0; Part < UF; ++Part) {
2336     State.set(Def, LastInduction, Part);
2337 
2338     if (isa<TruncInst>(EntryVal))
2339       addMetadata(LastInduction, EntryVal);
2340     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2341                                           State, Part);
2342 
2343     LastInduction = cast<Instruction>(
2344         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2345     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2346   }
2347 
2348   // Move the last step to the end of the latch block. This ensures consistent
2349   // placement of all induction updates.
2350   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2351   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2352   auto *ICmp = cast<Instruction>(Br->getCondition());
2353   LastInduction->moveBefore(ICmp);
2354   LastInduction->setName("vec.ind.next");
2355 
2356   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2357   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2358 }
2359 
2360 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2361   return Cost->isScalarAfterVectorization(I, VF) ||
2362          Cost->isProfitableToScalarize(I, VF);
2363 }
2364 
2365 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2366   if (shouldScalarizeInstruction(IV))
2367     return true;
2368   auto isScalarInst = [&](User *U) -> bool {
2369     auto *I = cast<Instruction>(U);
2370     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2371   };
2372   return llvm::any_of(IV->users(), isScalarInst);
2373 }
2374 
2375 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2376     const InductionDescriptor &ID, const Instruction *EntryVal,
2377     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2378     unsigned Part, unsigned Lane) {
2379   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2380          "Expected either an induction phi-node or a truncate of it!");
2381 
2382   // This induction variable is not the phi from the original loop but the
2383   // newly-created IV based on the proof that casted Phi is equal to the
2384   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2385   // re-uses the same InductionDescriptor that original IV uses but we don't
2386   // have to do any recording in this case - that is done when original IV is
2387   // processed.
2388   if (isa<TruncInst>(EntryVal))
2389     return;
2390 
2391   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2392   if (Casts.empty())
2393     return;
2394   // Only the first Cast instruction in the Casts vector is of interest.
2395   // The rest of the Casts (if exist) have no uses outside the
2396   // induction update chain itself.
2397   if (Lane < UINT_MAX)
2398     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2399   else
2400     State.set(CastDef, VectorLoopVal, Part);
2401 }
2402 
2403 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2404                                                 TruncInst *Trunc, VPValue *Def,
2405                                                 VPValue *CastDef,
2406                                                 VPTransformState &State) {
2407   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2408          "Primary induction variable must have an integer type");
2409 
2410   auto II = Legal->getInductionVars().find(IV);
2411   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2412 
2413   auto ID = II->second;
2414   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2415 
2416   // The value from the original loop to which we are mapping the new induction
2417   // variable.
2418   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2419 
2420   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2421 
2422   // Generate code for the induction step. Note that induction steps are
2423   // required to be loop-invariant
2424   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2425     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2426            "Induction step should be loop invariant");
2427     if (PSE.getSE()->isSCEVable(IV->getType())) {
2428       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2429       return Exp.expandCodeFor(Step, Step->getType(),
2430                                LoopVectorPreHeader->getTerminator());
2431     }
2432     return cast<SCEVUnknown>(Step)->getValue();
2433   };
2434 
2435   // The scalar value to broadcast. This is derived from the canonical
2436   // induction variable. If a truncation type is given, truncate the canonical
2437   // induction variable and step. Otherwise, derive these values from the
2438   // induction descriptor.
2439   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2440     Value *ScalarIV = Induction;
2441     if (IV != OldInduction) {
2442       ScalarIV = IV->getType()->isIntegerTy()
2443                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2444                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2445                                           IV->getType());
2446       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2447       ScalarIV->setName("offset.idx");
2448     }
2449     if (Trunc) {
2450       auto *TruncType = cast<IntegerType>(Trunc->getType());
2451       assert(Step->getType()->isIntegerTy() &&
2452              "Truncation requires an integer step");
2453       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2454       Step = Builder.CreateTrunc(Step, TruncType);
2455     }
2456     return ScalarIV;
2457   };
2458 
2459   // Create the vector values from the scalar IV, in the absence of creating a
2460   // vector IV.
2461   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2462     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2463     for (unsigned Part = 0; Part < UF; ++Part) {
2464       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2465       Value *EntryPart =
2466           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2467                         ID.getInductionOpcode());
2468       State.set(Def, EntryPart, Part);
2469       if (Trunc)
2470         addMetadata(EntryPart, Trunc);
2471       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2472                                             State, Part);
2473     }
2474   };
2475 
2476   // Fast-math-flags propagate from the original induction instruction.
2477   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2478   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2479     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2480 
2481   // Now do the actual transformations, and start with creating the step value.
2482   Value *Step = CreateStepValue(ID.getStep());
2483   if (VF.isZero() || VF.isScalar()) {
2484     Value *ScalarIV = CreateScalarIV(Step);
2485     CreateSplatIV(ScalarIV, Step);
2486     return;
2487   }
2488 
2489   // Determine if we want a scalar version of the induction variable. This is
2490   // true if the induction variable itself is not widened, or if it has at
2491   // least one user in the loop that is not widened.
2492   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2493   if (!NeedsScalarIV) {
2494     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2495                                     State);
2496     return;
2497   }
2498 
2499   // Try to create a new independent vector induction variable. If we can't
2500   // create the phi node, we will splat the scalar induction variable in each
2501   // loop iteration.
2502   if (!shouldScalarizeInstruction(EntryVal)) {
2503     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2504                                     State);
2505     Value *ScalarIV = CreateScalarIV(Step);
2506     // Create scalar steps that can be used by instructions we will later
2507     // scalarize. Note that the addition of the scalar steps will not increase
2508     // the number of instructions in the loop in the common case prior to
2509     // InstCombine. We will be trading one vector extract for each scalar step.
2510     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2511     return;
2512   }
2513 
2514   // All IV users are scalar instructions, so only emit a scalar IV, not a
2515   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2516   // predicate used by the masked loads/stores.
2517   Value *ScalarIV = CreateScalarIV(Step);
2518   if (!Cost->isScalarEpilogueAllowed())
2519     CreateSplatIV(ScalarIV, Step);
2520   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2521 }
2522 
2523 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2524                                           Instruction::BinaryOps BinOp) {
2525   // Create and check the types.
2526   auto *ValVTy = cast<VectorType>(Val->getType());
2527   ElementCount VLen = ValVTy->getElementCount();
2528 
2529   Type *STy = Val->getType()->getScalarType();
2530   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2531          "Induction Step must be an integer or FP");
2532   assert(Step->getType() == STy && "Step has wrong type");
2533 
2534   SmallVector<Constant *, 8> Indices;
2535 
2536   // Create a vector of consecutive numbers from zero to VF.
2537   VectorType *InitVecValVTy = ValVTy;
2538   Type *InitVecValSTy = STy;
2539   if (STy->isFloatingPointTy()) {
2540     InitVecValSTy =
2541         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2542     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2543   }
2544   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2545 
2546   // Add on StartIdx
2547   Value *StartIdxSplat = Builder.CreateVectorSplat(
2548       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2549   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2550 
2551   if (STy->isIntegerTy()) {
2552     Step = Builder.CreateVectorSplat(VLen, Step);
2553     assert(Step->getType() == Val->getType() && "Invalid step vec");
2554     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2555     // which can be found from the original scalar operations.
2556     Step = Builder.CreateMul(InitVec, Step);
2557     return Builder.CreateAdd(Val, Step, "induction");
2558   }
2559 
2560   // Floating point induction.
2561   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2562          "Binary Opcode should be specified for FP induction");
2563   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2564   Step = Builder.CreateVectorSplat(VLen, Step);
2565   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2566   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2567 }
2568 
2569 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2570                                            Instruction *EntryVal,
2571                                            const InductionDescriptor &ID,
2572                                            VPValue *Def, VPValue *CastDef,
2573                                            VPTransformState &State) {
2574   // We shouldn't have to build scalar steps if we aren't vectorizing.
2575   assert(VF.isVector() && "VF should be greater than one");
2576   // Get the value type and ensure it and the step have the same integer type.
2577   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2578   assert(ScalarIVTy == Step->getType() &&
2579          "Val and Step should have the same type");
2580 
2581   // We build scalar steps for both integer and floating-point induction
2582   // variables. Here, we determine the kind of arithmetic we will perform.
2583   Instruction::BinaryOps AddOp;
2584   Instruction::BinaryOps MulOp;
2585   if (ScalarIVTy->isIntegerTy()) {
2586     AddOp = Instruction::Add;
2587     MulOp = Instruction::Mul;
2588   } else {
2589     AddOp = ID.getInductionOpcode();
2590     MulOp = Instruction::FMul;
2591   }
2592 
2593   // Determine the number of scalars we need to generate for each unroll
2594   // iteration. If EntryVal is uniform, we only need to generate the first
2595   // lane. Otherwise, we generate all VF values.
2596   bool IsUniform =
2597       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2598   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2599   // Compute the scalar steps and save the results in State.
2600   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2601                                      ScalarIVTy->getScalarSizeInBits());
2602   Type *VecIVTy = nullptr;
2603   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2604   if (!IsUniform && VF.isScalable()) {
2605     VecIVTy = VectorType::get(ScalarIVTy, VF);
2606     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2607     SplatStep = Builder.CreateVectorSplat(VF, Step);
2608     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2609   }
2610 
2611   for (unsigned Part = 0; Part < UF; ++Part) {
2612     Value *StartIdx0 =
2613         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2614 
2615     if (!IsUniform && VF.isScalable()) {
2616       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2617       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2618       if (ScalarIVTy->isFloatingPointTy())
2619         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2620       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2621       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2622       State.set(Def, Add, Part);
2623       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2624                                             Part);
2625       // It's useful to record the lane values too for the known minimum number
2626       // of elements so we do those below. This improves the code quality when
2627       // trying to extract the first element, for example.
2628     }
2629 
2630     if (ScalarIVTy->isFloatingPointTy())
2631       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2632 
2633     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2634       Value *StartIdx = Builder.CreateBinOp(
2635           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2636       // The step returned by `createStepForVF` is a runtime-evaluated value
2637       // when VF is scalable. Otherwise, it should be folded into a Constant.
2638       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2639              "Expected StartIdx to be folded to a constant when VF is not "
2640              "scalable");
2641       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2642       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2643       State.set(Def, Add, VPIteration(Part, Lane));
2644       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2645                                             Part, Lane);
2646     }
2647   }
2648 }
2649 
2650 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2651                                                     const VPIteration &Instance,
2652                                                     VPTransformState &State) {
2653   Value *ScalarInst = State.get(Def, Instance);
2654   Value *VectorValue = State.get(Def, Instance.Part);
2655   VectorValue = Builder.CreateInsertElement(
2656       VectorValue, ScalarInst,
2657       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2658   State.set(Def, VectorValue, Instance.Part);
2659 }
2660 
2661 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2662   assert(Vec->getType()->isVectorTy() && "Invalid type");
2663   return Builder.CreateVectorReverse(Vec, "reverse");
2664 }
2665 
2666 // Return whether we allow using masked interleave-groups (for dealing with
2667 // strided loads/stores that reside in predicated blocks, or for dealing
2668 // with gaps).
2669 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2670   // If an override option has been passed in for interleaved accesses, use it.
2671   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2672     return EnableMaskedInterleavedMemAccesses;
2673 
2674   return TTI.enableMaskedInterleavedAccessVectorization();
2675 }
2676 
2677 // Try to vectorize the interleave group that \p Instr belongs to.
2678 //
2679 // E.g. Translate following interleaved load group (factor = 3):
2680 //   for (i = 0; i < N; i+=3) {
2681 //     R = Pic[i];             // Member of index 0
2682 //     G = Pic[i+1];           // Member of index 1
2683 //     B = Pic[i+2];           // Member of index 2
2684 //     ... // do something to R, G, B
2685 //   }
2686 // To:
2687 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2688 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2689 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2690 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2691 //
2692 // Or translate following interleaved store group (factor = 3):
2693 //   for (i = 0; i < N; i+=3) {
2694 //     ... do something to R, G, B
2695 //     Pic[i]   = R;           // Member of index 0
2696 //     Pic[i+1] = G;           // Member of index 1
2697 //     Pic[i+2] = B;           // Member of index 2
2698 //   }
2699 // To:
2700 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2701 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2702 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2703 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2704 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2705 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2706     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2707     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2708     VPValue *BlockInMask) {
2709   Instruction *Instr = Group->getInsertPos();
2710   const DataLayout &DL = Instr->getModule()->getDataLayout();
2711 
2712   // Prepare for the vector type of the interleaved load/store.
2713   Type *ScalarTy = getLoadStoreType(Instr);
2714   unsigned InterleaveFactor = Group->getFactor();
2715   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2716   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2717 
2718   // Prepare for the new pointers.
2719   SmallVector<Value *, 2> AddrParts;
2720   unsigned Index = Group->getIndex(Instr);
2721 
2722   // TODO: extend the masked interleaved-group support to reversed access.
2723   assert((!BlockInMask || !Group->isReverse()) &&
2724          "Reversed masked interleave-group not supported.");
2725 
2726   // If the group is reverse, adjust the index to refer to the last vector lane
2727   // instead of the first. We adjust the index from the first vector lane,
2728   // rather than directly getting the pointer for lane VF - 1, because the
2729   // pointer operand of the interleaved access is supposed to be uniform. For
2730   // uniform instructions, we're only required to generate a value for the
2731   // first vector lane in each unroll iteration.
2732   if (Group->isReverse())
2733     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2734 
2735   for (unsigned Part = 0; Part < UF; Part++) {
2736     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2737     setDebugLocFromInst(AddrPart);
2738 
2739     // Notice current instruction could be any index. Need to adjust the address
2740     // to the member of index 0.
2741     //
2742     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2743     //       b = A[i];       // Member of index 0
2744     // Current pointer is pointed to A[i+1], adjust it to A[i].
2745     //
2746     // E.g.  A[i+1] = a;     // Member of index 1
2747     //       A[i]   = b;     // Member of index 0
2748     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2749     // Current pointer is pointed to A[i+2], adjust it to A[i].
2750 
2751     bool InBounds = false;
2752     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2753       InBounds = gep->isInBounds();
2754     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2755     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2756 
2757     // Cast to the vector pointer type.
2758     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2759     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2760     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2761   }
2762 
2763   setDebugLocFromInst(Instr);
2764   Value *PoisonVec = PoisonValue::get(VecTy);
2765 
2766   Value *MaskForGaps = nullptr;
2767   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2768     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2769     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2770   }
2771 
2772   // Vectorize the interleaved load group.
2773   if (isa<LoadInst>(Instr)) {
2774     // For each unroll part, create a wide load for the group.
2775     SmallVector<Value *, 2> NewLoads;
2776     for (unsigned Part = 0; Part < UF; Part++) {
2777       Instruction *NewLoad;
2778       if (BlockInMask || MaskForGaps) {
2779         assert(useMaskedInterleavedAccesses(*TTI) &&
2780                "masked interleaved groups are not allowed.");
2781         Value *GroupMask = MaskForGaps;
2782         if (BlockInMask) {
2783           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2784           Value *ShuffledMask = Builder.CreateShuffleVector(
2785               BlockInMaskPart,
2786               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2787               "interleaved.mask");
2788           GroupMask = MaskForGaps
2789                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2790                                                 MaskForGaps)
2791                           : ShuffledMask;
2792         }
2793         NewLoad =
2794             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2795                                      GroupMask, PoisonVec, "wide.masked.vec");
2796       }
2797       else
2798         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2799                                             Group->getAlign(), "wide.vec");
2800       Group->addMetadata(NewLoad);
2801       NewLoads.push_back(NewLoad);
2802     }
2803 
2804     // For each member in the group, shuffle out the appropriate data from the
2805     // wide loads.
2806     unsigned J = 0;
2807     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2808       Instruction *Member = Group->getMember(I);
2809 
2810       // Skip the gaps in the group.
2811       if (!Member)
2812         continue;
2813 
2814       auto StrideMask =
2815           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2816       for (unsigned Part = 0; Part < UF; Part++) {
2817         Value *StridedVec = Builder.CreateShuffleVector(
2818             NewLoads[Part], StrideMask, "strided.vec");
2819 
2820         // If this member has different type, cast the result type.
2821         if (Member->getType() != ScalarTy) {
2822           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2823           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2824           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2825         }
2826 
2827         if (Group->isReverse())
2828           StridedVec = reverseVector(StridedVec);
2829 
2830         State.set(VPDefs[J], StridedVec, Part);
2831       }
2832       ++J;
2833     }
2834     return;
2835   }
2836 
2837   // The sub vector type for current instruction.
2838   auto *SubVT = VectorType::get(ScalarTy, VF);
2839 
2840   // Vectorize the interleaved store group.
2841   for (unsigned Part = 0; Part < UF; Part++) {
2842     // Collect the stored vector from each member.
2843     SmallVector<Value *, 4> StoredVecs;
2844     for (unsigned i = 0; i < InterleaveFactor; i++) {
2845       // Interleaved store group doesn't allow a gap, so each index has a member
2846       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2847 
2848       Value *StoredVec = State.get(StoredValues[i], Part);
2849 
2850       if (Group->isReverse())
2851         StoredVec = reverseVector(StoredVec);
2852 
2853       // If this member has different type, cast it to a unified type.
2854 
2855       if (StoredVec->getType() != SubVT)
2856         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2857 
2858       StoredVecs.push_back(StoredVec);
2859     }
2860 
2861     // Concatenate all vectors into a wide vector.
2862     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2863 
2864     // Interleave the elements in the wide vector.
2865     Value *IVec = Builder.CreateShuffleVector(
2866         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2867         "interleaved.vec");
2868 
2869     Instruction *NewStoreInstr;
2870     if (BlockInMask) {
2871       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2872       Value *ShuffledMask = Builder.CreateShuffleVector(
2873           BlockInMaskPart,
2874           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2875           "interleaved.mask");
2876       NewStoreInstr = Builder.CreateMaskedStore(
2877           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2878     }
2879     else
2880       NewStoreInstr =
2881           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2882 
2883     Group->addMetadata(NewStoreInstr);
2884   }
2885 }
2886 
2887 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2888     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2889     VPValue *StoredValue, VPValue *BlockInMask) {
2890   // Attempt to issue a wide load.
2891   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2892   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2893 
2894   assert((LI || SI) && "Invalid Load/Store instruction");
2895   assert((!SI || StoredValue) && "No stored value provided for widened store");
2896   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2897 
2898   LoopVectorizationCostModel::InstWidening Decision =
2899       Cost->getWideningDecision(Instr, VF);
2900   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2901           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2902           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2903          "CM decision is not to widen the memory instruction");
2904 
2905   Type *ScalarDataTy = getLoadStoreType(Instr);
2906 
2907   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2908   const Align Alignment = getLoadStoreAlignment(Instr);
2909 
2910   // Determine if the pointer operand of the access is either consecutive or
2911   // reverse consecutive.
2912   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2913   bool ConsecutiveStride =
2914       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2915   bool CreateGatherScatter =
2916       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2917 
2918   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2919   // gather/scatter. Otherwise Decision should have been to Scalarize.
2920   assert((ConsecutiveStride || CreateGatherScatter) &&
2921          "The instruction should be scalarized");
2922   (void)ConsecutiveStride;
2923 
2924   VectorParts BlockInMaskParts(UF);
2925   bool isMaskRequired = BlockInMask;
2926   if (isMaskRequired)
2927     for (unsigned Part = 0; Part < UF; ++Part)
2928       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2929 
2930   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2931     // Calculate the pointer for the specific unroll-part.
2932     GetElementPtrInst *PartPtr = nullptr;
2933 
2934     bool InBounds = false;
2935     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2936       InBounds = gep->isInBounds();
2937     if (Reverse) {
2938       // If the address is consecutive but reversed, then the
2939       // wide store needs to start at the last vector element.
2940       // RunTimeVF =  VScale * VF.getKnownMinValue()
2941       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2942       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2943       // NumElt = -Part * RunTimeVF
2944       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2945       // LastLane = 1 - RunTimeVF
2946       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2947       PartPtr =
2948           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2949       PartPtr->setIsInBounds(InBounds);
2950       PartPtr = cast<GetElementPtrInst>(
2951           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2952       PartPtr->setIsInBounds(InBounds);
2953       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2954         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2955     } else {
2956       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2957       PartPtr = cast<GetElementPtrInst>(
2958           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2959       PartPtr->setIsInBounds(InBounds);
2960     }
2961 
2962     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2963     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2964   };
2965 
2966   // Handle Stores:
2967   if (SI) {
2968     setDebugLocFromInst(SI);
2969 
2970     for (unsigned Part = 0; Part < UF; ++Part) {
2971       Instruction *NewSI = nullptr;
2972       Value *StoredVal = State.get(StoredValue, Part);
2973       if (CreateGatherScatter) {
2974         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2975         Value *VectorGep = State.get(Addr, Part);
2976         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2977                                             MaskPart);
2978       } else {
2979         if (Reverse) {
2980           // If we store to reverse consecutive memory locations, then we need
2981           // to reverse the order of elements in the stored value.
2982           StoredVal = reverseVector(StoredVal);
2983           // We don't want to update the value in the map as it might be used in
2984           // another expression. So don't call resetVectorValue(StoredVal).
2985         }
2986         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2987         if (isMaskRequired)
2988           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2989                                             BlockInMaskParts[Part]);
2990         else
2991           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2992       }
2993       addMetadata(NewSI, SI);
2994     }
2995     return;
2996   }
2997 
2998   // Handle loads.
2999   assert(LI && "Must have a load instruction");
3000   setDebugLocFromInst(LI);
3001   for (unsigned Part = 0; Part < UF; ++Part) {
3002     Value *NewLI;
3003     if (CreateGatherScatter) {
3004       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
3005       Value *VectorGep = State.get(Addr, Part);
3006       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
3007                                          nullptr, "wide.masked.gather");
3008       addMetadata(NewLI, LI);
3009     } else {
3010       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3011       if (isMaskRequired)
3012         NewLI = Builder.CreateMaskedLoad(
3013             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
3014             PoisonValue::get(DataTy), "wide.masked.load");
3015       else
3016         NewLI =
3017             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
3018 
3019       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3020       addMetadata(NewLI, LI);
3021       if (Reverse)
3022         NewLI = reverseVector(NewLI);
3023     }
3024 
3025     State.set(Def, NewLI, Part);
3026   }
3027 }
3028 
3029 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
3030                                                VPUser &User,
3031                                                const VPIteration &Instance,
3032                                                bool IfPredicateInstr,
3033                                                VPTransformState &State) {
3034   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3035 
3036   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3037   // the first lane and part.
3038   if (isa<NoAliasScopeDeclInst>(Instr))
3039     if (!Instance.isFirstIteration())
3040       return;
3041 
3042   setDebugLocFromInst(Instr);
3043 
3044   // Does this instruction return a value ?
3045   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3046 
3047   Instruction *Cloned = Instr->clone();
3048   if (!IsVoidRetTy)
3049     Cloned->setName(Instr->getName() + ".cloned");
3050 
3051   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3052                                Builder.GetInsertPoint());
3053   // Replace the operands of the cloned instructions with their scalar
3054   // equivalents in the new loop.
3055   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3056     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3057     auto InputInstance = Instance;
3058     if (!Operand || !OrigLoop->contains(Operand) ||
3059         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3060       InputInstance.Lane = VPLane::getFirstLane();
3061     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3062     Cloned->setOperand(op, NewOp);
3063   }
3064   addNewMetadata(Cloned, Instr);
3065 
3066   // Place the cloned scalar in the new loop.
3067   Builder.Insert(Cloned);
3068 
3069   State.set(Def, Cloned, Instance);
3070 
3071   // If we just cloned a new assumption, add it the assumption cache.
3072   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3073     AC->registerAssumption(II);
3074 
3075   // End if-block.
3076   if (IfPredicateInstr)
3077     PredicatedInstructions.push_back(Cloned);
3078 }
3079 
3080 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3081                                                       Value *End, Value *Step,
3082                                                       Instruction *DL) {
3083   BasicBlock *Header = L->getHeader();
3084   BasicBlock *Latch = L->getLoopLatch();
3085   // As we're just creating this loop, it's possible no latch exists
3086   // yet. If so, use the header as this will be a single block loop.
3087   if (!Latch)
3088     Latch = Header;
3089 
3090   IRBuilder<> B(&*Header->getFirstInsertionPt());
3091   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3092   setDebugLocFromInst(OldInst, &B);
3093   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3094 
3095   B.SetInsertPoint(Latch->getTerminator());
3096   setDebugLocFromInst(OldInst, &B);
3097 
3098   // Create i+1 and fill the PHINode.
3099   //
3100   // If the tail is not folded, we know that End - Start >= Step (either
3101   // statically or through the minimum iteration checks). We also know that both
3102   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3103   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3104   // overflows and we can mark the induction increment as NUW.
3105   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3106                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3107   Induction->addIncoming(Start, L->getLoopPreheader());
3108   Induction->addIncoming(Next, Latch);
3109   // Create the compare.
3110   Value *ICmp = B.CreateICmpEQ(Next, End);
3111   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3112 
3113   // Now we have two terminators. Remove the old one from the block.
3114   Latch->getTerminator()->eraseFromParent();
3115 
3116   return Induction;
3117 }
3118 
3119 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3120   if (TripCount)
3121     return TripCount;
3122 
3123   assert(L && "Create Trip Count for null loop.");
3124   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3125   // Find the loop boundaries.
3126   ScalarEvolution *SE = PSE.getSE();
3127   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3128   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3129          "Invalid loop count");
3130 
3131   Type *IdxTy = Legal->getWidestInductionType();
3132   assert(IdxTy && "No type for induction");
3133 
3134   // The exit count might have the type of i64 while the phi is i32. This can
3135   // happen if we have an induction variable that is sign extended before the
3136   // compare. The only way that we get a backedge taken count is that the
3137   // induction variable was signed and as such will not overflow. In such a case
3138   // truncation is legal.
3139   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3140       IdxTy->getPrimitiveSizeInBits())
3141     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3142   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3143 
3144   // Get the total trip count from the count by adding 1.
3145   const SCEV *ExitCount = SE->getAddExpr(
3146       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3147 
3148   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3149 
3150   // Expand the trip count and place the new instructions in the preheader.
3151   // Notice that the pre-header does not change, only the loop body.
3152   SCEVExpander Exp(*SE, DL, "induction");
3153 
3154   // Count holds the overall loop count (N).
3155   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3156                                 L->getLoopPreheader()->getTerminator());
3157 
3158   if (TripCount->getType()->isPointerTy())
3159     TripCount =
3160         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3161                                     L->getLoopPreheader()->getTerminator());
3162 
3163   return TripCount;
3164 }
3165 
3166 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3167   if (VectorTripCount)
3168     return VectorTripCount;
3169 
3170   Value *TC = getOrCreateTripCount(L);
3171   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3172 
3173   Type *Ty = TC->getType();
3174   // This is where we can make the step a runtime constant.
3175   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3176 
3177   // If the tail is to be folded by masking, round the number of iterations N
3178   // up to a multiple of Step instead of rounding down. This is done by first
3179   // adding Step-1 and then rounding down. Note that it's ok if this addition
3180   // overflows: the vector induction variable will eventually wrap to zero given
3181   // that it starts at zero and its Step is a power of two; the loop will then
3182   // exit, with the last early-exit vector comparison also producing all-true.
3183   if (Cost->foldTailByMasking()) {
3184     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3185            "VF*UF must be a power of 2 when folding tail by masking");
3186     assert(!VF.isScalable() &&
3187            "Tail folding not yet supported for scalable vectors");
3188     TC = Builder.CreateAdd(
3189         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3190   }
3191 
3192   // Now we need to generate the expression for the part of the loop that the
3193   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3194   // iterations are not required for correctness, or N - Step, otherwise. Step
3195   // is equal to the vectorization factor (number of SIMD elements) times the
3196   // unroll factor (number of SIMD instructions).
3197   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3198 
3199   // There are cases where we *must* run at least one iteration in the remainder
3200   // loop.  See the cost model for when this can happen.  If the step evenly
3201   // divides the trip count, we set the remainder to be equal to the step. If
3202   // the step does not evenly divide the trip count, no adjustment is necessary
3203   // since there will already be scalar iterations. Note that the minimum
3204   // iterations check ensures that N >= Step.
3205   if (Cost->requiresScalarEpilogue(VF)) {
3206     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3207     R = Builder.CreateSelect(IsZero, Step, R);
3208   }
3209 
3210   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3211 
3212   return VectorTripCount;
3213 }
3214 
3215 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3216                                                    const DataLayout &DL) {
3217   // Verify that V is a vector type with same number of elements as DstVTy.
3218   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3219   unsigned VF = DstFVTy->getNumElements();
3220   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3221   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3222   Type *SrcElemTy = SrcVecTy->getElementType();
3223   Type *DstElemTy = DstFVTy->getElementType();
3224   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3225          "Vector elements must have same size");
3226 
3227   // Do a direct cast if element types are castable.
3228   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3229     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3230   }
3231   // V cannot be directly casted to desired vector type.
3232   // May happen when V is a floating point vector but DstVTy is a vector of
3233   // pointers or vice-versa. Handle this using a two-step bitcast using an
3234   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3235   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3236          "Only one type should be a pointer type");
3237   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3238          "Only one type should be a floating point type");
3239   Type *IntTy =
3240       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3241   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3242   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3243   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3244 }
3245 
3246 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3247                                                          BasicBlock *Bypass) {
3248   Value *Count = getOrCreateTripCount(L);
3249   // Reuse existing vector loop preheader for TC checks.
3250   // Note that new preheader block is generated for vector loop.
3251   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3252   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3253 
3254   // Generate code to check if the loop's trip count is less than VF * UF, or
3255   // equal to it in case a scalar epilogue is required; this implies that the
3256   // vector trip count is zero. This check also covers the case where adding one
3257   // to the backedge-taken count overflowed leading to an incorrect trip count
3258   // of zero. In this case we will also jump to the scalar loop.
3259   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3260                                             : ICmpInst::ICMP_ULT;
3261 
3262   // If tail is to be folded, vector loop takes care of all iterations.
3263   Value *CheckMinIters = Builder.getFalse();
3264   if (!Cost->foldTailByMasking()) {
3265     Value *Step =
3266         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3267     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3268   }
3269   // Create new preheader for vector loop.
3270   LoopVectorPreHeader =
3271       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3272                  "vector.ph");
3273 
3274   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3275                                DT->getNode(Bypass)->getIDom()) &&
3276          "TC check is expected to dominate Bypass");
3277 
3278   // Update dominator for Bypass & LoopExit (if needed).
3279   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3280   if (!Cost->requiresScalarEpilogue(VF))
3281     // If there is an epilogue which must run, there's no edge from the
3282     // middle block to exit blocks  and thus no need to update the immediate
3283     // dominator of the exit blocks.
3284     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3285 
3286   ReplaceInstWithInst(
3287       TCCheckBlock->getTerminator(),
3288       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3289   LoopBypassBlocks.push_back(TCCheckBlock);
3290 }
3291 
3292 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3293 
3294   BasicBlock *const SCEVCheckBlock =
3295       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3296   if (!SCEVCheckBlock)
3297     return nullptr;
3298 
3299   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3300            (OptForSizeBasedOnProfile &&
3301             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3302          "Cannot SCEV check stride or overflow when optimizing for size");
3303 
3304 
3305   // Update dominator only if this is first RT check.
3306   if (LoopBypassBlocks.empty()) {
3307     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3308     if (!Cost->requiresScalarEpilogue(VF))
3309       // If there is an epilogue which must run, there's no edge from the
3310       // middle block to exit blocks  and thus no need to update the immediate
3311       // dominator of the exit blocks.
3312       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3313   }
3314 
3315   LoopBypassBlocks.push_back(SCEVCheckBlock);
3316   AddedSafetyChecks = true;
3317   return SCEVCheckBlock;
3318 }
3319 
3320 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3321                                                       BasicBlock *Bypass) {
3322   // VPlan-native path does not do any analysis for runtime checks currently.
3323   if (EnableVPlanNativePath)
3324     return nullptr;
3325 
3326   BasicBlock *const MemCheckBlock =
3327       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3328 
3329   // Check if we generated code that checks in runtime if arrays overlap. We put
3330   // the checks into a separate block to make the more common case of few
3331   // elements faster.
3332   if (!MemCheckBlock)
3333     return nullptr;
3334 
3335   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3336     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3337            "Cannot emit memory checks when optimizing for size, unless forced "
3338            "to vectorize.");
3339     ORE->emit([&]() {
3340       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3341                                         L->getStartLoc(), L->getHeader())
3342              << "Code-size may be reduced by not forcing "
3343                 "vectorization, or by source-code modifications "
3344                 "eliminating the need for runtime checks "
3345                 "(e.g., adding 'restrict').";
3346     });
3347   }
3348 
3349   LoopBypassBlocks.push_back(MemCheckBlock);
3350 
3351   AddedSafetyChecks = true;
3352 
3353   // We currently don't use LoopVersioning for the actual loop cloning but we
3354   // still use it to add the noalias metadata.
3355   LVer = std::make_unique<LoopVersioning>(
3356       *Legal->getLAI(),
3357       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3358       DT, PSE.getSE());
3359   LVer->prepareNoAliasMetadata();
3360   return MemCheckBlock;
3361 }
3362 
3363 Value *InnerLoopVectorizer::emitTransformedIndex(
3364     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3365     const InductionDescriptor &ID) const {
3366 
3367   SCEVExpander Exp(*SE, DL, "induction");
3368   auto Step = ID.getStep();
3369   auto StartValue = ID.getStartValue();
3370   assert(Index->getType()->getScalarType() == Step->getType() &&
3371          "Index scalar type does not match StepValue type");
3372 
3373   // Note: the IR at this point is broken. We cannot use SE to create any new
3374   // SCEV and then expand it, hoping that SCEV's simplification will give us
3375   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3376   // lead to various SCEV crashes. So all we can do is to use builder and rely
3377   // on InstCombine for future simplifications. Here we handle some trivial
3378   // cases only.
3379   auto CreateAdd = [&B](Value *X, Value *Y) {
3380     assert(X->getType() == Y->getType() && "Types don't match!");
3381     if (auto *CX = dyn_cast<ConstantInt>(X))
3382       if (CX->isZero())
3383         return Y;
3384     if (auto *CY = dyn_cast<ConstantInt>(Y))
3385       if (CY->isZero())
3386         return X;
3387     return B.CreateAdd(X, Y);
3388   };
3389 
3390   // We allow X to be a vector type, in which case Y will potentially be
3391   // splatted into a vector with the same element count.
3392   auto CreateMul = [&B](Value *X, Value *Y) {
3393     assert(X->getType()->getScalarType() == Y->getType() &&
3394            "Types don't match!");
3395     if (auto *CX = dyn_cast<ConstantInt>(X))
3396       if (CX->isOne())
3397         return Y;
3398     if (auto *CY = dyn_cast<ConstantInt>(Y))
3399       if (CY->isOne())
3400         return X;
3401     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3402     if (XVTy && !isa<VectorType>(Y->getType()))
3403       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3404     return B.CreateMul(X, Y);
3405   };
3406 
3407   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3408   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3409   // the DomTree is not kept up-to-date for additional blocks generated in the
3410   // vector loop. By using the header as insertion point, we guarantee that the
3411   // expanded instructions dominate all their uses.
3412   auto GetInsertPoint = [this, &B]() {
3413     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3414     if (InsertBB != LoopVectorBody &&
3415         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3416       return LoopVectorBody->getTerminator();
3417     return &*B.GetInsertPoint();
3418   };
3419 
3420   switch (ID.getKind()) {
3421   case InductionDescriptor::IK_IntInduction: {
3422     assert(!isa<VectorType>(Index->getType()) &&
3423            "Vector indices not supported for integer inductions yet");
3424     assert(Index->getType() == StartValue->getType() &&
3425            "Index type does not match StartValue type");
3426     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3427       return B.CreateSub(StartValue, Index);
3428     auto *Offset = CreateMul(
3429         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3430     return CreateAdd(StartValue, Offset);
3431   }
3432   case InductionDescriptor::IK_PtrInduction: {
3433     assert(isa<SCEVConstant>(Step) &&
3434            "Expected constant step for pointer induction");
3435     return B.CreateGEP(
3436         StartValue->getType()->getPointerElementType(), StartValue,
3437         CreateMul(Index,
3438                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3439                                     GetInsertPoint())));
3440   }
3441   case InductionDescriptor::IK_FpInduction: {
3442     assert(!isa<VectorType>(Index->getType()) &&
3443            "Vector indices not supported for FP inductions yet");
3444     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3445     auto InductionBinOp = ID.getInductionBinOp();
3446     assert(InductionBinOp &&
3447            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3448             InductionBinOp->getOpcode() == Instruction::FSub) &&
3449            "Original bin op should be defined for FP induction");
3450 
3451     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3452     Value *MulExp = B.CreateFMul(StepValue, Index);
3453     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3454                          "induction");
3455   }
3456   case InductionDescriptor::IK_NoInduction:
3457     return nullptr;
3458   }
3459   llvm_unreachable("invalid enum");
3460 }
3461 
3462 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3463   LoopScalarBody = OrigLoop->getHeader();
3464   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3465   assert(LoopVectorPreHeader && "Invalid loop structure");
3466   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3467   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3468          "multiple exit loop without required epilogue?");
3469 
3470   LoopMiddleBlock =
3471       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3472                  LI, nullptr, Twine(Prefix) + "middle.block");
3473   LoopScalarPreHeader =
3474       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3475                  nullptr, Twine(Prefix) + "scalar.ph");
3476 
3477   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3478 
3479   // Set up the middle block terminator.  Two cases:
3480   // 1) If we know that we must execute the scalar epilogue, emit an
3481   //    unconditional branch.
3482   // 2) Otherwise, we must have a single unique exit block (due to how we
3483   //    implement the multiple exit case).  In this case, set up a conditonal
3484   //    branch from the middle block to the loop scalar preheader, and the
3485   //    exit block.  completeLoopSkeleton will update the condition to use an
3486   //    iteration check, if required to decide whether to execute the remainder.
3487   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3488     BranchInst::Create(LoopScalarPreHeader) :
3489     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3490                        Builder.getTrue());
3491   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3492   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3493 
3494   // We intentionally don't let SplitBlock to update LoopInfo since
3495   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3496   // LoopVectorBody is explicitly added to the correct place few lines later.
3497   LoopVectorBody =
3498       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3499                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3500 
3501   // Update dominator for loop exit.
3502   if (!Cost->requiresScalarEpilogue(VF))
3503     // If there is an epilogue which must run, there's no edge from the
3504     // middle block to exit blocks  and thus no need to update the immediate
3505     // dominator of the exit blocks.
3506     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3507 
3508   // Create and register the new vector loop.
3509   Loop *Lp = LI->AllocateLoop();
3510   Loop *ParentLoop = OrigLoop->getParentLoop();
3511 
3512   // Insert the new loop into the loop nest and register the new basic blocks
3513   // before calling any utilities such as SCEV that require valid LoopInfo.
3514   if (ParentLoop) {
3515     ParentLoop->addChildLoop(Lp);
3516   } else {
3517     LI->addTopLevelLoop(Lp);
3518   }
3519   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3520   return Lp;
3521 }
3522 
3523 void InnerLoopVectorizer::createInductionResumeValues(
3524     Loop *L, Value *VectorTripCount,
3525     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3526   assert(VectorTripCount && L && "Expected valid arguments");
3527   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3528           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3529          "Inconsistent information about additional bypass.");
3530   // We are going to resume the execution of the scalar loop.
3531   // Go over all of the induction variables that we found and fix the
3532   // PHIs that are left in the scalar version of the loop.
3533   // The starting values of PHI nodes depend on the counter of the last
3534   // iteration in the vectorized loop.
3535   // If we come from a bypass edge then we need to start from the original
3536   // start value.
3537   for (auto &InductionEntry : Legal->getInductionVars()) {
3538     PHINode *OrigPhi = InductionEntry.first;
3539     InductionDescriptor II = InductionEntry.second;
3540 
3541     // Create phi nodes to merge from the  backedge-taken check block.
3542     PHINode *BCResumeVal =
3543         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3544                         LoopScalarPreHeader->getTerminator());
3545     // Copy original phi DL over to the new one.
3546     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3547     Value *&EndValue = IVEndValues[OrigPhi];
3548     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3549     if (OrigPhi == OldInduction) {
3550       // We know what the end value is.
3551       EndValue = VectorTripCount;
3552     } else {
3553       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3554 
3555       // Fast-math-flags propagate from the original induction instruction.
3556       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3557         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3558 
3559       Type *StepType = II.getStep()->getType();
3560       Instruction::CastOps CastOp =
3561           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3562       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3563       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3564       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3565       EndValue->setName("ind.end");
3566 
3567       // Compute the end value for the additional bypass (if applicable).
3568       if (AdditionalBypass.first) {
3569         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3570         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3571                                          StepType, true);
3572         CRD =
3573             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3574         EndValueFromAdditionalBypass =
3575             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3576         EndValueFromAdditionalBypass->setName("ind.end");
3577       }
3578     }
3579     // The new PHI merges the original incoming value, in case of a bypass,
3580     // or the value at the end of the vectorized loop.
3581     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3582 
3583     // Fix the scalar body counter (PHI node).
3584     // The old induction's phi node in the scalar body needs the truncated
3585     // value.
3586     for (BasicBlock *BB : LoopBypassBlocks)
3587       BCResumeVal->addIncoming(II.getStartValue(), BB);
3588 
3589     if (AdditionalBypass.first)
3590       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3591                                             EndValueFromAdditionalBypass);
3592 
3593     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3594   }
3595 }
3596 
3597 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3598                                                       MDNode *OrigLoopID) {
3599   assert(L && "Expected valid loop.");
3600 
3601   // The trip counts should be cached by now.
3602   Value *Count = getOrCreateTripCount(L);
3603   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3604 
3605   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3606 
3607   // Add a check in the middle block to see if we have completed
3608   // all of the iterations in the first vector loop.  Three cases:
3609   // 1) If we require a scalar epilogue, there is no conditional branch as
3610   //    we unconditionally branch to the scalar preheader.  Do nothing.
3611   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3612   //    Thus if tail is to be folded, we know we don't need to run the
3613   //    remainder and we can use the previous value for the condition (true).
3614   // 3) Otherwise, construct a runtime check.
3615   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3616     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3617                                         Count, VectorTripCount, "cmp.n",
3618                                         LoopMiddleBlock->getTerminator());
3619 
3620     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3621     // of the corresponding compare because they may have ended up with
3622     // different line numbers and we want to avoid awkward line stepping while
3623     // debugging. Eg. if the compare has got a line number inside the loop.
3624     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3625     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3626   }
3627 
3628   // Get ready to start creating new instructions into the vectorized body.
3629   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3630          "Inconsistent vector loop preheader");
3631   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3632 
3633   Optional<MDNode *> VectorizedLoopID =
3634       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3635                                       LLVMLoopVectorizeFollowupVectorized});
3636   if (VectorizedLoopID.hasValue()) {
3637     L->setLoopID(VectorizedLoopID.getValue());
3638 
3639     // Do not setAlreadyVectorized if loop attributes have been defined
3640     // explicitly.
3641     return LoopVectorPreHeader;
3642   }
3643 
3644   // Keep all loop hints from the original loop on the vector loop (we'll
3645   // replace the vectorizer-specific hints below).
3646   if (MDNode *LID = OrigLoop->getLoopID())
3647     L->setLoopID(LID);
3648 
3649   LoopVectorizeHints Hints(L, true, *ORE);
3650   Hints.setAlreadyVectorized();
3651 
3652 #ifdef EXPENSIVE_CHECKS
3653   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3654   LI->verify(*DT);
3655 #endif
3656 
3657   return LoopVectorPreHeader;
3658 }
3659 
3660 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3661   /*
3662    In this function we generate a new loop. The new loop will contain
3663    the vectorized instructions while the old loop will continue to run the
3664    scalar remainder.
3665 
3666        [ ] <-- loop iteration number check.
3667     /   |
3668    /    v
3669   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3670   |  /  |
3671   | /   v
3672   ||   [ ]     <-- vector pre header.
3673   |/    |
3674   |     v
3675   |    [  ] \
3676   |    [  ]_|   <-- vector loop.
3677   |     |
3678   |     v
3679   \   -[ ]   <--- middle-block.
3680    \/   |
3681    /\   v
3682    | ->[ ]     <--- new preheader.
3683    |    |
3684  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3685    |   [ ] \
3686    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3687     \   |
3688      \  v
3689       >[ ]     <-- exit block(s).
3690    ...
3691    */
3692 
3693   // Get the metadata of the original loop before it gets modified.
3694   MDNode *OrigLoopID = OrigLoop->getLoopID();
3695 
3696   // Workaround!  Compute the trip count of the original loop and cache it
3697   // before we start modifying the CFG.  This code has a systemic problem
3698   // wherein it tries to run analysis over partially constructed IR; this is
3699   // wrong, and not simply for SCEV.  The trip count of the original loop
3700   // simply happens to be prone to hitting this in practice.  In theory, we
3701   // can hit the same issue for any SCEV, or ValueTracking query done during
3702   // mutation.  See PR49900.
3703   getOrCreateTripCount(OrigLoop);
3704 
3705   // Create an empty vector loop, and prepare basic blocks for the runtime
3706   // checks.
3707   Loop *Lp = createVectorLoopSkeleton("");
3708 
3709   // Now, compare the new count to zero. If it is zero skip the vector loop and
3710   // jump to the scalar loop. This check also covers the case where the
3711   // backedge-taken count is uint##_max: adding one to it will overflow leading
3712   // to an incorrect trip count of zero. In this (rare) case we will also jump
3713   // to the scalar loop.
3714   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3715 
3716   // Generate the code to check any assumptions that we've made for SCEV
3717   // expressions.
3718   emitSCEVChecks(Lp, LoopScalarPreHeader);
3719 
3720   // Generate the code that checks in runtime if arrays overlap. We put the
3721   // checks into a separate block to make the more common case of few elements
3722   // faster.
3723   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3724 
3725   // Some loops have a single integer induction variable, while other loops
3726   // don't. One example is c++ iterators that often have multiple pointer
3727   // induction variables. In the code below we also support a case where we
3728   // don't have a single induction variable.
3729   //
3730   // We try to obtain an induction variable from the original loop as hard
3731   // as possible. However if we don't find one that:
3732   //   - is an integer
3733   //   - counts from zero, stepping by one
3734   //   - is the size of the widest induction variable type
3735   // then we create a new one.
3736   OldInduction = Legal->getPrimaryInduction();
3737   Type *IdxTy = Legal->getWidestInductionType();
3738   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3739   // The loop step is equal to the vectorization factor (num of SIMD elements)
3740   // times the unroll factor (num of SIMD instructions).
3741   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3742   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3743   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3744   Induction =
3745       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3746                               getDebugLocFromInstOrOperands(OldInduction));
3747 
3748   // Emit phis for the new starting index of the scalar loop.
3749   createInductionResumeValues(Lp, CountRoundDown);
3750 
3751   return completeLoopSkeleton(Lp, OrigLoopID);
3752 }
3753 
3754 // Fix up external users of the induction variable. At this point, we are
3755 // in LCSSA form, with all external PHIs that use the IV having one input value,
3756 // coming from the remainder loop. We need those PHIs to also have a correct
3757 // value for the IV when arriving directly from the middle block.
3758 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3759                                        const InductionDescriptor &II,
3760                                        Value *CountRoundDown, Value *EndValue,
3761                                        BasicBlock *MiddleBlock) {
3762   // There are two kinds of external IV usages - those that use the value
3763   // computed in the last iteration (the PHI) and those that use the penultimate
3764   // value (the value that feeds into the phi from the loop latch).
3765   // We allow both, but they, obviously, have different values.
3766 
3767   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3768 
3769   DenseMap<Value *, Value *> MissingVals;
3770 
3771   // An external user of the last iteration's value should see the value that
3772   // the remainder loop uses to initialize its own IV.
3773   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3774   for (User *U : PostInc->users()) {
3775     Instruction *UI = cast<Instruction>(U);
3776     if (!OrigLoop->contains(UI)) {
3777       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3778       MissingVals[UI] = EndValue;
3779     }
3780   }
3781 
3782   // An external user of the penultimate value need to see EndValue - Step.
3783   // The simplest way to get this is to recompute it from the constituent SCEVs,
3784   // that is Start + (Step * (CRD - 1)).
3785   for (User *U : OrigPhi->users()) {
3786     auto *UI = cast<Instruction>(U);
3787     if (!OrigLoop->contains(UI)) {
3788       const DataLayout &DL =
3789           OrigLoop->getHeader()->getModule()->getDataLayout();
3790       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3791 
3792       IRBuilder<> B(MiddleBlock->getTerminator());
3793 
3794       // Fast-math-flags propagate from the original induction instruction.
3795       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3796         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3797 
3798       Value *CountMinusOne = B.CreateSub(
3799           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3800       Value *CMO =
3801           !II.getStep()->getType()->isIntegerTy()
3802               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3803                              II.getStep()->getType())
3804               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3805       CMO->setName("cast.cmo");
3806       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3807       Escape->setName("ind.escape");
3808       MissingVals[UI] = Escape;
3809     }
3810   }
3811 
3812   for (auto &I : MissingVals) {
3813     PHINode *PHI = cast<PHINode>(I.first);
3814     // One corner case we have to handle is two IVs "chasing" each-other,
3815     // that is %IV2 = phi [...], [ %IV1, %latch ]
3816     // In this case, if IV1 has an external use, we need to avoid adding both
3817     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3818     // don't already have an incoming value for the middle block.
3819     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3820       PHI->addIncoming(I.second, MiddleBlock);
3821   }
3822 }
3823 
3824 namespace {
3825 
3826 struct CSEDenseMapInfo {
3827   static bool canHandle(const Instruction *I) {
3828     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3829            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3830   }
3831 
3832   static inline Instruction *getEmptyKey() {
3833     return DenseMapInfo<Instruction *>::getEmptyKey();
3834   }
3835 
3836   static inline Instruction *getTombstoneKey() {
3837     return DenseMapInfo<Instruction *>::getTombstoneKey();
3838   }
3839 
3840   static unsigned getHashValue(const Instruction *I) {
3841     assert(canHandle(I) && "Unknown instruction!");
3842     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3843                                                            I->value_op_end()));
3844   }
3845 
3846   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3847     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3848         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3849       return LHS == RHS;
3850     return LHS->isIdenticalTo(RHS);
3851   }
3852 };
3853 
3854 } // end anonymous namespace
3855 
3856 ///Perform cse of induction variable instructions.
3857 static void cse(BasicBlock *BB) {
3858   // Perform simple cse.
3859   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3860   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3861     Instruction *In = &*I++;
3862 
3863     if (!CSEDenseMapInfo::canHandle(In))
3864       continue;
3865 
3866     // Check if we can replace this instruction with any of the
3867     // visited instructions.
3868     if (Instruction *V = CSEMap.lookup(In)) {
3869       In->replaceAllUsesWith(V);
3870       In->eraseFromParent();
3871       continue;
3872     }
3873 
3874     CSEMap[In] = In;
3875   }
3876 }
3877 
3878 InstructionCost
3879 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3880                                               bool &NeedToScalarize) const {
3881   Function *F = CI->getCalledFunction();
3882   Type *ScalarRetTy = CI->getType();
3883   SmallVector<Type *, 4> Tys, ScalarTys;
3884   for (auto &ArgOp : CI->arg_operands())
3885     ScalarTys.push_back(ArgOp->getType());
3886 
3887   // Estimate cost of scalarized vector call. The source operands are assumed
3888   // to be vectors, so we need to extract individual elements from there,
3889   // execute VF scalar calls, and then gather the result into the vector return
3890   // value.
3891   InstructionCost ScalarCallCost =
3892       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3893   if (VF.isScalar())
3894     return ScalarCallCost;
3895 
3896   // Compute corresponding vector type for return value and arguments.
3897   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3898   for (Type *ScalarTy : ScalarTys)
3899     Tys.push_back(ToVectorTy(ScalarTy, VF));
3900 
3901   // Compute costs of unpacking argument values for the scalar calls and
3902   // packing the return values to a vector.
3903   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3904 
3905   InstructionCost Cost =
3906       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3907 
3908   // If we can't emit a vector call for this function, then the currently found
3909   // cost is the cost we need to return.
3910   NeedToScalarize = true;
3911   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3912   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3913 
3914   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3915     return Cost;
3916 
3917   // If the corresponding vector cost is cheaper, return its cost.
3918   InstructionCost VectorCallCost =
3919       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3920   if (VectorCallCost < Cost) {
3921     NeedToScalarize = false;
3922     Cost = VectorCallCost;
3923   }
3924   return Cost;
3925 }
3926 
3927 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3928   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3929     return Elt;
3930   return VectorType::get(Elt, VF);
3931 }
3932 
3933 InstructionCost
3934 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3935                                                    ElementCount VF) const {
3936   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3937   assert(ID && "Expected intrinsic call!");
3938   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3939   FastMathFlags FMF;
3940   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3941     FMF = FPMO->getFastMathFlags();
3942 
3943   SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3944   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3945   SmallVector<Type *> ParamTys;
3946   std::transform(FTy->param_begin(), FTy->param_end(),
3947                  std::back_inserter(ParamTys),
3948                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3949 
3950   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3951                                     dyn_cast<IntrinsicInst>(CI));
3952   return TTI.getIntrinsicInstrCost(CostAttrs,
3953                                    TargetTransformInfo::TCK_RecipThroughput);
3954 }
3955 
3956 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3957   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3958   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3959   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3960 }
3961 
3962 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3963   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3964   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3965   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3966 }
3967 
3968 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3969   // For every instruction `I` in MinBWs, truncate the operands, create a
3970   // truncated version of `I` and reextend its result. InstCombine runs
3971   // later and will remove any ext/trunc pairs.
3972   SmallPtrSet<Value *, 4> Erased;
3973   for (const auto &KV : Cost->getMinimalBitwidths()) {
3974     // If the value wasn't vectorized, we must maintain the original scalar
3975     // type. The absence of the value from State indicates that it
3976     // wasn't vectorized.
3977     VPValue *Def = State.Plan->getVPValue(KV.first);
3978     if (!State.hasAnyVectorValue(Def))
3979       continue;
3980     for (unsigned Part = 0; Part < UF; ++Part) {
3981       Value *I = State.get(Def, Part);
3982       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3983         continue;
3984       Type *OriginalTy = I->getType();
3985       Type *ScalarTruncatedTy =
3986           IntegerType::get(OriginalTy->getContext(), KV.second);
3987       auto *TruncatedTy = VectorType::get(
3988           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3989       if (TruncatedTy == OriginalTy)
3990         continue;
3991 
3992       IRBuilder<> B(cast<Instruction>(I));
3993       auto ShrinkOperand = [&](Value *V) -> Value * {
3994         if (auto *ZI = dyn_cast<ZExtInst>(V))
3995           if (ZI->getSrcTy() == TruncatedTy)
3996             return ZI->getOperand(0);
3997         return B.CreateZExtOrTrunc(V, TruncatedTy);
3998       };
3999 
4000       // The actual instruction modification depends on the instruction type,
4001       // unfortunately.
4002       Value *NewI = nullptr;
4003       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4004         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
4005                              ShrinkOperand(BO->getOperand(1)));
4006 
4007         // Any wrapping introduced by shrinking this operation shouldn't be
4008         // considered undefined behavior. So, we can't unconditionally copy
4009         // arithmetic wrapping flags to NewI.
4010         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
4011       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
4012         NewI =
4013             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
4014                          ShrinkOperand(CI->getOperand(1)));
4015       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
4016         NewI = B.CreateSelect(SI->getCondition(),
4017                               ShrinkOperand(SI->getTrueValue()),
4018                               ShrinkOperand(SI->getFalseValue()));
4019       } else if (auto *CI = dyn_cast<CastInst>(I)) {
4020         switch (CI->getOpcode()) {
4021         default:
4022           llvm_unreachable("Unhandled cast!");
4023         case Instruction::Trunc:
4024           NewI = ShrinkOperand(CI->getOperand(0));
4025           break;
4026         case Instruction::SExt:
4027           NewI = B.CreateSExtOrTrunc(
4028               CI->getOperand(0),
4029               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4030           break;
4031         case Instruction::ZExt:
4032           NewI = B.CreateZExtOrTrunc(
4033               CI->getOperand(0),
4034               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4035           break;
4036         }
4037       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
4038         auto Elements0 =
4039             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
4040         auto *O0 = B.CreateZExtOrTrunc(
4041             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
4042         auto Elements1 =
4043             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
4044         auto *O1 = B.CreateZExtOrTrunc(
4045             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
4046 
4047         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4048       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4049         // Don't do anything with the operands, just extend the result.
4050         continue;
4051       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4052         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
4053                             ->getNumElements();
4054         auto *O0 = B.CreateZExtOrTrunc(
4055             IE->getOperand(0),
4056             FixedVectorType::get(ScalarTruncatedTy, Elements));
4057         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4058         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4059       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4060         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
4061                             ->getNumElements();
4062         auto *O0 = B.CreateZExtOrTrunc(
4063             EE->getOperand(0),
4064             FixedVectorType::get(ScalarTruncatedTy, Elements));
4065         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4066       } else {
4067         // If we don't know what to do, be conservative and don't do anything.
4068         continue;
4069       }
4070 
4071       // Lastly, extend the result.
4072       NewI->takeName(cast<Instruction>(I));
4073       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4074       I->replaceAllUsesWith(Res);
4075       cast<Instruction>(I)->eraseFromParent();
4076       Erased.insert(I);
4077       State.reset(Def, Res, Part);
4078     }
4079   }
4080 
4081   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4082   for (const auto &KV : Cost->getMinimalBitwidths()) {
4083     // If the value wasn't vectorized, we must maintain the original scalar
4084     // type. The absence of the value from State indicates that it
4085     // wasn't vectorized.
4086     VPValue *Def = State.Plan->getVPValue(KV.first);
4087     if (!State.hasAnyVectorValue(Def))
4088       continue;
4089     for (unsigned Part = 0; Part < UF; ++Part) {
4090       Value *I = State.get(Def, Part);
4091       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4092       if (Inst && Inst->use_empty()) {
4093         Value *NewI = Inst->getOperand(0);
4094         Inst->eraseFromParent();
4095         State.reset(Def, NewI, Part);
4096       }
4097     }
4098   }
4099 }
4100 
4101 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4102   // Insert truncates and extends for any truncated instructions as hints to
4103   // InstCombine.
4104   if (VF.isVector())
4105     truncateToMinimalBitwidths(State);
4106 
4107   // Fix widened non-induction PHIs by setting up the PHI operands.
4108   if (OrigPHIsToFix.size()) {
4109     assert(EnableVPlanNativePath &&
4110            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4111     fixNonInductionPHIs(State);
4112   }
4113 
4114   // At this point every instruction in the original loop is widened to a
4115   // vector form. Now we need to fix the recurrences in the loop. These PHI
4116   // nodes are currently empty because we did not want to introduce cycles.
4117   // This is the second stage of vectorizing recurrences.
4118   fixCrossIterationPHIs(State);
4119 
4120   // Forget the original basic block.
4121   PSE.getSE()->forgetLoop(OrigLoop);
4122 
4123   // If we inserted an edge from the middle block to the unique exit block,
4124   // update uses outside the loop (phis) to account for the newly inserted
4125   // edge.
4126   if (!Cost->requiresScalarEpilogue(VF)) {
4127     // Fix-up external users of the induction variables.
4128     for (auto &Entry : Legal->getInductionVars())
4129       fixupIVUsers(Entry.first, Entry.second,
4130                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4131                    IVEndValues[Entry.first], LoopMiddleBlock);
4132 
4133     fixLCSSAPHIs(State);
4134   }
4135 
4136   for (Instruction *PI : PredicatedInstructions)
4137     sinkScalarOperands(&*PI);
4138 
4139   // Remove redundant induction instructions.
4140   cse(LoopVectorBody);
4141 
4142   // Set/update profile weights for the vector and remainder loops as original
4143   // loop iterations are now distributed among them. Note that original loop
4144   // represented by LoopScalarBody becomes remainder loop after vectorization.
4145   //
4146   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4147   // end up getting slightly roughened result but that should be OK since
4148   // profile is not inherently precise anyway. Note also possible bypass of
4149   // vector code caused by legality checks is ignored, assigning all the weight
4150   // to the vector loop, optimistically.
4151   //
4152   // For scalable vectorization we can't know at compile time how many iterations
4153   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4154   // vscale of '1'.
4155   setProfileInfoAfterUnrolling(
4156       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4157       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4158 }
4159 
4160 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4161   // In order to support recurrences we need to be able to vectorize Phi nodes.
4162   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4163   // stage #2: We now need to fix the recurrences by adding incoming edges to
4164   // the currently empty PHI nodes. At this point every instruction in the
4165   // original loop is widened to a vector form so we can use them to construct
4166   // the incoming edges.
4167   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4168   for (VPRecipeBase &R : Header->phis()) {
4169     auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R);
4170     if (!PhiR)
4171       continue;
4172     auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4173     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(PhiR)) {
4174       fixReduction(ReductionPhi, State);
4175     } else if (Legal->isFirstOrderRecurrence(OrigPhi))
4176       fixFirstOrderRecurrence(PhiR, State);
4177   }
4178 }
4179 
4180 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4181                                                   VPTransformState &State) {
4182   // This is the second phase of vectorizing first-order recurrences. An
4183   // overview of the transformation is described below. Suppose we have the
4184   // following loop.
4185   //
4186   //   for (int i = 0; i < n; ++i)
4187   //     b[i] = a[i] - a[i - 1];
4188   //
4189   // There is a first-order recurrence on "a". For this loop, the shorthand
4190   // scalar IR looks like:
4191   //
4192   //   scalar.ph:
4193   //     s_init = a[-1]
4194   //     br scalar.body
4195   //
4196   //   scalar.body:
4197   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4198   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4199   //     s2 = a[i]
4200   //     b[i] = s2 - s1
4201   //     br cond, scalar.body, ...
4202   //
4203   // In this example, s1 is a recurrence because it's value depends on the
4204   // previous iteration. In the first phase of vectorization, we created a
4205   // temporary value for s1. We now complete the vectorization and produce the
4206   // shorthand vector IR shown below (for VF = 4, UF = 1).
4207   //
4208   //   vector.ph:
4209   //     v_init = vector(..., ..., ..., a[-1])
4210   //     br vector.body
4211   //
4212   //   vector.body
4213   //     i = phi [0, vector.ph], [i+4, vector.body]
4214   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4215   //     v2 = a[i, i+1, i+2, i+3];
4216   //     v3 = vector(v1(3), v2(0, 1, 2))
4217   //     b[i, i+1, i+2, i+3] = v2 - v3
4218   //     br cond, vector.body, middle.block
4219   //
4220   //   middle.block:
4221   //     x = v2(3)
4222   //     br scalar.ph
4223   //
4224   //   scalar.ph:
4225   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4226   //     br scalar.body
4227   //
4228   // After execution completes the vector loop, we extract the next value of
4229   // the recurrence (x) to use as the initial value in the scalar loop.
4230 
4231   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4232 
4233   auto *IdxTy = Builder.getInt32Ty();
4234   auto *One = ConstantInt::get(IdxTy, 1);
4235 
4236   // Create a vector from the initial value.
4237   auto *VectorInit = ScalarInit;
4238   if (VF.isVector()) {
4239     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4240     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4241     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4242     VectorInit = Builder.CreateInsertElement(
4243         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)),
4244         VectorInit, LastIdx, "vector.recur.init");
4245   }
4246 
4247   VPValue *PreviousDef = PhiR->getBackedgeValue();
4248   // We constructed a temporary phi node in the first phase of vectorization.
4249   // This phi node will eventually be deleted.
4250   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiR, 0)));
4251 
4252   // Create a phi node for the new recurrence. The current value will either be
4253   // the initial value inserted into a vector or loop-varying vector value.
4254   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4255   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4256 
4257   // Get the vectorized previous value of the last part UF - 1. It appears last
4258   // among all unrolled iterations, due to the order of their construction.
4259   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4260 
4261   // Find and set the insertion point after the previous value if it is an
4262   // instruction.
4263   BasicBlock::iterator InsertPt;
4264   // Note that the previous value may have been constant-folded so it is not
4265   // guaranteed to be an instruction in the vector loop.
4266   // FIXME: Loop invariant values do not form recurrences. We should deal with
4267   //        them earlier.
4268   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4269     InsertPt = LoopVectorBody->getFirstInsertionPt();
4270   else {
4271     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4272     if (isa<PHINode>(PreviousLastPart))
4273       // If the previous value is a phi node, we should insert after all the phi
4274       // nodes in the block containing the PHI to avoid breaking basic block
4275       // verification. Note that the basic block may be different to
4276       // LoopVectorBody, in case we predicate the loop.
4277       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4278     else
4279       InsertPt = ++PreviousInst->getIterator();
4280   }
4281   Builder.SetInsertPoint(&*InsertPt);
4282 
4283   // The vector from which to take the initial value for the current iteration
4284   // (actual or unrolled). Initially, this is the vector phi node.
4285   Value *Incoming = VecPhi;
4286 
4287   // Shuffle the current and previous vector and update the vector parts.
4288   for (unsigned Part = 0; Part < UF; ++Part) {
4289     Value *PreviousPart = State.get(PreviousDef, Part);
4290     Value *PhiPart = State.get(PhiR, Part);
4291     auto *Shuffle = VF.isVector()
4292                         ? Builder.CreateVectorSplice(Incoming, PreviousPart, -1)
4293                         : Incoming;
4294     PhiPart->replaceAllUsesWith(Shuffle);
4295     cast<Instruction>(PhiPart)->eraseFromParent();
4296     State.reset(PhiR, Shuffle, Part);
4297     Incoming = PreviousPart;
4298   }
4299 
4300   // Fix the latch value of the new recurrence in the vector loop.
4301   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4302 
4303   // Extract the last vector element in the middle block. This will be the
4304   // initial value for the recurrence when jumping to the scalar loop.
4305   auto *ExtractForScalar = Incoming;
4306   if (VF.isVector()) {
4307     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4308     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4309     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4310     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4311                                                     "vector.recur.extract");
4312   }
4313   // Extract the second last element in the middle block if the
4314   // Phi is used outside the loop. We need to extract the phi itself
4315   // and not the last element (the phi update in the current iteration). This
4316   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4317   // when the scalar loop is not run at all.
4318   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4319   if (VF.isVector()) {
4320     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4321     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4322     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4323         Incoming, Idx, "vector.recur.extract.for.phi");
4324   } else if (UF > 1)
4325     // When loop is unrolled without vectorizing, initialize
4326     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4327     // of `Incoming`. This is analogous to the vectorized case above: extracting
4328     // the second last element when VF > 1.
4329     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4330 
4331   // Fix the initial value of the original recurrence in the scalar loop.
4332   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4333   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4334   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4335   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4336     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4337     Start->addIncoming(Incoming, BB);
4338   }
4339 
4340   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4341   Phi->setName("scalar.recur");
4342 
4343   // Finally, fix users of the recurrence outside the loop. The users will need
4344   // either the last value of the scalar recurrence or the last value of the
4345   // vector recurrence we extracted in the middle block. Since the loop is in
4346   // LCSSA form, we just need to find all the phi nodes for the original scalar
4347   // recurrence in the exit block, and then add an edge for the middle block.
4348   // Note that LCSSA does not imply single entry when the original scalar loop
4349   // had multiple exiting edges (as we always run the last iteration in the
4350   // scalar epilogue); in that case, there is no edge from middle to exit and
4351   // and thus no phis which needed updated.
4352   if (!Cost->requiresScalarEpilogue(VF))
4353     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4354       if (any_of(LCSSAPhi.incoming_values(),
4355                  [Phi](Value *V) { return V == Phi; }))
4356         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4357 }
4358 
4359 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4360                                        VPTransformState &State) {
4361   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4362   // Get it's reduction variable descriptor.
4363   assert(Legal->isReductionVariable(OrigPhi) &&
4364          "Unable to find the reduction variable");
4365   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4366 
4367   RecurKind RK = RdxDesc.getRecurrenceKind();
4368   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4369   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4370   setDebugLocFromInst(ReductionStartValue);
4371 
4372   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4373   // This is the vector-clone of the value that leaves the loop.
4374   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4375 
4376   // Wrap flags are in general invalid after vectorization, clear them.
4377   clearReductionWrapFlags(RdxDesc, State);
4378 
4379   // Fix the vector-loop phi.
4380 
4381   // Reductions do not have to start at zero. They can start with
4382   // any loop invariant values.
4383   BasicBlock *VectorLoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4384 
4385   unsigned LastPartForNewPhi = PhiR->isOrdered() ? 1 : UF;
4386   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
4387     Value *VecRdxPhi = State.get(PhiR->getVPSingleValue(), Part);
4388     Value *Val = State.get(PhiR->getBackedgeValue(), Part);
4389     if (PhiR->isOrdered())
4390       Val = State.get(PhiR->getBackedgeValue(), UF - 1);
4391 
4392     cast<PHINode>(VecRdxPhi)->addIncoming(Val, VectorLoopLatch);
4393   }
4394 
4395   // Before each round, move the insertion point right between
4396   // the PHIs and the values we are going to write.
4397   // This allows us to write both PHINodes and the extractelement
4398   // instructions.
4399   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4400 
4401   setDebugLocFromInst(LoopExitInst);
4402 
4403   Type *PhiTy = OrigPhi->getType();
4404   // If tail is folded by masking, the vector value to leave the loop should be
4405   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4406   // instead of the former. For an inloop reduction the reduction will already
4407   // be predicated, and does not need to be handled here.
4408   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4409     for (unsigned Part = 0; Part < UF; ++Part) {
4410       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4411       Value *Sel = nullptr;
4412       for (User *U : VecLoopExitInst->users()) {
4413         if (isa<SelectInst>(U)) {
4414           assert(!Sel && "Reduction exit feeding two selects");
4415           Sel = U;
4416         } else
4417           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4418       }
4419       assert(Sel && "Reduction exit feeds no select");
4420       State.reset(LoopExitInstDef, Sel, Part);
4421 
4422       // If the target can create a predicated operator for the reduction at no
4423       // extra cost in the loop (for example a predicated vadd), it can be
4424       // cheaper for the select to remain in the loop than be sunk out of it,
4425       // and so use the select value for the phi instead of the old
4426       // LoopExitValue.
4427       if (PreferPredicatedReductionSelect ||
4428           TTI->preferPredicatedReductionSelect(
4429               RdxDesc.getOpcode(), PhiTy,
4430               TargetTransformInfo::ReductionFlags())) {
4431         auto *VecRdxPhi =
4432             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4433         VecRdxPhi->setIncomingValueForBlock(
4434             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4435       }
4436     }
4437   }
4438 
4439   // If the vector reduction can be performed in a smaller type, we truncate
4440   // then extend the loop exit value to enable InstCombine to evaluate the
4441   // entire expression in the smaller type.
4442   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4443     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4444     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4445     Builder.SetInsertPoint(
4446         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4447     VectorParts RdxParts(UF);
4448     for (unsigned Part = 0; Part < UF; ++Part) {
4449       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4450       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4451       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4452                                         : Builder.CreateZExt(Trunc, VecTy);
4453       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4454            UI != RdxParts[Part]->user_end();)
4455         if (*UI != Trunc) {
4456           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4457           RdxParts[Part] = Extnd;
4458         } else {
4459           ++UI;
4460         }
4461     }
4462     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4463     for (unsigned Part = 0; Part < UF; ++Part) {
4464       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4465       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4466     }
4467   }
4468 
4469   // Reduce all of the unrolled parts into a single vector.
4470   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4471   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4472 
4473   // The middle block terminator has already been assigned a DebugLoc here (the
4474   // OrigLoop's single latch terminator). We want the whole middle block to
4475   // appear to execute on this line because: (a) it is all compiler generated,
4476   // (b) these instructions are always executed after evaluating the latch
4477   // conditional branch, and (c) other passes may add new predecessors which
4478   // terminate on this line. This is the easiest way to ensure we don't
4479   // accidentally cause an extra step back into the loop while debugging.
4480   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4481   if (PhiR->isOrdered())
4482     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4483   else {
4484     // Floating-point operations should have some FMF to enable the reduction.
4485     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4486     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4487     for (unsigned Part = 1; Part < UF; ++Part) {
4488       Value *RdxPart = State.get(LoopExitInstDef, Part);
4489       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4490         ReducedPartRdx = Builder.CreateBinOp(
4491             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4492       } else {
4493         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4494       }
4495     }
4496   }
4497 
4498   // Create the reduction after the loop. Note that inloop reductions create the
4499   // target reduction in the loop using a Reduction recipe.
4500   if (VF.isVector() && !PhiR->isInLoop()) {
4501     ReducedPartRdx =
4502         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4503     // If the reduction can be performed in a smaller type, we need to extend
4504     // the reduction to the wider type before we branch to the original loop.
4505     if (PhiTy != RdxDesc.getRecurrenceType())
4506       ReducedPartRdx = RdxDesc.isSigned()
4507                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4508                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4509   }
4510 
4511   // Create a phi node that merges control-flow from the backedge-taken check
4512   // block and the middle block.
4513   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4514                                         LoopScalarPreHeader->getTerminator());
4515   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4516     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4517   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4518 
4519   // Now, we need to fix the users of the reduction variable
4520   // inside and outside of the scalar remainder loop.
4521 
4522   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4523   // in the exit blocks.  See comment on analogous loop in
4524   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4525   if (!Cost->requiresScalarEpilogue(VF))
4526     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4527       if (any_of(LCSSAPhi.incoming_values(),
4528                  [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4529         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4530 
4531   // Fix the scalar loop reduction variable with the incoming reduction sum
4532   // from the vector body and from the backedge value.
4533   int IncomingEdgeBlockIdx =
4534       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4535   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4536   // Pick the other block.
4537   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4538   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4539   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4540 }
4541 
4542 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4543                                                   VPTransformState &State) {
4544   RecurKind RK = RdxDesc.getRecurrenceKind();
4545   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4546     return;
4547 
4548   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4549   assert(LoopExitInstr && "null loop exit instruction");
4550   SmallVector<Instruction *, 8> Worklist;
4551   SmallPtrSet<Instruction *, 8> Visited;
4552   Worklist.push_back(LoopExitInstr);
4553   Visited.insert(LoopExitInstr);
4554 
4555   while (!Worklist.empty()) {
4556     Instruction *Cur = Worklist.pop_back_val();
4557     if (isa<OverflowingBinaryOperator>(Cur))
4558       for (unsigned Part = 0; Part < UF; ++Part) {
4559         Value *V = State.get(State.Plan->getVPValue(Cur), Part);
4560         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4561       }
4562 
4563     for (User *U : Cur->users()) {
4564       Instruction *UI = cast<Instruction>(U);
4565       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4566           Visited.insert(UI).second)
4567         Worklist.push_back(UI);
4568     }
4569   }
4570 }
4571 
4572 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4573   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4574     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4575       // Some phis were already hand updated by the reduction and recurrence
4576       // code above, leave them alone.
4577       continue;
4578 
4579     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4580     // Non-instruction incoming values will have only one value.
4581 
4582     VPLane Lane = VPLane::getFirstLane();
4583     if (isa<Instruction>(IncomingValue) &&
4584         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4585                                            VF))
4586       Lane = VPLane::getLastLaneForVF(VF);
4587 
4588     // Can be a loop invariant incoming value or the last scalar value to be
4589     // extracted from the vectorized loop.
4590     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4591     Value *lastIncomingValue =
4592         OrigLoop->isLoopInvariant(IncomingValue)
4593             ? IncomingValue
4594             : State.get(State.Plan->getVPValue(IncomingValue),
4595                         VPIteration(UF - 1, Lane));
4596     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4597   }
4598 }
4599 
4600 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4601   // The basic block and loop containing the predicated instruction.
4602   auto *PredBB = PredInst->getParent();
4603   auto *VectorLoop = LI->getLoopFor(PredBB);
4604 
4605   // Initialize a worklist with the operands of the predicated instruction.
4606   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4607 
4608   // Holds instructions that we need to analyze again. An instruction may be
4609   // reanalyzed if we don't yet know if we can sink it or not.
4610   SmallVector<Instruction *, 8> InstsToReanalyze;
4611 
4612   // Returns true if a given use occurs in the predicated block. Phi nodes use
4613   // their operands in their corresponding predecessor blocks.
4614   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4615     auto *I = cast<Instruction>(U.getUser());
4616     BasicBlock *BB = I->getParent();
4617     if (auto *Phi = dyn_cast<PHINode>(I))
4618       BB = Phi->getIncomingBlock(
4619           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4620     return BB == PredBB;
4621   };
4622 
4623   // Iteratively sink the scalarized operands of the predicated instruction
4624   // into the block we created for it. When an instruction is sunk, it's
4625   // operands are then added to the worklist. The algorithm ends after one pass
4626   // through the worklist doesn't sink a single instruction.
4627   bool Changed;
4628   do {
4629     // Add the instructions that need to be reanalyzed to the worklist, and
4630     // reset the changed indicator.
4631     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4632     InstsToReanalyze.clear();
4633     Changed = false;
4634 
4635     while (!Worklist.empty()) {
4636       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4637 
4638       // We can't sink an instruction if it is a phi node, is not in the loop,
4639       // or may have side effects.
4640       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4641           I->mayHaveSideEffects())
4642         continue;
4643 
4644       // If the instruction is already in PredBB, check if we can sink its
4645       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4646       // sinking the scalar instruction I, hence it appears in PredBB; but it
4647       // may have failed to sink I's operands (recursively), which we try
4648       // (again) here.
4649       if (I->getParent() == PredBB) {
4650         Worklist.insert(I->op_begin(), I->op_end());
4651         continue;
4652       }
4653 
4654       // It's legal to sink the instruction if all its uses occur in the
4655       // predicated block. Otherwise, there's nothing to do yet, and we may
4656       // need to reanalyze the instruction.
4657       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4658         InstsToReanalyze.push_back(I);
4659         continue;
4660       }
4661 
4662       // Move the instruction to the beginning of the predicated block, and add
4663       // it's operands to the worklist.
4664       I->moveBefore(&*PredBB->getFirstInsertionPt());
4665       Worklist.insert(I->op_begin(), I->op_end());
4666 
4667       // The sinking may have enabled other instructions to be sunk, so we will
4668       // need to iterate.
4669       Changed = true;
4670     }
4671   } while (Changed);
4672 }
4673 
4674 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4675   for (PHINode *OrigPhi : OrigPHIsToFix) {
4676     VPWidenPHIRecipe *VPPhi =
4677         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4678     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4679     // Make sure the builder has a valid insert point.
4680     Builder.SetInsertPoint(NewPhi);
4681     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4682       VPValue *Inc = VPPhi->getIncomingValue(i);
4683       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4684       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4685     }
4686   }
4687 }
4688 
4689 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4690   return Cost->useOrderedReductions(RdxDesc);
4691 }
4692 
4693 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4694                                    VPUser &Operands, unsigned UF,
4695                                    ElementCount VF, bool IsPtrLoopInvariant,
4696                                    SmallBitVector &IsIndexLoopInvariant,
4697                                    VPTransformState &State) {
4698   // Construct a vector GEP by widening the operands of the scalar GEP as
4699   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4700   // results in a vector of pointers when at least one operand of the GEP
4701   // is vector-typed. Thus, to keep the representation compact, we only use
4702   // vector-typed operands for loop-varying values.
4703 
4704   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4705     // If we are vectorizing, but the GEP has only loop-invariant operands,
4706     // the GEP we build (by only using vector-typed operands for
4707     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4708     // produce a vector of pointers, we need to either arbitrarily pick an
4709     // operand to broadcast, or broadcast a clone of the original GEP.
4710     // Here, we broadcast a clone of the original.
4711     //
4712     // TODO: If at some point we decide to scalarize instructions having
4713     //       loop-invariant operands, this special case will no longer be
4714     //       required. We would add the scalarization decision to
4715     //       collectLoopScalars() and teach getVectorValue() to broadcast
4716     //       the lane-zero scalar value.
4717     auto *Clone = Builder.Insert(GEP->clone());
4718     for (unsigned Part = 0; Part < UF; ++Part) {
4719       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4720       State.set(VPDef, EntryPart, Part);
4721       addMetadata(EntryPart, GEP);
4722     }
4723   } else {
4724     // If the GEP has at least one loop-varying operand, we are sure to
4725     // produce a vector of pointers. But if we are only unrolling, we want
4726     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4727     // produce with the code below will be scalar (if VF == 1) or vector
4728     // (otherwise). Note that for the unroll-only case, we still maintain
4729     // values in the vector mapping with initVector, as we do for other
4730     // instructions.
4731     for (unsigned Part = 0; Part < UF; ++Part) {
4732       // The pointer operand of the new GEP. If it's loop-invariant, we
4733       // won't broadcast it.
4734       auto *Ptr = IsPtrLoopInvariant
4735                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4736                       : State.get(Operands.getOperand(0), Part);
4737 
4738       // Collect all the indices for the new GEP. If any index is
4739       // loop-invariant, we won't broadcast it.
4740       SmallVector<Value *, 4> Indices;
4741       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4742         VPValue *Operand = Operands.getOperand(I);
4743         if (IsIndexLoopInvariant[I - 1])
4744           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4745         else
4746           Indices.push_back(State.get(Operand, Part));
4747       }
4748 
4749       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4750       // but it should be a vector, otherwise.
4751       auto *NewGEP =
4752           GEP->isInBounds()
4753               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4754                                           Indices)
4755               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4756       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4757              "NewGEP is not a pointer vector");
4758       State.set(VPDef, NewGEP, Part);
4759       addMetadata(NewGEP, GEP);
4760     }
4761   }
4762 }
4763 
4764 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4765                                               VPWidenPHIRecipe *PhiR,
4766                                               VPTransformState &State) {
4767   PHINode *P = cast<PHINode>(PN);
4768   if (EnableVPlanNativePath) {
4769     // Currently we enter here in the VPlan-native path for non-induction
4770     // PHIs where all control flow is uniform. We simply widen these PHIs.
4771     // Create a vector phi with no operands - the vector phi operands will be
4772     // set at the end of vector code generation.
4773     Type *VecTy = (State.VF.isScalar())
4774                       ? PN->getType()
4775                       : VectorType::get(PN->getType(), State.VF);
4776     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4777     State.set(PhiR, VecPhi, 0);
4778     OrigPHIsToFix.push_back(P);
4779 
4780     return;
4781   }
4782 
4783   assert(PN->getParent() == OrigLoop->getHeader() &&
4784          "Non-header phis should have been handled elsewhere");
4785 
4786   // In order to support recurrences we need to be able to vectorize Phi nodes.
4787   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4788   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4789   // this value when we vectorize all of the instructions that use the PHI.
4790   if (Legal->isFirstOrderRecurrence(P)) {
4791     Type *VecTy = State.VF.isScalar()
4792                       ? PN->getType()
4793                       : VectorType::get(PN->getType(), State.VF);
4794 
4795     for (unsigned Part = 0; Part < State.UF; ++Part) {
4796       Value *EntryPart = PHINode::Create(
4797           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4798       State.set(PhiR, EntryPart, Part);
4799     }
4800       return;
4801   }
4802 
4803   assert(!Legal->isReductionVariable(P) &&
4804          "reductions should be handled elsewhere");
4805 
4806   setDebugLocFromInst(P);
4807 
4808   // This PHINode must be an induction variable.
4809   // Make sure that we know about it.
4810   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4811 
4812   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4813   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4814 
4815   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4816   // which can be found from the original scalar operations.
4817   switch (II.getKind()) {
4818   case InductionDescriptor::IK_NoInduction:
4819     llvm_unreachable("Unknown induction");
4820   case InductionDescriptor::IK_IntInduction:
4821   case InductionDescriptor::IK_FpInduction:
4822     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4823   case InductionDescriptor::IK_PtrInduction: {
4824     // Handle the pointer induction variable case.
4825     assert(P->getType()->isPointerTy() && "Unexpected type.");
4826 
4827     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4828       // This is the normalized GEP that starts counting at zero.
4829       Value *PtrInd =
4830           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4831       // Determine the number of scalars we need to generate for each unroll
4832       // iteration. If the instruction is uniform, we only need to generate the
4833       // first lane. Otherwise, we generate all VF values.
4834       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4835       unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
4836 
4837       bool NeedsVectorIndex = !IsUniform && VF.isScalable();
4838       Value *UnitStepVec = nullptr, *PtrIndSplat = nullptr;
4839       if (NeedsVectorIndex) {
4840         Type *VecIVTy = VectorType::get(PtrInd->getType(), VF);
4841         UnitStepVec = Builder.CreateStepVector(VecIVTy);
4842         PtrIndSplat = Builder.CreateVectorSplat(VF, PtrInd);
4843       }
4844 
4845       for (unsigned Part = 0; Part < UF; ++Part) {
4846         Value *PartStart = createStepForVF(
4847             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4848 
4849         if (NeedsVectorIndex) {
4850           Value *PartStartSplat = Builder.CreateVectorSplat(VF, PartStart);
4851           Value *Indices = Builder.CreateAdd(PartStartSplat, UnitStepVec);
4852           Value *GlobalIndices = Builder.CreateAdd(PtrIndSplat, Indices);
4853           Value *SclrGep =
4854               emitTransformedIndex(Builder, GlobalIndices, PSE.getSE(), DL, II);
4855           SclrGep->setName("next.gep");
4856           State.set(PhiR, SclrGep, Part);
4857           // We've cached the whole vector, which means we can support the
4858           // extraction of any lane.
4859           continue;
4860         }
4861 
4862         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4863           Value *Idx = Builder.CreateAdd(
4864               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4865           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4866           Value *SclrGep =
4867               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4868           SclrGep->setName("next.gep");
4869           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4870         }
4871       }
4872       return;
4873     }
4874     assert(isa<SCEVConstant>(II.getStep()) &&
4875            "Induction step not a SCEV constant!");
4876     Type *PhiType = II.getStep()->getType();
4877 
4878     // Build a pointer phi
4879     Value *ScalarStartValue = II.getStartValue();
4880     Type *ScStValueType = ScalarStartValue->getType();
4881     PHINode *NewPointerPhi =
4882         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4883     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4884 
4885     // A pointer induction, performed by using a gep
4886     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4887     Instruction *InductionLoc = LoopLatch->getTerminator();
4888     const SCEV *ScalarStep = II.getStep();
4889     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4890     Value *ScalarStepValue =
4891         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4892     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4893     Value *NumUnrolledElems =
4894         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4895     Value *InductionGEP = GetElementPtrInst::Create(
4896         ScStValueType->getPointerElementType(), NewPointerPhi,
4897         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4898         InductionLoc);
4899     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4900 
4901     // Create UF many actual address geps that use the pointer
4902     // phi as base and a vectorized version of the step value
4903     // (<step*0, ..., step*N>) as offset.
4904     for (unsigned Part = 0; Part < State.UF; ++Part) {
4905       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4906       Value *StartOffsetScalar =
4907           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4908       Value *StartOffset =
4909           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4910       // Create a vector of consecutive numbers from zero to VF.
4911       StartOffset =
4912           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4913 
4914       Value *GEP = Builder.CreateGEP(
4915           ScStValueType->getPointerElementType(), NewPointerPhi,
4916           Builder.CreateMul(
4917               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4918               "vector.gep"));
4919       State.set(PhiR, GEP, Part);
4920     }
4921   }
4922   }
4923 }
4924 
4925 /// A helper function for checking whether an integer division-related
4926 /// instruction may divide by zero (in which case it must be predicated if
4927 /// executed conditionally in the scalar code).
4928 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4929 /// Non-zero divisors that are non compile-time constants will not be
4930 /// converted into multiplication, so we will still end up scalarizing
4931 /// the division, but can do so w/o predication.
4932 static bool mayDivideByZero(Instruction &I) {
4933   assert((I.getOpcode() == Instruction::UDiv ||
4934           I.getOpcode() == Instruction::SDiv ||
4935           I.getOpcode() == Instruction::URem ||
4936           I.getOpcode() == Instruction::SRem) &&
4937          "Unexpected instruction");
4938   Value *Divisor = I.getOperand(1);
4939   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4940   return !CInt || CInt->isZero();
4941 }
4942 
4943 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4944                                            VPUser &User,
4945                                            VPTransformState &State) {
4946   switch (I.getOpcode()) {
4947   case Instruction::Call:
4948   case Instruction::Br:
4949   case Instruction::PHI:
4950   case Instruction::GetElementPtr:
4951   case Instruction::Select:
4952     llvm_unreachable("This instruction is handled by a different recipe.");
4953   case Instruction::UDiv:
4954   case Instruction::SDiv:
4955   case Instruction::SRem:
4956   case Instruction::URem:
4957   case Instruction::Add:
4958   case Instruction::FAdd:
4959   case Instruction::Sub:
4960   case Instruction::FSub:
4961   case Instruction::FNeg:
4962   case Instruction::Mul:
4963   case Instruction::FMul:
4964   case Instruction::FDiv:
4965   case Instruction::FRem:
4966   case Instruction::Shl:
4967   case Instruction::LShr:
4968   case Instruction::AShr:
4969   case Instruction::And:
4970   case Instruction::Or:
4971   case Instruction::Xor: {
4972     // Just widen unops and binops.
4973     setDebugLocFromInst(&I);
4974 
4975     for (unsigned Part = 0; Part < UF; ++Part) {
4976       SmallVector<Value *, 2> Ops;
4977       for (VPValue *VPOp : User.operands())
4978         Ops.push_back(State.get(VPOp, Part));
4979 
4980       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4981 
4982       if (auto *VecOp = dyn_cast<Instruction>(V))
4983         VecOp->copyIRFlags(&I);
4984 
4985       // Use this vector value for all users of the original instruction.
4986       State.set(Def, V, Part);
4987       addMetadata(V, &I);
4988     }
4989 
4990     break;
4991   }
4992   case Instruction::ICmp:
4993   case Instruction::FCmp: {
4994     // Widen compares. Generate vector compares.
4995     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4996     auto *Cmp = cast<CmpInst>(&I);
4997     setDebugLocFromInst(Cmp);
4998     for (unsigned Part = 0; Part < UF; ++Part) {
4999       Value *A = State.get(User.getOperand(0), Part);
5000       Value *B = State.get(User.getOperand(1), Part);
5001       Value *C = nullptr;
5002       if (FCmp) {
5003         // Propagate fast math flags.
5004         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
5005         Builder.setFastMathFlags(Cmp->getFastMathFlags());
5006         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
5007       } else {
5008         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
5009       }
5010       State.set(Def, C, Part);
5011       addMetadata(C, &I);
5012     }
5013 
5014     break;
5015   }
5016 
5017   case Instruction::ZExt:
5018   case Instruction::SExt:
5019   case Instruction::FPToUI:
5020   case Instruction::FPToSI:
5021   case Instruction::FPExt:
5022   case Instruction::PtrToInt:
5023   case Instruction::IntToPtr:
5024   case Instruction::SIToFP:
5025   case Instruction::UIToFP:
5026   case Instruction::Trunc:
5027   case Instruction::FPTrunc:
5028   case Instruction::BitCast: {
5029     auto *CI = cast<CastInst>(&I);
5030     setDebugLocFromInst(CI);
5031 
5032     /// Vectorize casts.
5033     Type *DestTy =
5034         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
5035 
5036     for (unsigned Part = 0; Part < UF; ++Part) {
5037       Value *A = State.get(User.getOperand(0), Part);
5038       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
5039       State.set(Def, Cast, Part);
5040       addMetadata(Cast, &I);
5041     }
5042     break;
5043   }
5044   default:
5045     // This instruction is not vectorized by simple widening.
5046     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
5047     llvm_unreachable("Unhandled instruction!");
5048   } // end of switch.
5049 }
5050 
5051 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
5052                                                VPUser &ArgOperands,
5053                                                VPTransformState &State) {
5054   assert(!isa<DbgInfoIntrinsic>(I) &&
5055          "DbgInfoIntrinsic should have been dropped during VPlan construction");
5056   setDebugLocFromInst(&I);
5057 
5058   Module *M = I.getParent()->getParent()->getParent();
5059   auto *CI = cast<CallInst>(&I);
5060 
5061   SmallVector<Type *, 4> Tys;
5062   for (Value *ArgOperand : CI->arg_operands())
5063     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
5064 
5065   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5066 
5067   // The flag shows whether we use Intrinsic or a usual Call for vectorized
5068   // version of the instruction.
5069   // Is it beneficial to perform intrinsic call compared to lib call?
5070   bool NeedToScalarize = false;
5071   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
5072   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
5073   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
5074   assert((UseVectorIntrinsic || !NeedToScalarize) &&
5075          "Instruction should be scalarized elsewhere.");
5076   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
5077          "Either the intrinsic cost or vector call cost must be valid");
5078 
5079   for (unsigned Part = 0; Part < UF; ++Part) {
5080     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
5081     SmallVector<Value *, 4> Args;
5082     for (auto &I : enumerate(ArgOperands.operands())) {
5083       // Some intrinsics have a scalar argument - don't replace it with a
5084       // vector.
5085       Value *Arg;
5086       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5087         Arg = State.get(I.value(), Part);
5088       else {
5089         Arg = State.get(I.value(), VPIteration(0, 0));
5090         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
5091           TysForDecl.push_back(Arg->getType());
5092       }
5093       Args.push_back(Arg);
5094     }
5095 
5096     Function *VectorF;
5097     if (UseVectorIntrinsic) {
5098       // Use vector version of the intrinsic.
5099       if (VF.isVector())
5100         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5101       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5102       assert(VectorF && "Can't retrieve vector intrinsic.");
5103     } else {
5104       // Use vector version of the function call.
5105       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5106 #ifndef NDEBUG
5107       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5108              "Can't create vector function.");
5109 #endif
5110         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5111     }
5112       SmallVector<OperandBundleDef, 1> OpBundles;
5113       CI->getOperandBundlesAsDefs(OpBundles);
5114       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5115 
5116       if (isa<FPMathOperator>(V))
5117         V->copyFastMathFlags(CI);
5118 
5119       State.set(Def, V, Part);
5120       addMetadata(V, &I);
5121   }
5122 }
5123 
5124 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5125                                                  VPUser &Operands,
5126                                                  bool InvariantCond,
5127                                                  VPTransformState &State) {
5128   setDebugLocFromInst(&I);
5129 
5130   // The condition can be loop invariant  but still defined inside the
5131   // loop. This means that we can't just use the original 'cond' value.
5132   // We have to take the 'vectorized' value and pick the first lane.
5133   // Instcombine will make this a no-op.
5134   auto *InvarCond = InvariantCond
5135                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5136                         : nullptr;
5137 
5138   for (unsigned Part = 0; Part < UF; ++Part) {
5139     Value *Cond =
5140         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5141     Value *Op0 = State.get(Operands.getOperand(1), Part);
5142     Value *Op1 = State.get(Operands.getOperand(2), Part);
5143     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5144     State.set(VPDef, Sel, Part);
5145     addMetadata(Sel, &I);
5146   }
5147 }
5148 
5149 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5150   // We should not collect Scalars more than once per VF. Right now, this
5151   // function is called from collectUniformsAndScalars(), which already does
5152   // this check. Collecting Scalars for VF=1 does not make any sense.
5153   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5154          "This function should not be visited twice for the same VF");
5155 
5156   SmallSetVector<Instruction *, 8> Worklist;
5157 
5158   // These sets are used to seed the analysis with pointers used by memory
5159   // accesses that will remain scalar.
5160   SmallSetVector<Instruction *, 8> ScalarPtrs;
5161   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5162   auto *Latch = TheLoop->getLoopLatch();
5163 
5164   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5165   // The pointer operands of loads and stores will be scalar as long as the
5166   // memory access is not a gather or scatter operation. The value operand of a
5167   // store will remain scalar if the store is scalarized.
5168   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5169     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5170     assert(WideningDecision != CM_Unknown &&
5171            "Widening decision should be ready at this moment");
5172     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5173       if (Ptr == Store->getValueOperand())
5174         return WideningDecision == CM_Scalarize;
5175     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5176            "Ptr is neither a value or pointer operand");
5177     return WideningDecision != CM_GatherScatter;
5178   };
5179 
5180   // A helper that returns true if the given value is a bitcast or
5181   // getelementptr instruction contained in the loop.
5182   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5183     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5184             isa<GetElementPtrInst>(V)) &&
5185            !TheLoop->isLoopInvariant(V);
5186   };
5187 
5188   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5189     if (!isa<PHINode>(Ptr) ||
5190         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5191       return false;
5192     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5193     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5194       return false;
5195     return isScalarUse(MemAccess, Ptr);
5196   };
5197 
5198   // A helper that evaluates a memory access's use of a pointer. If the
5199   // pointer is actually the pointer induction of a loop, it is being
5200   // inserted into Worklist. If the use will be a scalar use, and the
5201   // pointer is only used by memory accesses, we place the pointer in
5202   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5203   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5204     if (isScalarPtrInduction(MemAccess, Ptr)) {
5205       Worklist.insert(cast<Instruction>(Ptr));
5206       Instruction *Update = cast<Instruction>(
5207           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5208       Worklist.insert(Update);
5209       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5210                         << "\n");
5211       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5212                         << "\n");
5213       return;
5214     }
5215     // We only care about bitcast and getelementptr instructions contained in
5216     // the loop.
5217     if (!isLoopVaryingBitCastOrGEP(Ptr))
5218       return;
5219 
5220     // If the pointer has already been identified as scalar (e.g., if it was
5221     // also identified as uniform), there's nothing to do.
5222     auto *I = cast<Instruction>(Ptr);
5223     if (Worklist.count(I))
5224       return;
5225 
5226     // If the use of the pointer will be a scalar use, and all users of the
5227     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5228     // place the pointer in PossibleNonScalarPtrs.
5229     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5230           return isa<LoadInst>(U) || isa<StoreInst>(U);
5231         }))
5232       ScalarPtrs.insert(I);
5233     else
5234       PossibleNonScalarPtrs.insert(I);
5235   };
5236 
5237   // We seed the scalars analysis with three classes of instructions: (1)
5238   // instructions marked uniform-after-vectorization and (2) bitcast,
5239   // getelementptr and (pointer) phi instructions used by memory accesses
5240   // requiring a scalar use.
5241   //
5242   // (1) Add to the worklist all instructions that have been identified as
5243   // uniform-after-vectorization.
5244   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5245 
5246   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5247   // memory accesses requiring a scalar use. The pointer operands of loads and
5248   // stores will be scalar as long as the memory accesses is not a gather or
5249   // scatter operation. The value operand of a store will remain scalar if the
5250   // store is scalarized.
5251   for (auto *BB : TheLoop->blocks())
5252     for (auto &I : *BB) {
5253       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5254         evaluatePtrUse(Load, Load->getPointerOperand());
5255       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5256         evaluatePtrUse(Store, Store->getPointerOperand());
5257         evaluatePtrUse(Store, Store->getValueOperand());
5258       }
5259     }
5260   for (auto *I : ScalarPtrs)
5261     if (!PossibleNonScalarPtrs.count(I)) {
5262       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5263       Worklist.insert(I);
5264     }
5265 
5266   // Insert the forced scalars.
5267   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5268   // induction variable when the PHI user is scalarized.
5269   auto ForcedScalar = ForcedScalars.find(VF);
5270   if (ForcedScalar != ForcedScalars.end())
5271     for (auto *I : ForcedScalar->second)
5272       Worklist.insert(I);
5273 
5274   // Expand the worklist by looking through any bitcasts and getelementptr
5275   // instructions we've already identified as scalar. This is similar to the
5276   // expansion step in collectLoopUniforms(); however, here we're only
5277   // expanding to include additional bitcasts and getelementptr instructions.
5278   unsigned Idx = 0;
5279   while (Idx != Worklist.size()) {
5280     Instruction *Dst = Worklist[Idx++];
5281     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5282       continue;
5283     auto *Src = cast<Instruction>(Dst->getOperand(0));
5284     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5285           auto *J = cast<Instruction>(U);
5286           return !TheLoop->contains(J) || Worklist.count(J) ||
5287                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5288                   isScalarUse(J, Src));
5289         })) {
5290       Worklist.insert(Src);
5291       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5292     }
5293   }
5294 
5295   // An induction variable will remain scalar if all users of the induction
5296   // variable and induction variable update remain scalar.
5297   for (auto &Induction : Legal->getInductionVars()) {
5298     auto *Ind = Induction.first;
5299     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5300 
5301     // If tail-folding is applied, the primary induction variable will be used
5302     // to feed a vector compare.
5303     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5304       continue;
5305 
5306     // Determine if all users of the induction variable are scalar after
5307     // vectorization.
5308     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5309       auto *I = cast<Instruction>(U);
5310       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5311     });
5312     if (!ScalarInd)
5313       continue;
5314 
5315     // Determine if all users of the induction variable update instruction are
5316     // scalar after vectorization.
5317     auto ScalarIndUpdate =
5318         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5319           auto *I = cast<Instruction>(U);
5320           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5321         });
5322     if (!ScalarIndUpdate)
5323       continue;
5324 
5325     // The induction variable and its update instruction will remain scalar.
5326     Worklist.insert(Ind);
5327     Worklist.insert(IndUpdate);
5328     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5329     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5330                       << "\n");
5331   }
5332 
5333   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5334 }
5335 
5336 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5337   if (!blockNeedsPredication(I->getParent()))
5338     return false;
5339   switch(I->getOpcode()) {
5340   default:
5341     break;
5342   case Instruction::Load:
5343   case Instruction::Store: {
5344     if (!Legal->isMaskRequired(I))
5345       return false;
5346     auto *Ptr = getLoadStorePointerOperand(I);
5347     auto *Ty = getLoadStoreType(I);
5348     const Align Alignment = getLoadStoreAlignment(I);
5349     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5350                                 TTI.isLegalMaskedGather(Ty, Alignment))
5351                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5352                                 TTI.isLegalMaskedScatter(Ty, Alignment));
5353   }
5354   case Instruction::UDiv:
5355   case Instruction::SDiv:
5356   case Instruction::SRem:
5357   case Instruction::URem:
5358     return mayDivideByZero(*I);
5359   }
5360   return false;
5361 }
5362 
5363 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5364     Instruction *I, ElementCount VF) {
5365   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5366   assert(getWideningDecision(I, VF) == CM_Unknown &&
5367          "Decision should not be set yet.");
5368   auto *Group = getInterleavedAccessGroup(I);
5369   assert(Group && "Must have a group.");
5370 
5371   // If the instruction's allocated size doesn't equal it's type size, it
5372   // requires padding and will be scalarized.
5373   auto &DL = I->getModule()->getDataLayout();
5374   auto *ScalarTy = getLoadStoreType(I);
5375   if (hasIrregularType(ScalarTy, DL))
5376     return false;
5377 
5378   // Check if masking is required.
5379   // A Group may need masking for one of two reasons: it resides in a block that
5380   // needs predication, or it was decided to use masking to deal with gaps.
5381   bool PredicatedAccessRequiresMasking =
5382       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5383   bool AccessWithGapsRequiresMasking =
5384       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5385   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5386     return true;
5387 
5388   // If masked interleaving is required, we expect that the user/target had
5389   // enabled it, because otherwise it either wouldn't have been created or
5390   // it should have been invalidated by the CostModel.
5391   assert(useMaskedInterleavedAccesses(TTI) &&
5392          "Masked interleave-groups for predicated accesses are not enabled.");
5393 
5394   auto *Ty = getLoadStoreType(I);
5395   const Align Alignment = getLoadStoreAlignment(I);
5396   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5397                           : TTI.isLegalMaskedStore(Ty, Alignment);
5398 }
5399 
5400 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5401     Instruction *I, ElementCount VF) {
5402   // Get and ensure we have a valid memory instruction.
5403   LoadInst *LI = dyn_cast<LoadInst>(I);
5404   StoreInst *SI = dyn_cast<StoreInst>(I);
5405   assert((LI || SI) && "Invalid memory instruction");
5406 
5407   auto *Ptr = getLoadStorePointerOperand(I);
5408 
5409   // In order to be widened, the pointer should be consecutive, first of all.
5410   if (!Legal->isConsecutivePtr(Ptr))
5411     return false;
5412 
5413   // If the instruction is a store located in a predicated block, it will be
5414   // scalarized.
5415   if (isScalarWithPredication(I))
5416     return false;
5417 
5418   // If the instruction's allocated size doesn't equal it's type size, it
5419   // requires padding and will be scalarized.
5420   auto &DL = I->getModule()->getDataLayout();
5421   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5422   if (hasIrregularType(ScalarTy, DL))
5423     return false;
5424 
5425   return true;
5426 }
5427 
5428 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5429   // We should not collect Uniforms more than once per VF. Right now,
5430   // this function is called from collectUniformsAndScalars(), which
5431   // already does this check. Collecting Uniforms for VF=1 does not make any
5432   // sense.
5433 
5434   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5435          "This function should not be visited twice for the same VF");
5436 
5437   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5438   // not analyze again.  Uniforms.count(VF) will return 1.
5439   Uniforms[VF].clear();
5440 
5441   // We now know that the loop is vectorizable!
5442   // Collect instructions inside the loop that will remain uniform after
5443   // vectorization.
5444 
5445   // Global values, params and instructions outside of current loop are out of
5446   // scope.
5447   auto isOutOfScope = [&](Value *V) -> bool {
5448     Instruction *I = dyn_cast<Instruction>(V);
5449     return (!I || !TheLoop->contains(I));
5450   };
5451 
5452   SetVector<Instruction *> Worklist;
5453   BasicBlock *Latch = TheLoop->getLoopLatch();
5454 
5455   // Instructions that are scalar with predication must not be considered
5456   // uniform after vectorization, because that would create an erroneous
5457   // replicating region where only a single instance out of VF should be formed.
5458   // TODO: optimize such seldom cases if found important, see PR40816.
5459   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5460     if (isOutOfScope(I)) {
5461       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5462                         << *I << "\n");
5463       return;
5464     }
5465     if (isScalarWithPredication(I)) {
5466       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5467                         << *I << "\n");
5468       return;
5469     }
5470     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5471     Worklist.insert(I);
5472   };
5473 
5474   // Start with the conditional branch. If the branch condition is an
5475   // instruction contained in the loop that is only used by the branch, it is
5476   // uniform.
5477   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5478   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5479     addToWorklistIfAllowed(Cmp);
5480 
5481   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5482     InstWidening WideningDecision = getWideningDecision(I, VF);
5483     assert(WideningDecision != CM_Unknown &&
5484            "Widening decision should be ready at this moment");
5485 
5486     // A uniform memory op is itself uniform.  We exclude uniform stores
5487     // here as they demand the last lane, not the first one.
5488     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5489       assert(WideningDecision == CM_Scalarize);
5490       return true;
5491     }
5492 
5493     return (WideningDecision == CM_Widen ||
5494             WideningDecision == CM_Widen_Reverse ||
5495             WideningDecision == CM_Interleave);
5496   };
5497 
5498 
5499   // Returns true if Ptr is the pointer operand of a memory access instruction
5500   // I, and I is known to not require scalarization.
5501   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5502     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5503   };
5504 
5505   // Holds a list of values which are known to have at least one uniform use.
5506   // Note that there may be other uses which aren't uniform.  A "uniform use"
5507   // here is something which only demands lane 0 of the unrolled iterations;
5508   // it does not imply that all lanes produce the same value (e.g. this is not
5509   // the usual meaning of uniform)
5510   SetVector<Value *> HasUniformUse;
5511 
5512   // Scan the loop for instructions which are either a) known to have only
5513   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5514   for (auto *BB : TheLoop->blocks())
5515     for (auto &I : *BB) {
5516       // If there's no pointer operand, there's nothing to do.
5517       auto *Ptr = getLoadStorePointerOperand(&I);
5518       if (!Ptr)
5519         continue;
5520 
5521       // A uniform memory op is itself uniform.  We exclude uniform stores
5522       // here as they demand the last lane, not the first one.
5523       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5524         addToWorklistIfAllowed(&I);
5525 
5526       if (isUniformDecision(&I, VF)) {
5527         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5528         HasUniformUse.insert(Ptr);
5529       }
5530     }
5531 
5532   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5533   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5534   // disallows uses outside the loop as well.
5535   for (auto *V : HasUniformUse) {
5536     if (isOutOfScope(V))
5537       continue;
5538     auto *I = cast<Instruction>(V);
5539     auto UsersAreMemAccesses =
5540       llvm::all_of(I->users(), [&](User *U) -> bool {
5541         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5542       });
5543     if (UsersAreMemAccesses)
5544       addToWorklistIfAllowed(I);
5545   }
5546 
5547   // Expand Worklist in topological order: whenever a new instruction
5548   // is added , its users should be already inside Worklist.  It ensures
5549   // a uniform instruction will only be used by uniform instructions.
5550   unsigned idx = 0;
5551   while (idx != Worklist.size()) {
5552     Instruction *I = Worklist[idx++];
5553 
5554     for (auto OV : I->operand_values()) {
5555       // isOutOfScope operands cannot be uniform instructions.
5556       if (isOutOfScope(OV))
5557         continue;
5558       // First order recurrence Phi's should typically be considered
5559       // non-uniform.
5560       auto *OP = dyn_cast<PHINode>(OV);
5561       if (OP && Legal->isFirstOrderRecurrence(OP))
5562         continue;
5563       // If all the users of the operand are uniform, then add the
5564       // operand into the uniform worklist.
5565       auto *OI = cast<Instruction>(OV);
5566       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5567             auto *J = cast<Instruction>(U);
5568             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5569           }))
5570         addToWorklistIfAllowed(OI);
5571     }
5572   }
5573 
5574   // For an instruction to be added into Worklist above, all its users inside
5575   // the loop should also be in Worklist. However, this condition cannot be
5576   // true for phi nodes that form a cyclic dependence. We must process phi
5577   // nodes separately. An induction variable will remain uniform if all users
5578   // of the induction variable and induction variable update remain uniform.
5579   // The code below handles both pointer and non-pointer induction variables.
5580   for (auto &Induction : Legal->getInductionVars()) {
5581     auto *Ind = Induction.first;
5582     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5583 
5584     // Determine if all users of the induction variable are uniform after
5585     // vectorization.
5586     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5587       auto *I = cast<Instruction>(U);
5588       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5589              isVectorizedMemAccessUse(I, Ind);
5590     });
5591     if (!UniformInd)
5592       continue;
5593 
5594     // Determine if all users of the induction variable update instruction are
5595     // uniform after vectorization.
5596     auto UniformIndUpdate =
5597         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5598           auto *I = cast<Instruction>(U);
5599           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5600                  isVectorizedMemAccessUse(I, IndUpdate);
5601         });
5602     if (!UniformIndUpdate)
5603       continue;
5604 
5605     // The induction variable and its update instruction will remain uniform.
5606     addToWorklistIfAllowed(Ind);
5607     addToWorklistIfAllowed(IndUpdate);
5608   }
5609 
5610   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5611 }
5612 
5613 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5614   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5615 
5616   if (Legal->getRuntimePointerChecking()->Need) {
5617     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5618         "runtime pointer checks needed. Enable vectorization of this "
5619         "loop with '#pragma clang loop vectorize(enable)' when "
5620         "compiling with -Os/-Oz",
5621         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5622     return true;
5623   }
5624 
5625   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5626     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5627         "runtime SCEV checks needed. Enable vectorization of this "
5628         "loop with '#pragma clang loop vectorize(enable)' when "
5629         "compiling with -Os/-Oz",
5630         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5631     return true;
5632   }
5633 
5634   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5635   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5636     reportVectorizationFailure("Runtime stride check for small trip count",
5637         "runtime stride == 1 checks needed. Enable vectorization of "
5638         "this loop without such check by compiling with -Os/-Oz",
5639         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5640     return true;
5641   }
5642 
5643   return false;
5644 }
5645 
5646 ElementCount
5647 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5648   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5649     reportVectorizationInfo(
5650         "Disabling scalable vectorization, because target does not "
5651         "support scalable vectors.",
5652         "ScalableVectorsUnsupported", ORE, TheLoop);
5653     return ElementCount::getScalable(0);
5654   }
5655 
5656   if (Hints->isScalableVectorizationDisabled()) {
5657     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5658                             "ScalableVectorizationDisabled", ORE, TheLoop);
5659     return ElementCount::getScalable(0);
5660   }
5661 
5662   auto MaxScalableVF = ElementCount::getScalable(
5663       std::numeric_limits<ElementCount::ScalarTy>::max());
5664 
5665   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5666   // FIXME: While for scalable vectors this is currently sufficient, this should
5667   // be replaced by a more detailed mechanism that filters out specific VFs,
5668   // instead of invalidating vectorization for a whole set of VFs based on the
5669   // MaxVF.
5670 
5671   // Disable scalable vectorization if the loop contains unsupported reductions.
5672   if (!canVectorizeReductions(MaxScalableVF)) {
5673     reportVectorizationInfo(
5674         "Scalable vectorization not supported for the reduction "
5675         "operations found in this loop.",
5676         "ScalableVFUnfeasible", ORE, TheLoop);
5677     return ElementCount::getScalable(0);
5678   }
5679 
5680   // Disable scalable vectorization if the loop contains any instructions
5681   // with element types not supported for scalable vectors.
5682   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5683         return !Ty->isVoidTy() &&
5684                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5685       })) {
5686     reportVectorizationInfo("Scalable vectorization is not supported "
5687                             "for all element types found in this loop.",
5688                             "ScalableVFUnfeasible", ORE, TheLoop);
5689     return ElementCount::getScalable(0);
5690   }
5691 
5692   if (Legal->isSafeForAnyVectorWidth())
5693     return MaxScalableVF;
5694 
5695   // Limit MaxScalableVF by the maximum safe dependence distance.
5696   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5697   MaxScalableVF = ElementCount::getScalable(
5698       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5699   if (!MaxScalableVF)
5700     reportVectorizationInfo(
5701         "Max legal vector width too small, scalable vectorization "
5702         "unfeasible.",
5703         "ScalableVFUnfeasible", ORE, TheLoop);
5704 
5705   return MaxScalableVF;
5706 }
5707 
5708 FixedScalableVFPair
5709 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5710                                                  ElementCount UserVF) {
5711   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5712   unsigned SmallestType, WidestType;
5713   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5714 
5715   // Get the maximum safe dependence distance in bits computed by LAA.
5716   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5717   // the memory accesses that is most restrictive (involved in the smallest
5718   // dependence distance).
5719   unsigned MaxSafeElements =
5720       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5721 
5722   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5723   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5724 
5725   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5726                     << ".\n");
5727   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5728                     << ".\n");
5729 
5730   // First analyze the UserVF, fall back if the UserVF should be ignored.
5731   if (UserVF) {
5732     auto MaxSafeUserVF =
5733         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5734 
5735     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
5736       // If `VF=vscale x N` is safe, then so is `VF=N`
5737       if (UserVF.isScalable())
5738         return FixedScalableVFPair(
5739             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
5740       else
5741         return UserVF;
5742     }
5743 
5744     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5745 
5746     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5747     // is better to ignore the hint and let the compiler choose a suitable VF.
5748     if (!UserVF.isScalable()) {
5749       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5750                         << " is unsafe, clamping to max safe VF="
5751                         << MaxSafeFixedVF << ".\n");
5752       ORE->emit([&]() {
5753         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5754                                           TheLoop->getStartLoc(),
5755                                           TheLoop->getHeader())
5756                << "User-specified vectorization factor "
5757                << ore::NV("UserVectorizationFactor", UserVF)
5758                << " is unsafe, clamping to maximum safe vectorization factor "
5759                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5760       });
5761       return MaxSafeFixedVF;
5762     }
5763 
5764     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5765                       << " is unsafe. Ignoring scalable UserVF.\n");
5766     ORE->emit([&]() {
5767       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5768                                         TheLoop->getStartLoc(),
5769                                         TheLoop->getHeader())
5770              << "User-specified vectorization factor "
5771              << ore::NV("UserVectorizationFactor", UserVF)
5772              << " is unsafe. Ignoring the hint to let the compiler pick a "
5773                 "suitable VF.";
5774     });
5775   }
5776 
5777   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5778                     << " / " << WidestType << " bits.\n");
5779 
5780   FixedScalableVFPair Result(ElementCount::getFixed(1),
5781                              ElementCount::getScalable(0));
5782   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5783                                            WidestType, MaxSafeFixedVF))
5784     Result.FixedVF = MaxVF;
5785 
5786   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5787                                            WidestType, MaxSafeScalableVF))
5788     if (MaxVF.isScalable()) {
5789       Result.ScalableVF = MaxVF;
5790       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5791                         << "\n");
5792     }
5793 
5794   return Result;
5795 }
5796 
5797 FixedScalableVFPair
5798 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5799   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5800     // TODO: It may by useful to do since it's still likely to be dynamically
5801     // uniform if the target can skip.
5802     reportVectorizationFailure(
5803         "Not inserting runtime ptr check for divergent target",
5804         "runtime pointer checks needed. Not enabled for divergent target",
5805         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5806     return FixedScalableVFPair::getNone();
5807   }
5808 
5809   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5810   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5811   if (TC == 1) {
5812     reportVectorizationFailure("Single iteration (non) loop",
5813         "loop trip count is one, irrelevant for vectorization",
5814         "SingleIterationLoop", ORE, TheLoop);
5815     return FixedScalableVFPair::getNone();
5816   }
5817 
5818   switch (ScalarEpilogueStatus) {
5819   case CM_ScalarEpilogueAllowed:
5820     return computeFeasibleMaxVF(TC, UserVF);
5821   case CM_ScalarEpilogueNotAllowedUsePredicate:
5822     LLVM_FALLTHROUGH;
5823   case CM_ScalarEpilogueNotNeededUsePredicate:
5824     LLVM_DEBUG(
5825         dbgs() << "LV: vector predicate hint/switch found.\n"
5826                << "LV: Not allowing scalar epilogue, creating predicated "
5827                << "vector loop.\n");
5828     break;
5829   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5830     // fallthrough as a special case of OptForSize
5831   case CM_ScalarEpilogueNotAllowedOptSize:
5832     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5833       LLVM_DEBUG(
5834           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5835     else
5836       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5837                         << "count.\n");
5838 
5839     // Bail if runtime checks are required, which are not good when optimising
5840     // for size.
5841     if (runtimeChecksRequired())
5842       return FixedScalableVFPair::getNone();
5843 
5844     break;
5845   }
5846 
5847   // The only loops we can vectorize without a scalar epilogue, are loops with
5848   // a bottom-test and a single exiting block. We'd have to handle the fact
5849   // that not every instruction executes on the last iteration.  This will
5850   // require a lane mask which varies through the vector loop body.  (TODO)
5851   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5852     // If there was a tail-folding hint/switch, but we can't fold the tail by
5853     // masking, fallback to a vectorization with a scalar epilogue.
5854     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5855       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5856                            "scalar epilogue instead.\n");
5857       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5858       return computeFeasibleMaxVF(TC, UserVF);
5859     }
5860     return FixedScalableVFPair::getNone();
5861   }
5862 
5863   // Now try the tail folding
5864 
5865   // Invalidate interleave groups that require an epilogue if we can't mask
5866   // the interleave-group.
5867   if (!useMaskedInterleavedAccesses(TTI)) {
5868     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5869            "No decisions should have been taken at this point");
5870     // Note: There is no need to invalidate any cost modeling decisions here, as
5871     // non where taken so far.
5872     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5873   }
5874 
5875   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5876   // Avoid tail folding if the trip count is known to be a multiple of any VF
5877   // we chose.
5878   // FIXME: The condition below pessimises the case for fixed-width vectors,
5879   // when scalable VFs are also candidates for vectorization.
5880   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5881     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5882     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5883            "MaxFixedVF must be a power of 2");
5884     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5885                                    : MaxFixedVF.getFixedValue();
5886     ScalarEvolution *SE = PSE.getSE();
5887     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5888     const SCEV *ExitCount = SE->getAddExpr(
5889         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5890     const SCEV *Rem = SE->getURemExpr(
5891         SE->applyLoopGuards(ExitCount, TheLoop),
5892         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5893     if (Rem->isZero()) {
5894       // Accept MaxFixedVF if we do not have a tail.
5895       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5896       return MaxFactors;
5897     }
5898   }
5899 
5900   // If we don't know the precise trip count, or if the trip count that we
5901   // found modulo the vectorization factor is not zero, try to fold the tail
5902   // by masking.
5903   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5904   if (Legal->prepareToFoldTailByMasking()) {
5905     FoldTailByMasking = true;
5906     return MaxFactors;
5907   }
5908 
5909   // If there was a tail-folding hint/switch, but we can't fold the tail by
5910   // masking, fallback to a vectorization with a scalar epilogue.
5911   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5912     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5913                          "scalar epilogue instead.\n");
5914     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5915     return MaxFactors;
5916   }
5917 
5918   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5919     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5920     return FixedScalableVFPair::getNone();
5921   }
5922 
5923   if (TC == 0) {
5924     reportVectorizationFailure(
5925         "Unable to calculate the loop count due to complex control flow",
5926         "unable to calculate the loop count due to complex control flow",
5927         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5928     return FixedScalableVFPair::getNone();
5929   }
5930 
5931   reportVectorizationFailure(
5932       "Cannot optimize for size and vectorize at the same time.",
5933       "cannot optimize for size and vectorize at the same time. "
5934       "Enable vectorization of this loop with '#pragma clang loop "
5935       "vectorize(enable)' when compiling with -Os/-Oz",
5936       "NoTailLoopWithOptForSize", ORE, TheLoop);
5937   return FixedScalableVFPair::getNone();
5938 }
5939 
5940 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5941     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5942     const ElementCount &MaxSafeVF) {
5943   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5944   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5945       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5946                            : TargetTransformInfo::RGK_FixedWidthVector);
5947 
5948   // Convenience function to return the minimum of two ElementCounts.
5949   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5950     assert((LHS.isScalable() == RHS.isScalable()) &&
5951            "Scalable flags must match");
5952     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5953   };
5954 
5955   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5956   // Note that both WidestRegister and WidestType may not be a powers of 2.
5957   auto MaxVectorElementCount = ElementCount::get(
5958       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5959       ComputeScalableMaxVF);
5960   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5961   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5962                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5963 
5964   if (!MaxVectorElementCount) {
5965     LLVM_DEBUG(dbgs() << "LV: The target has no "
5966                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5967                       << " vector registers.\n");
5968     return ElementCount::getFixed(1);
5969   }
5970 
5971   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5972   if (ConstTripCount &&
5973       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5974       isPowerOf2_32(ConstTripCount)) {
5975     // We need to clamp the VF to be the ConstTripCount. There is no point in
5976     // choosing a higher viable VF as done in the loop below. If
5977     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5978     // the TC is less than or equal to the known number of lanes.
5979     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5980                       << ConstTripCount << "\n");
5981     return TripCountEC;
5982   }
5983 
5984   ElementCount MaxVF = MaxVectorElementCount;
5985   if (TTI.shouldMaximizeVectorBandwidth() ||
5986       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5987     auto MaxVectorElementCountMaxBW = ElementCount::get(
5988         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5989         ComputeScalableMaxVF);
5990     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5991 
5992     // Collect all viable vectorization factors larger than the default MaxVF
5993     // (i.e. MaxVectorElementCount).
5994     SmallVector<ElementCount, 8> VFs;
5995     for (ElementCount VS = MaxVectorElementCount * 2;
5996          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5997       VFs.push_back(VS);
5998 
5999     // For each VF calculate its register usage.
6000     auto RUs = calculateRegisterUsage(VFs);
6001 
6002     // Select the largest VF which doesn't require more registers than existing
6003     // ones.
6004     for (int i = RUs.size() - 1; i >= 0; --i) {
6005       bool Selected = true;
6006       for (auto &pair : RUs[i].MaxLocalUsers) {
6007         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6008         if (pair.second > TargetNumRegisters)
6009           Selected = false;
6010       }
6011       if (Selected) {
6012         MaxVF = VFs[i];
6013         break;
6014       }
6015     }
6016     if (ElementCount MinVF =
6017             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
6018       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
6019         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
6020                           << ") with target's minimum: " << MinVF << '\n');
6021         MaxVF = MinVF;
6022       }
6023     }
6024   }
6025   return MaxVF;
6026 }
6027 
6028 bool LoopVectorizationCostModel::isMoreProfitable(
6029     const VectorizationFactor &A, const VectorizationFactor &B) const {
6030   InstructionCost CostA = A.Cost;
6031   InstructionCost CostB = B.Cost;
6032 
6033   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
6034 
6035   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
6036       MaxTripCount) {
6037     // If we are folding the tail and the trip count is a known (possibly small)
6038     // constant, the trip count will be rounded up to an integer number of
6039     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
6040     // which we compare directly. When not folding the tail, the total cost will
6041     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
6042     // approximated with the per-lane cost below instead of using the tripcount
6043     // as here.
6044     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
6045     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
6046     return RTCostA < RTCostB;
6047   }
6048 
6049   // When set to preferred, for now assume vscale may be larger than 1, so
6050   // that scalable vectorization is slightly favorable over fixed-width
6051   // vectorization.
6052   if (Hints->isScalableVectorizationPreferred())
6053     if (A.Width.isScalable() && !B.Width.isScalable())
6054       return (CostA * B.Width.getKnownMinValue()) <=
6055              (CostB * A.Width.getKnownMinValue());
6056 
6057   // To avoid the need for FP division:
6058   //      (CostA / A.Width) < (CostB / B.Width)
6059   // <=>  (CostA * B.Width) < (CostB * A.Width)
6060   return (CostA * B.Width.getKnownMinValue()) <
6061          (CostB * A.Width.getKnownMinValue());
6062 }
6063 
6064 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
6065     const ElementCountSet &VFCandidates) {
6066   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
6067   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
6068   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
6069   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
6070          "Expected Scalar VF to be a candidate");
6071 
6072   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
6073   VectorizationFactor ChosenFactor = ScalarCost;
6074 
6075   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6076   if (ForceVectorization && VFCandidates.size() > 1) {
6077     // Ignore scalar width, because the user explicitly wants vectorization.
6078     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6079     // evaluation.
6080     ChosenFactor.Cost = InstructionCost::getMax();
6081   }
6082 
6083   SmallVector<InstructionVFPair> InvalidCosts;
6084   for (const auto &i : VFCandidates) {
6085     // The cost for scalar VF=1 is already calculated, so ignore it.
6086     if (i.isScalar())
6087       continue;
6088 
6089     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
6090     VectorizationFactor Candidate(i, C.first);
6091     LLVM_DEBUG(
6092         dbgs() << "LV: Vector loop of width " << i << " costs: "
6093                << (Candidate.Cost / Candidate.Width.getKnownMinValue())
6094                << (i.isScalable() ? " (assuming a minimum vscale of 1)" : "")
6095                << ".\n");
6096 
6097     if (!C.second && !ForceVectorization) {
6098       LLVM_DEBUG(
6099           dbgs() << "LV: Not considering vector loop of width " << i
6100                  << " because it will not generate any vector instructions.\n");
6101       continue;
6102     }
6103 
6104     // If profitable add it to ProfitableVF list.
6105     if (isMoreProfitable(Candidate, ScalarCost))
6106       ProfitableVFs.push_back(Candidate);
6107 
6108     if (isMoreProfitable(Candidate, ChosenFactor))
6109       ChosenFactor = Candidate;
6110   }
6111 
6112   // Emit a report of VFs with invalid costs in the loop.
6113   if (!InvalidCosts.empty()) {
6114     // Group the remarks per instruction, keeping the instruction order from
6115     // InvalidCosts.
6116     std::map<Instruction *, unsigned> Numbering;
6117     unsigned I = 0;
6118     for (auto &Pair : InvalidCosts)
6119       if (!Numbering.count(Pair.first))
6120         Numbering[Pair.first] = I++;
6121 
6122     // Sort the list, first on instruction(number) then on VF.
6123     llvm::sort(InvalidCosts,
6124                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
6125                  if (Numbering[A.first] != Numbering[B.first])
6126                    return Numbering[A.first] < Numbering[B.first];
6127                  ElementCountComparator ECC;
6128                  return ECC(A.second, B.second);
6129                });
6130 
6131     // For a list of ordered instruction-vf pairs:
6132     //   [(load, vf1), (load, vf2), (store, vf1)]
6133     // Group the instructions together to emit separate remarks for:
6134     //   load  (vf1, vf2)
6135     //   store (vf1)
6136     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
6137     auto Subset = ArrayRef<InstructionVFPair>();
6138     do {
6139       if (Subset.empty())
6140         Subset = Tail.take_front(1);
6141 
6142       Instruction *I = Subset.front().first;
6143 
6144       // If the next instruction is different, or if there are no other pairs,
6145       // emit a remark for the collated subset. e.g.
6146       //   [(load, vf1), (load, vf2))]
6147       // to emit:
6148       //  remark: invalid costs for 'load' at VF=(vf, vf2)
6149       if (Subset == Tail || Tail[Subset.size()].first != I) {
6150         std::string OutString;
6151         raw_string_ostream OS(OutString);
6152         assert(!Subset.empty() && "Unexpected empty range");
6153         OS << "Instruction with invalid costs prevented vectorization at VF=(";
6154         for (auto &Pair : Subset)
6155           OS << (Pair.second == Subset.front().second ? "" : ", ")
6156              << Pair.second;
6157         OS << "):";
6158         if (auto *CI = dyn_cast<CallInst>(I))
6159           OS << " call to " << CI->getCalledFunction()->getName();
6160         else
6161           OS << " " << I->getOpcodeName();
6162         OS.flush();
6163         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
6164         Tail = Tail.drop_front(Subset.size());
6165         Subset = {};
6166       } else
6167         // Grow the subset by one element
6168         Subset = Tail.take_front(Subset.size() + 1);
6169     } while (!Tail.empty());
6170   }
6171 
6172   if (!EnableCondStoresVectorization && NumPredStores) {
6173     reportVectorizationFailure("There are conditional stores.",
6174         "store that is conditionally executed prevents vectorization",
6175         "ConditionalStore", ORE, TheLoop);
6176     ChosenFactor = ScalarCost;
6177   }
6178 
6179   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6180                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
6181              << "LV: Vectorization seems to be not beneficial, "
6182              << "but was forced by a user.\n");
6183   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6184   return ChosenFactor;
6185 }
6186 
6187 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6188     const Loop &L, ElementCount VF) const {
6189   // Cross iteration phis such as reductions need special handling and are
6190   // currently unsupported.
6191   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6192         return Legal->isFirstOrderRecurrence(&Phi) ||
6193                Legal->isReductionVariable(&Phi);
6194       }))
6195     return false;
6196 
6197   // Phis with uses outside of the loop require special handling and are
6198   // currently unsupported.
6199   for (auto &Entry : Legal->getInductionVars()) {
6200     // Look for uses of the value of the induction at the last iteration.
6201     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6202     for (User *U : PostInc->users())
6203       if (!L.contains(cast<Instruction>(U)))
6204         return false;
6205     // Look for uses of penultimate value of the induction.
6206     for (User *U : Entry.first->users())
6207       if (!L.contains(cast<Instruction>(U)))
6208         return false;
6209   }
6210 
6211   // Induction variables that are widened require special handling that is
6212   // currently not supported.
6213   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6214         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6215                  this->isProfitableToScalarize(Entry.first, VF));
6216       }))
6217     return false;
6218 
6219   // Epilogue vectorization code has not been auditted to ensure it handles
6220   // non-latch exits properly.  It may be fine, but it needs auditted and
6221   // tested.
6222   if (L.getExitingBlock() != L.getLoopLatch())
6223     return false;
6224 
6225   return true;
6226 }
6227 
6228 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6229     const ElementCount VF) const {
6230   // FIXME: We need a much better cost-model to take different parameters such
6231   // as register pressure, code size increase and cost of extra branches into
6232   // account. For now we apply a very crude heuristic and only consider loops
6233   // with vectorization factors larger than a certain value.
6234   // We also consider epilogue vectorization unprofitable for targets that don't
6235   // consider interleaving beneficial (eg. MVE).
6236   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6237     return false;
6238   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6239     return true;
6240   return false;
6241 }
6242 
6243 VectorizationFactor
6244 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6245     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6246   VectorizationFactor Result = VectorizationFactor::Disabled();
6247   if (!EnableEpilogueVectorization) {
6248     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6249     return Result;
6250   }
6251 
6252   if (!isScalarEpilogueAllowed()) {
6253     LLVM_DEBUG(
6254         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6255                   "allowed.\n";);
6256     return Result;
6257   }
6258 
6259   // FIXME: This can be fixed for scalable vectors later, because at this stage
6260   // the LoopVectorizer will only consider vectorizing a loop with scalable
6261   // vectors when the loop has a hint to enable vectorization for a given VF.
6262   if (MainLoopVF.isScalable()) {
6263     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6264                          "yet supported.\n");
6265     return Result;
6266   }
6267 
6268   // Not really a cost consideration, but check for unsupported cases here to
6269   // simplify the logic.
6270   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6271     LLVM_DEBUG(
6272         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6273                   "not a supported candidate.\n";);
6274     return Result;
6275   }
6276 
6277   if (EpilogueVectorizationForceVF > 1) {
6278     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6279     if (LVP.hasPlanWithVFs(
6280             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
6281       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
6282     else {
6283       LLVM_DEBUG(
6284           dbgs()
6285               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6286       return Result;
6287     }
6288   }
6289 
6290   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6291       TheLoop->getHeader()->getParent()->hasMinSize()) {
6292     LLVM_DEBUG(
6293         dbgs()
6294             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6295     return Result;
6296   }
6297 
6298   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6299     return Result;
6300 
6301   for (auto &NextVF : ProfitableVFs)
6302     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6303         (Result.Width.getFixedValue() == 1 ||
6304          isMoreProfitable(NextVF, Result)) &&
6305         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6306       Result = NextVF;
6307 
6308   if (Result != VectorizationFactor::Disabled())
6309     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6310                       << Result.Width.getFixedValue() << "\n";);
6311   return Result;
6312 }
6313 
6314 std::pair<unsigned, unsigned>
6315 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6316   unsigned MinWidth = -1U;
6317   unsigned MaxWidth = 8;
6318   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6319   for (Type *T : ElementTypesInLoop) {
6320     MinWidth = std::min<unsigned>(
6321         MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6322     MaxWidth = std::max<unsigned>(
6323         MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6324   }
6325   return {MinWidth, MaxWidth};
6326 }
6327 
6328 void LoopVectorizationCostModel::collectElementTypesForWidening() {
6329   ElementTypesInLoop.clear();
6330   // For each block.
6331   for (BasicBlock *BB : TheLoop->blocks()) {
6332     // For each instruction in the loop.
6333     for (Instruction &I : BB->instructionsWithoutDebug()) {
6334       Type *T = I.getType();
6335 
6336       // Skip ignored values.
6337       if (ValuesToIgnore.count(&I))
6338         continue;
6339 
6340       // Only examine Loads, Stores and PHINodes.
6341       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6342         continue;
6343 
6344       // Examine PHI nodes that are reduction variables. Update the type to
6345       // account for the recurrence type.
6346       if (auto *PN = dyn_cast<PHINode>(&I)) {
6347         if (!Legal->isReductionVariable(PN))
6348           continue;
6349         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6350         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6351             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6352                                       RdxDesc.getRecurrenceType(),
6353                                       TargetTransformInfo::ReductionFlags()))
6354           continue;
6355         T = RdxDesc.getRecurrenceType();
6356       }
6357 
6358       // Examine the stored values.
6359       if (auto *ST = dyn_cast<StoreInst>(&I))
6360         T = ST->getValueOperand()->getType();
6361 
6362       // Ignore loaded pointer types and stored pointer types that are not
6363       // vectorizable.
6364       //
6365       // FIXME: The check here attempts to predict whether a load or store will
6366       //        be vectorized. We only know this for certain after a VF has
6367       //        been selected. Here, we assume that if an access can be
6368       //        vectorized, it will be. We should also look at extending this
6369       //        optimization to non-pointer types.
6370       //
6371       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6372           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6373         continue;
6374 
6375       ElementTypesInLoop.insert(T);
6376     }
6377   }
6378 }
6379 
6380 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6381                                                            unsigned LoopCost) {
6382   // -- The interleave heuristics --
6383   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6384   // There are many micro-architectural considerations that we can't predict
6385   // at this level. For example, frontend pressure (on decode or fetch) due to
6386   // code size, or the number and capabilities of the execution ports.
6387   //
6388   // We use the following heuristics to select the interleave count:
6389   // 1. If the code has reductions, then we interleave to break the cross
6390   // iteration dependency.
6391   // 2. If the loop is really small, then we interleave to reduce the loop
6392   // overhead.
6393   // 3. We don't interleave if we think that we will spill registers to memory
6394   // due to the increased register pressure.
6395 
6396   if (!isScalarEpilogueAllowed())
6397     return 1;
6398 
6399   // We used the distance for the interleave count.
6400   if (Legal->getMaxSafeDepDistBytes() != -1U)
6401     return 1;
6402 
6403   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6404   const bool HasReductions = !Legal->getReductionVars().empty();
6405   // Do not interleave loops with a relatively small known or estimated trip
6406   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6407   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6408   // because with the above conditions interleaving can expose ILP and break
6409   // cross iteration dependences for reductions.
6410   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6411       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6412     return 1;
6413 
6414   RegisterUsage R = calculateRegisterUsage({VF})[0];
6415   // We divide by these constants so assume that we have at least one
6416   // instruction that uses at least one register.
6417   for (auto& pair : R.MaxLocalUsers) {
6418     pair.second = std::max(pair.second, 1U);
6419   }
6420 
6421   // We calculate the interleave count using the following formula.
6422   // Subtract the number of loop invariants from the number of available
6423   // registers. These registers are used by all of the interleaved instances.
6424   // Next, divide the remaining registers by the number of registers that is
6425   // required by the loop, in order to estimate how many parallel instances
6426   // fit without causing spills. All of this is rounded down if necessary to be
6427   // a power of two. We want power of two interleave count to simplify any
6428   // addressing operations or alignment considerations.
6429   // We also want power of two interleave counts to ensure that the induction
6430   // variable of the vector loop wraps to zero, when tail is folded by masking;
6431   // this currently happens when OptForSize, in which case IC is set to 1 above.
6432   unsigned IC = UINT_MAX;
6433 
6434   for (auto& pair : R.MaxLocalUsers) {
6435     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6436     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6437                       << " registers of "
6438                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6439     if (VF.isScalar()) {
6440       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6441         TargetNumRegisters = ForceTargetNumScalarRegs;
6442     } else {
6443       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6444         TargetNumRegisters = ForceTargetNumVectorRegs;
6445     }
6446     unsigned MaxLocalUsers = pair.second;
6447     unsigned LoopInvariantRegs = 0;
6448     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6449       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6450 
6451     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6452     // Don't count the induction variable as interleaved.
6453     if (EnableIndVarRegisterHeur) {
6454       TmpIC =
6455           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6456                         std::max(1U, (MaxLocalUsers - 1)));
6457     }
6458 
6459     IC = std::min(IC, TmpIC);
6460   }
6461 
6462   // Clamp the interleave ranges to reasonable counts.
6463   unsigned MaxInterleaveCount =
6464       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6465 
6466   // Check if the user has overridden the max.
6467   if (VF.isScalar()) {
6468     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6469       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6470   } else {
6471     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6472       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6473   }
6474 
6475   // If trip count is known or estimated compile time constant, limit the
6476   // interleave count to be less than the trip count divided by VF, provided it
6477   // is at least 1.
6478   //
6479   // For scalable vectors we can't know if interleaving is beneficial. It may
6480   // not be beneficial for small loops if none of the lanes in the second vector
6481   // iterations is enabled. However, for larger loops, there is likely to be a
6482   // similar benefit as for fixed-width vectors. For now, we choose to leave
6483   // the InterleaveCount as if vscale is '1', although if some information about
6484   // the vector is known (e.g. min vector size), we can make a better decision.
6485   if (BestKnownTC) {
6486     MaxInterleaveCount =
6487         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6488     // Make sure MaxInterleaveCount is greater than 0.
6489     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6490   }
6491 
6492   assert(MaxInterleaveCount > 0 &&
6493          "Maximum interleave count must be greater than 0");
6494 
6495   // Clamp the calculated IC to be between the 1 and the max interleave count
6496   // that the target and trip count allows.
6497   if (IC > MaxInterleaveCount)
6498     IC = MaxInterleaveCount;
6499   else
6500     // Make sure IC is greater than 0.
6501     IC = std::max(1u, IC);
6502 
6503   assert(IC > 0 && "Interleave count must be greater than 0.");
6504 
6505   // If we did not calculate the cost for VF (because the user selected the VF)
6506   // then we calculate the cost of VF here.
6507   if (LoopCost == 0) {
6508     InstructionCost C = expectedCost(VF).first;
6509     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
6510     LoopCost = *C.getValue();
6511   }
6512 
6513   assert(LoopCost && "Non-zero loop cost expected");
6514 
6515   // Interleave if we vectorized this loop and there is a reduction that could
6516   // benefit from interleaving.
6517   if (VF.isVector() && HasReductions) {
6518     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6519     return IC;
6520   }
6521 
6522   // Note that if we've already vectorized the loop we will have done the
6523   // runtime check and so interleaving won't require further checks.
6524   bool InterleavingRequiresRuntimePointerCheck =
6525       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6526 
6527   // We want to interleave small loops in order to reduce the loop overhead and
6528   // potentially expose ILP opportunities.
6529   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6530                     << "LV: IC is " << IC << '\n'
6531                     << "LV: VF is " << VF << '\n');
6532   const bool AggressivelyInterleaveReductions =
6533       TTI.enableAggressiveInterleaving(HasReductions);
6534   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6535     // We assume that the cost overhead is 1 and we use the cost model
6536     // to estimate the cost of the loop and interleave until the cost of the
6537     // loop overhead is about 5% of the cost of the loop.
6538     unsigned SmallIC =
6539         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6540 
6541     // Interleave until store/load ports (estimated by max interleave count) are
6542     // saturated.
6543     unsigned NumStores = Legal->getNumStores();
6544     unsigned NumLoads = Legal->getNumLoads();
6545     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6546     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6547 
6548     // If we have a scalar reduction (vector reductions are already dealt with
6549     // by this point), we can increase the critical path length if the loop
6550     // we're interleaving is inside another loop. Limit, by default to 2, so the
6551     // critical path only gets increased by one reduction operation.
6552     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6553       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6554       SmallIC = std::min(SmallIC, F);
6555       StoresIC = std::min(StoresIC, F);
6556       LoadsIC = std::min(LoadsIC, F);
6557     }
6558 
6559     if (EnableLoadStoreRuntimeInterleave &&
6560         std::max(StoresIC, LoadsIC) > SmallIC) {
6561       LLVM_DEBUG(
6562           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6563       return std::max(StoresIC, LoadsIC);
6564     }
6565 
6566     // If there are scalar reductions and TTI has enabled aggressive
6567     // interleaving for reductions, we will interleave to expose ILP.
6568     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6569         AggressivelyInterleaveReductions) {
6570       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6571       // Interleave no less than SmallIC but not as aggressive as the normal IC
6572       // to satisfy the rare situation when resources are too limited.
6573       return std::max(IC / 2, SmallIC);
6574     } else {
6575       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6576       return SmallIC;
6577     }
6578   }
6579 
6580   // Interleave if this is a large loop (small loops are already dealt with by
6581   // this point) that could benefit from interleaving.
6582   if (AggressivelyInterleaveReductions) {
6583     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6584     return IC;
6585   }
6586 
6587   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6588   return 1;
6589 }
6590 
6591 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6592 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6593   // This function calculates the register usage by measuring the highest number
6594   // of values that are alive at a single location. Obviously, this is a very
6595   // rough estimation. We scan the loop in a topological order in order and
6596   // assign a number to each instruction. We use RPO to ensure that defs are
6597   // met before their users. We assume that each instruction that has in-loop
6598   // users starts an interval. We record every time that an in-loop value is
6599   // used, so we have a list of the first and last occurrences of each
6600   // instruction. Next, we transpose this data structure into a multi map that
6601   // holds the list of intervals that *end* at a specific location. This multi
6602   // map allows us to perform a linear search. We scan the instructions linearly
6603   // and record each time that a new interval starts, by placing it in a set.
6604   // If we find this value in the multi-map then we remove it from the set.
6605   // The max register usage is the maximum size of the set.
6606   // We also search for instructions that are defined outside the loop, but are
6607   // used inside the loop. We need this number separately from the max-interval
6608   // usage number because when we unroll, loop-invariant values do not take
6609   // more register.
6610   LoopBlocksDFS DFS(TheLoop);
6611   DFS.perform(LI);
6612 
6613   RegisterUsage RU;
6614 
6615   // Each 'key' in the map opens a new interval. The values
6616   // of the map are the index of the 'last seen' usage of the
6617   // instruction that is the key.
6618   using IntervalMap = DenseMap<Instruction *, unsigned>;
6619 
6620   // Maps instruction to its index.
6621   SmallVector<Instruction *, 64> IdxToInstr;
6622   // Marks the end of each interval.
6623   IntervalMap EndPoint;
6624   // Saves the list of instruction indices that are used in the loop.
6625   SmallPtrSet<Instruction *, 8> Ends;
6626   // Saves the list of values that are used in the loop but are
6627   // defined outside the loop, such as arguments and constants.
6628   SmallPtrSet<Value *, 8> LoopInvariants;
6629 
6630   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6631     for (Instruction &I : BB->instructionsWithoutDebug()) {
6632       IdxToInstr.push_back(&I);
6633 
6634       // Save the end location of each USE.
6635       for (Value *U : I.operands()) {
6636         auto *Instr = dyn_cast<Instruction>(U);
6637 
6638         // Ignore non-instruction values such as arguments, constants, etc.
6639         if (!Instr)
6640           continue;
6641 
6642         // If this instruction is outside the loop then record it and continue.
6643         if (!TheLoop->contains(Instr)) {
6644           LoopInvariants.insert(Instr);
6645           continue;
6646         }
6647 
6648         // Overwrite previous end points.
6649         EndPoint[Instr] = IdxToInstr.size();
6650         Ends.insert(Instr);
6651       }
6652     }
6653   }
6654 
6655   // Saves the list of intervals that end with the index in 'key'.
6656   using InstrList = SmallVector<Instruction *, 2>;
6657   DenseMap<unsigned, InstrList> TransposeEnds;
6658 
6659   // Transpose the EndPoints to a list of values that end at each index.
6660   for (auto &Interval : EndPoint)
6661     TransposeEnds[Interval.second].push_back(Interval.first);
6662 
6663   SmallPtrSet<Instruction *, 8> OpenIntervals;
6664   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6665   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6666 
6667   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6668 
6669   // A lambda that gets the register usage for the given type and VF.
6670   const auto &TTICapture = TTI;
6671   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6672     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6673       return 0;
6674     InstructionCost::CostType RegUsage =
6675         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6676     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6677            "Nonsensical values for register usage.");
6678     return RegUsage;
6679   };
6680 
6681   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6682     Instruction *I = IdxToInstr[i];
6683 
6684     // Remove all of the instructions that end at this location.
6685     InstrList &List = TransposeEnds[i];
6686     for (Instruction *ToRemove : List)
6687       OpenIntervals.erase(ToRemove);
6688 
6689     // Ignore instructions that are never used within the loop.
6690     if (!Ends.count(I))
6691       continue;
6692 
6693     // Skip ignored values.
6694     if (ValuesToIgnore.count(I))
6695       continue;
6696 
6697     // For each VF find the maximum usage of registers.
6698     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6699       // Count the number of live intervals.
6700       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6701 
6702       if (VFs[j].isScalar()) {
6703         for (auto Inst : OpenIntervals) {
6704           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6705           if (RegUsage.find(ClassID) == RegUsage.end())
6706             RegUsage[ClassID] = 1;
6707           else
6708             RegUsage[ClassID] += 1;
6709         }
6710       } else {
6711         collectUniformsAndScalars(VFs[j]);
6712         for (auto Inst : OpenIntervals) {
6713           // Skip ignored values for VF > 1.
6714           if (VecValuesToIgnore.count(Inst))
6715             continue;
6716           if (isScalarAfterVectorization(Inst, VFs[j])) {
6717             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6718             if (RegUsage.find(ClassID) == RegUsage.end())
6719               RegUsage[ClassID] = 1;
6720             else
6721               RegUsage[ClassID] += 1;
6722           } else {
6723             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6724             if (RegUsage.find(ClassID) == RegUsage.end())
6725               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6726             else
6727               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6728           }
6729         }
6730       }
6731 
6732       for (auto& pair : RegUsage) {
6733         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6734           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6735         else
6736           MaxUsages[j][pair.first] = pair.second;
6737       }
6738     }
6739 
6740     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6741                       << OpenIntervals.size() << '\n');
6742 
6743     // Add the current instruction to the list of open intervals.
6744     OpenIntervals.insert(I);
6745   }
6746 
6747   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6748     SmallMapVector<unsigned, unsigned, 4> Invariant;
6749 
6750     for (auto Inst : LoopInvariants) {
6751       unsigned Usage =
6752           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6753       unsigned ClassID =
6754           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6755       if (Invariant.find(ClassID) == Invariant.end())
6756         Invariant[ClassID] = Usage;
6757       else
6758         Invariant[ClassID] += Usage;
6759     }
6760 
6761     LLVM_DEBUG({
6762       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6763       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6764              << " item\n";
6765       for (const auto &pair : MaxUsages[i]) {
6766         dbgs() << "LV(REG): RegisterClass: "
6767                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6768                << " registers\n";
6769       }
6770       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6771              << " item\n";
6772       for (const auto &pair : Invariant) {
6773         dbgs() << "LV(REG): RegisterClass: "
6774                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6775                << " registers\n";
6776       }
6777     });
6778 
6779     RU.LoopInvariantRegs = Invariant;
6780     RU.MaxLocalUsers = MaxUsages[i];
6781     RUs[i] = RU;
6782   }
6783 
6784   return RUs;
6785 }
6786 
6787 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6788   // TODO: Cost model for emulated masked load/store is completely
6789   // broken. This hack guides the cost model to use an artificially
6790   // high enough value to practically disable vectorization with such
6791   // operations, except where previously deployed legality hack allowed
6792   // using very low cost values. This is to avoid regressions coming simply
6793   // from moving "masked load/store" check from legality to cost model.
6794   // Masked Load/Gather emulation was previously never allowed.
6795   // Limited number of Masked Store/Scatter emulation was allowed.
6796   assert(isPredicatedInst(I) &&
6797          "Expecting a scalar emulated instruction");
6798   return isa<LoadInst>(I) ||
6799          (isa<StoreInst>(I) &&
6800           NumPredStores > NumberOfStoresToPredicate);
6801 }
6802 
6803 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6804   // If we aren't vectorizing the loop, or if we've already collected the
6805   // instructions to scalarize, there's nothing to do. Collection may already
6806   // have occurred if we have a user-selected VF and are now computing the
6807   // expected cost for interleaving.
6808   if (VF.isScalar() || VF.isZero() ||
6809       InstsToScalarize.find(VF) != InstsToScalarize.end())
6810     return;
6811 
6812   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6813   // not profitable to scalarize any instructions, the presence of VF in the
6814   // map will indicate that we've analyzed it already.
6815   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6816 
6817   // Find all the instructions that are scalar with predication in the loop and
6818   // determine if it would be better to not if-convert the blocks they are in.
6819   // If so, we also record the instructions to scalarize.
6820   for (BasicBlock *BB : TheLoop->blocks()) {
6821     if (!blockNeedsPredication(BB))
6822       continue;
6823     for (Instruction &I : *BB)
6824       if (isScalarWithPredication(&I)) {
6825         ScalarCostsTy ScalarCosts;
6826         // Do not apply discount logic if hacked cost is needed
6827         // for emulated masked memrefs.
6828         if (!useEmulatedMaskMemRefHack(&I) &&
6829             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6830           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6831         // Remember that BB will remain after vectorization.
6832         PredicatedBBsAfterVectorization.insert(BB);
6833       }
6834   }
6835 }
6836 
6837 int LoopVectorizationCostModel::computePredInstDiscount(
6838     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6839   assert(!isUniformAfterVectorization(PredInst, VF) &&
6840          "Instruction marked uniform-after-vectorization will be predicated");
6841 
6842   // Initialize the discount to zero, meaning that the scalar version and the
6843   // vector version cost the same.
6844   InstructionCost Discount = 0;
6845 
6846   // Holds instructions to analyze. The instructions we visit are mapped in
6847   // ScalarCosts. Those instructions are the ones that would be scalarized if
6848   // we find that the scalar version costs less.
6849   SmallVector<Instruction *, 8> Worklist;
6850 
6851   // Returns true if the given instruction can be scalarized.
6852   auto canBeScalarized = [&](Instruction *I) -> bool {
6853     // We only attempt to scalarize instructions forming a single-use chain
6854     // from the original predicated block that would otherwise be vectorized.
6855     // Although not strictly necessary, we give up on instructions we know will
6856     // already be scalar to avoid traversing chains that are unlikely to be
6857     // beneficial.
6858     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6859         isScalarAfterVectorization(I, VF))
6860       return false;
6861 
6862     // If the instruction is scalar with predication, it will be analyzed
6863     // separately. We ignore it within the context of PredInst.
6864     if (isScalarWithPredication(I))
6865       return false;
6866 
6867     // If any of the instruction's operands are uniform after vectorization,
6868     // the instruction cannot be scalarized. This prevents, for example, a
6869     // masked load from being scalarized.
6870     //
6871     // We assume we will only emit a value for lane zero of an instruction
6872     // marked uniform after vectorization, rather than VF identical values.
6873     // Thus, if we scalarize an instruction that uses a uniform, we would
6874     // create uses of values corresponding to the lanes we aren't emitting code
6875     // for. This behavior can be changed by allowing getScalarValue to clone
6876     // the lane zero values for uniforms rather than asserting.
6877     for (Use &U : I->operands())
6878       if (auto *J = dyn_cast<Instruction>(U.get()))
6879         if (isUniformAfterVectorization(J, VF))
6880           return false;
6881 
6882     // Otherwise, we can scalarize the instruction.
6883     return true;
6884   };
6885 
6886   // Compute the expected cost discount from scalarizing the entire expression
6887   // feeding the predicated instruction. We currently only consider expressions
6888   // that are single-use instruction chains.
6889   Worklist.push_back(PredInst);
6890   while (!Worklist.empty()) {
6891     Instruction *I = Worklist.pop_back_val();
6892 
6893     // If we've already analyzed the instruction, there's nothing to do.
6894     if (ScalarCosts.find(I) != ScalarCosts.end())
6895       continue;
6896 
6897     // Compute the cost of the vector instruction. Note that this cost already
6898     // includes the scalarization overhead of the predicated instruction.
6899     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6900 
6901     // Compute the cost of the scalarized instruction. This cost is the cost of
6902     // the instruction as if it wasn't if-converted and instead remained in the
6903     // predicated block. We will scale this cost by block probability after
6904     // computing the scalarization overhead.
6905     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6906     InstructionCost ScalarCost =
6907         VF.getKnownMinValue() *
6908         getInstructionCost(I, ElementCount::getFixed(1)).first;
6909 
6910     // Compute the scalarization overhead of needed insertelement instructions
6911     // and phi nodes.
6912     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6913       ScalarCost += TTI.getScalarizationOverhead(
6914           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6915           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6916       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6917       ScalarCost +=
6918           VF.getKnownMinValue() *
6919           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6920     }
6921 
6922     // Compute the scalarization overhead of needed extractelement
6923     // instructions. For each of the instruction's operands, if the operand can
6924     // be scalarized, add it to the worklist; otherwise, account for the
6925     // overhead.
6926     for (Use &U : I->operands())
6927       if (auto *J = dyn_cast<Instruction>(U.get())) {
6928         assert(VectorType::isValidElementType(J->getType()) &&
6929                "Instruction has non-scalar type");
6930         if (canBeScalarized(J))
6931           Worklist.push_back(J);
6932         else if (needsExtract(J, VF)) {
6933           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6934           ScalarCost += TTI.getScalarizationOverhead(
6935               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6936               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6937         }
6938       }
6939 
6940     // Scale the total scalar cost by block probability.
6941     ScalarCost /= getReciprocalPredBlockProb();
6942 
6943     // Compute the discount. A non-negative discount means the vector version
6944     // of the instruction costs more, and scalarizing would be beneficial.
6945     Discount += VectorCost - ScalarCost;
6946     ScalarCosts[I] = ScalarCost;
6947   }
6948 
6949   return *Discount.getValue();
6950 }
6951 
6952 LoopVectorizationCostModel::VectorizationCostTy
6953 LoopVectorizationCostModel::expectedCost(
6954     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6955   VectorizationCostTy Cost;
6956 
6957   // For each block.
6958   for (BasicBlock *BB : TheLoop->blocks()) {
6959     VectorizationCostTy BlockCost;
6960 
6961     // For each instruction in the old loop.
6962     for (Instruction &I : BB->instructionsWithoutDebug()) {
6963       // Skip ignored values.
6964       if (ValuesToIgnore.count(&I) ||
6965           (VF.isVector() && VecValuesToIgnore.count(&I)))
6966         continue;
6967 
6968       VectorizationCostTy C = getInstructionCost(&I, VF);
6969 
6970       // Check if we should override the cost.
6971       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6972         C.first = InstructionCost(ForceTargetInstructionCost);
6973 
6974       // Keep a list of instructions with invalid costs.
6975       if (Invalid && !C.first.isValid())
6976         Invalid->emplace_back(&I, VF);
6977 
6978       BlockCost.first += C.first;
6979       BlockCost.second |= C.second;
6980       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6981                         << " for VF " << VF << " For instruction: " << I
6982                         << '\n');
6983     }
6984 
6985     // If we are vectorizing a predicated block, it will have been
6986     // if-converted. This means that the block's instructions (aside from
6987     // stores and instructions that may divide by zero) will now be
6988     // unconditionally executed. For the scalar case, we may not always execute
6989     // the predicated block, if it is an if-else block. Thus, scale the block's
6990     // cost by the probability of executing it. blockNeedsPredication from
6991     // Legal is used so as to not include all blocks in tail folded loops.
6992     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6993       BlockCost.first /= getReciprocalPredBlockProb();
6994 
6995     Cost.first += BlockCost.first;
6996     Cost.second |= BlockCost.second;
6997   }
6998 
6999   return Cost;
7000 }
7001 
7002 /// Gets Address Access SCEV after verifying that the access pattern
7003 /// is loop invariant except the induction variable dependence.
7004 ///
7005 /// This SCEV can be sent to the Target in order to estimate the address
7006 /// calculation cost.
7007 static const SCEV *getAddressAccessSCEV(
7008               Value *Ptr,
7009               LoopVectorizationLegality *Legal,
7010               PredicatedScalarEvolution &PSE,
7011               const Loop *TheLoop) {
7012 
7013   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
7014   if (!Gep)
7015     return nullptr;
7016 
7017   // We are looking for a gep with all loop invariant indices except for one
7018   // which should be an induction variable.
7019   auto SE = PSE.getSE();
7020   unsigned NumOperands = Gep->getNumOperands();
7021   for (unsigned i = 1; i < NumOperands; ++i) {
7022     Value *Opd = Gep->getOperand(i);
7023     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
7024         !Legal->isInductionVariable(Opd))
7025       return nullptr;
7026   }
7027 
7028   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
7029   return PSE.getSCEV(Ptr);
7030 }
7031 
7032 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
7033   return Legal->hasStride(I->getOperand(0)) ||
7034          Legal->hasStride(I->getOperand(1));
7035 }
7036 
7037 InstructionCost
7038 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
7039                                                         ElementCount VF) {
7040   assert(VF.isVector() &&
7041          "Scalarization cost of instruction implies vectorization.");
7042   if (VF.isScalable())
7043     return InstructionCost::getInvalid();
7044 
7045   Type *ValTy = getLoadStoreType(I);
7046   auto SE = PSE.getSE();
7047 
7048   unsigned AS = getLoadStoreAddressSpace(I);
7049   Value *Ptr = getLoadStorePointerOperand(I);
7050   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
7051 
7052   // Figure out whether the access is strided and get the stride value
7053   // if it's known in compile time
7054   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
7055 
7056   // Get the cost of the scalar memory instruction and address computation.
7057   InstructionCost Cost =
7058       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
7059 
7060   // Don't pass *I here, since it is scalar but will actually be part of a
7061   // vectorized loop where the user of it is a vectorized instruction.
7062   const Align Alignment = getLoadStoreAlignment(I);
7063   Cost += VF.getKnownMinValue() *
7064           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
7065                               AS, TTI::TCK_RecipThroughput);
7066 
7067   // Get the overhead of the extractelement and insertelement instructions
7068   // we might create due to scalarization.
7069   Cost += getScalarizationOverhead(I, VF);
7070 
7071   // If we have a predicated load/store, it will need extra i1 extracts and
7072   // conditional branches, but may not be executed for each vector lane. Scale
7073   // the cost by the probability of executing the predicated block.
7074   if (isPredicatedInst(I)) {
7075     Cost /= getReciprocalPredBlockProb();
7076 
7077     // Add the cost of an i1 extract and a branch
7078     auto *Vec_i1Ty =
7079         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
7080     Cost += TTI.getScalarizationOverhead(
7081         Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7082         /*Insert=*/false, /*Extract=*/true);
7083     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
7084 
7085     if (useEmulatedMaskMemRefHack(I))
7086       // Artificially setting to a high enough value to practically disable
7087       // vectorization with such operations.
7088       Cost = 3000000;
7089   }
7090 
7091   return Cost;
7092 }
7093 
7094 InstructionCost
7095 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7096                                                     ElementCount VF) {
7097   Type *ValTy = getLoadStoreType(I);
7098   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7099   Value *Ptr = getLoadStorePointerOperand(I);
7100   unsigned AS = getLoadStoreAddressSpace(I);
7101   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7102   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7103 
7104   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7105          "Stride should be 1 or -1 for consecutive memory access");
7106   const Align Alignment = getLoadStoreAlignment(I);
7107   InstructionCost Cost = 0;
7108   if (Legal->isMaskRequired(I))
7109     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7110                                       CostKind);
7111   else
7112     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7113                                 CostKind, I);
7114 
7115   bool Reverse = ConsecutiveStride < 0;
7116   if (Reverse)
7117     Cost +=
7118         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7119   return Cost;
7120 }
7121 
7122 InstructionCost
7123 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7124                                                 ElementCount VF) {
7125   assert(Legal->isUniformMemOp(*I));
7126 
7127   Type *ValTy = getLoadStoreType(I);
7128   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7129   const Align Alignment = getLoadStoreAlignment(I);
7130   unsigned AS = getLoadStoreAddressSpace(I);
7131   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7132   if (isa<LoadInst>(I)) {
7133     return TTI.getAddressComputationCost(ValTy) +
7134            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7135                                CostKind) +
7136            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7137   }
7138   StoreInst *SI = cast<StoreInst>(I);
7139 
7140   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7141   return TTI.getAddressComputationCost(ValTy) +
7142          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7143                              CostKind) +
7144          (isLoopInvariantStoreValue
7145               ? 0
7146               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7147                                        VF.getKnownMinValue() - 1));
7148 }
7149 
7150 InstructionCost
7151 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7152                                                  ElementCount VF) {
7153   Type *ValTy = getLoadStoreType(I);
7154   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7155   const Align Alignment = getLoadStoreAlignment(I);
7156   const Value *Ptr = getLoadStorePointerOperand(I);
7157 
7158   return TTI.getAddressComputationCost(VectorTy) +
7159          TTI.getGatherScatterOpCost(
7160              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7161              TargetTransformInfo::TCK_RecipThroughput, I);
7162 }
7163 
7164 InstructionCost
7165 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7166                                                    ElementCount VF) {
7167   // TODO: Once we have support for interleaving with scalable vectors
7168   // we can calculate the cost properly here.
7169   if (VF.isScalable())
7170     return InstructionCost::getInvalid();
7171 
7172   Type *ValTy = getLoadStoreType(I);
7173   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7174   unsigned AS = getLoadStoreAddressSpace(I);
7175 
7176   auto Group = getInterleavedAccessGroup(I);
7177   assert(Group && "Fail to get an interleaved access group.");
7178 
7179   unsigned InterleaveFactor = Group->getFactor();
7180   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7181 
7182   // Holds the indices of existing members in an interleaved load group.
7183   // An interleaved store group doesn't need this as it doesn't allow gaps.
7184   SmallVector<unsigned, 4> Indices;
7185   if (isa<LoadInst>(I)) {
7186     for (unsigned i = 0; i < InterleaveFactor; i++)
7187       if (Group->getMember(i))
7188         Indices.push_back(i);
7189   }
7190 
7191   // Calculate the cost of the whole interleaved group.
7192   bool UseMaskForGaps =
7193       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
7194   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7195       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7196       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7197 
7198   if (Group->isReverse()) {
7199     // TODO: Add support for reversed masked interleaved access.
7200     assert(!Legal->isMaskRequired(I) &&
7201            "Reverse masked interleaved access not supported.");
7202     Cost +=
7203         Group->getNumMembers() *
7204         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7205   }
7206   return Cost;
7207 }
7208 
7209 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
7210     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7211   // Early exit for no inloop reductions
7212   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7213     return InstructionCost::getInvalid();
7214   auto *VectorTy = cast<VectorType>(Ty);
7215 
7216   // We are looking for a pattern of, and finding the minimal acceptable cost:
7217   //  reduce(mul(ext(A), ext(B))) or
7218   //  reduce(mul(A, B)) or
7219   //  reduce(ext(A)) or
7220   //  reduce(A).
7221   // The basic idea is that we walk down the tree to do that, finding the root
7222   // reduction instruction in InLoopReductionImmediateChains. From there we find
7223   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7224   // of the components. If the reduction cost is lower then we return it for the
7225   // reduction instruction and 0 for the other instructions in the pattern. If
7226   // it is not we return an invalid cost specifying the orignal cost method
7227   // should be used.
7228   Instruction *RetI = I;
7229   if ((RetI->getOpcode() == Instruction::SExt ||
7230        RetI->getOpcode() == Instruction::ZExt)) {
7231     if (!RetI->hasOneUser())
7232       return InstructionCost::getInvalid();
7233     RetI = RetI->user_back();
7234   }
7235   if (RetI->getOpcode() == Instruction::Mul &&
7236       RetI->user_back()->getOpcode() == Instruction::Add) {
7237     if (!RetI->hasOneUser())
7238       return InstructionCost::getInvalid();
7239     RetI = RetI->user_back();
7240   }
7241 
7242   // Test if the found instruction is a reduction, and if not return an invalid
7243   // cost specifying the parent to use the original cost modelling.
7244   if (!InLoopReductionImmediateChains.count(RetI))
7245     return InstructionCost::getInvalid();
7246 
7247   // Find the reduction this chain is a part of and calculate the basic cost of
7248   // the reduction on its own.
7249   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7250   Instruction *ReductionPhi = LastChain;
7251   while (!isa<PHINode>(ReductionPhi))
7252     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7253 
7254   const RecurrenceDescriptor &RdxDesc =
7255       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7256   InstructionCost BaseCost =
7257       TTI.getArithmeticReductionCost(RdxDesc.getOpcode(), VectorTy, CostKind);
7258 
7259   // Get the operand that was not the reduction chain and match it to one of the
7260   // patterns, returning the better cost if it is found.
7261   Instruction *RedOp = RetI->getOperand(1) == LastChain
7262                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7263                            : dyn_cast<Instruction>(RetI->getOperand(1));
7264 
7265   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7266 
7267   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
7268       !TheLoop->isLoopInvariant(RedOp)) {
7269     bool IsUnsigned = isa<ZExtInst>(RedOp);
7270     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7271     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7272         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7273         CostKind);
7274 
7275     InstructionCost ExtCost =
7276         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7277                              TTI::CastContextHint::None, CostKind, RedOp);
7278     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7279       return I == RetI ? *RedCost.getValue() : 0;
7280   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
7281     Instruction *Mul = RedOp;
7282     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
7283     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
7284     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
7285         Op0->getOpcode() == Op1->getOpcode() &&
7286         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7287         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7288       bool IsUnsigned = isa<ZExtInst>(Op0);
7289       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7290       // reduce(mul(ext, ext))
7291       InstructionCost ExtCost =
7292           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7293                                TTI::CastContextHint::None, CostKind, Op0);
7294       InstructionCost MulCost =
7295           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7296 
7297       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7298           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7299           CostKind);
7300 
7301       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7302         return I == RetI ? *RedCost.getValue() : 0;
7303     } else {
7304       InstructionCost MulCost =
7305           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7306 
7307       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7308           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7309           CostKind);
7310 
7311       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7312         return I == RetI ? *RedCost.getValue() : 0;
7313     }
7314   }
7315 
7316   return I == RetI ? BaseCost : InstructionCost::getInvalid();
7317 }
7318 
7319 InstructionCost
7320 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7321                                                      ElementCount VF) {
7322   // Calculate scalar cost only. Vectorization cost should be ready at this
7323   // moment.
7324   if (VF.isScalar()) {
7325     Type *ValTy = getLoadStoreType(I);
7326     const Align Alignment = getLoadStoreAlignment(I);
7327     unsigned AS = getLoadStoreAddressSpace(I);
7328 
7329     return TTI.getAddressComputationCost(ValTy) +
7330            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7331                                TTI::TCK_RecipThroughput, I);
7332   }
7333   return getWideningCost(I, VF);
7334 }
7335 
7336 LoopVectorizationCostModel::VectorizationCostTy
7337 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7338                                                ElementCount VF) {
7339   // If we know that this instruction will remain uniform, check the cost of
7340   // the scalar version.
7341   if (isUniformAfterVectorization(I, VF))
7342     VF = ElementCount::getFixed(1);
7343 
7344   if (VF.isVector() && isProfitableToScalarize(I, VF))
7345     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7346 
7347   // Forced scalars do not have any scalarization overhead.
7348   auto ForcedScalar = ForcedScalars.find(VF);
7349   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7350     auto InstSet = ForcedScalar->second;
7351     if (InstSet.count(I))
7352       return VectorizationCostTy(
7353           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7354            VF.getKnownMinValue()),
7355           false);
7356   }
7357 
7358   Type *VectorTy;
7359   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7360 
7361   bool TypeNotScalarized =
7362       VF.isVector() && VectorTy->isVectorTy() &&
7363       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7364   return VectorizationCostTy(C, TypeNotScalarized);
7365 }
7366 
7367 InstructionCost
7368 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7369                                                      ElementCount VF) const {
7370 
7371   // There is no mechanism yet to create a scalable scalarization loop,
7372   // so this is currently Invalid.
7373   if (VF.isScalable())
7374     return InstructionCost::getInvalid();
7375 
7376   if (VF.isScalar())
7377     return 0;
7378 
7379   InstructionCost Cost = 0;
7380   Type *RetTy = ToVectorTy(I->getType(), VF);
7381   if (!RetTy->isVoidTy() &&
7382       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7383     Cost += TTI.getScalarizationOverhead(
7384         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7385         true, false);
7386 
7387   // Some targets keep addresses scalar.
7388   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7389     return Cost;
7390 
7391   // Some targets support efficient element stores.
7392   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7393     return Cost;
7394 
7395   // Collect operands to consider.
7396   CallInst *CI = dyn_cast<CallInst>(I);
7397   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7398 
7399   // Skip operands that do not require extraction/scalarization and do not incur
7400   // any overhead.
7401   SmallVector<Type *> Tys;
7402   for (auto *V : filterExtractingOperands(Ops, VF))
7403     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7404   return Cost + TTI.getOperandsScalarizationOverhead(
7405                     filterExtractingOperands(Ops, VF), Tys);
7406 }
7407 
7408 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7409   if (VF.isScalar())
7410     return;
7411   NumPredStores = 0;
7412   for (BasicBlock *BB : TheLoop->blocks()) {
7413     // For each instruction in the old loop.
7414     for (Instruction &I : *BB) {
7415       Value *Ptr =  getLoadStorePointerOperand(&I);
7416       if (!Ptr)
7417         continue;
7418 
7419       // TODO: We should generate better code and update the cost model for
7420       // predicated uniform stores. Today they are treated as any other
7421       // predicated store (see added test cases in
7422       // invariant-store-vectorization.ll).
7423       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7424         NumPredStores++;
7425 
7426       if (Legal->isUniformMemOp(I)) {
7427         // TODO: Avoid replicating loads and stores instead of
7428         // relying on instcombine to remove them.
7429         // Load: Scalar load + broadcast
7430         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7431         InstructionCost Cost;
7432         if (isa<StoreInst>(&I) && VF.isScalable() &&
7433             isLegalGatherOrScatter(&I)) {
7434           Cost = getGatherScatterCost(&I, VF);
7435           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7436         } else {
7437           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7438                  "Cannot yet scalarize uniform stores");
7439           Cost = getUniformMemOpCost(&I, VF);
7440           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7441         }
7442         continue;
7443       }
7444 
7445       // We assume that widening is the best solution when possible.
7446       if (memoryInstructionCanBeWidened(&I, VF)) {
7447         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7448         int ConsecutiveStride =
7449                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7450         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7451                "Expected consecutive stride.");
7452         InstWidening Decision =
7453             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7454         setWideningDecision(&I, VF, Decision, Cost);
7455         continue;
7456       }
7457 
7458       // Choose between Interleaving, Gather/Scatter or Scalarization.
7459       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7460       unsigned NumAccesses = 1;
7461       if (isAccessInterleaved(&I)) {
7462         auto Group = getInterleavedAccessGroup(&I);
7463         assert(Group && "Fail to get an interleaved access group.");
7464 
7465         // Make one decision for the whole group.
7466         if (getWideningDecision(&I, VF) != CM_Unknown)
7467           continue;
7468 
7469         NumAccesses = Group->getNumMembers();
7470         if (interleavedAccessCanBeWidened(&I, VF))
7471           InterleaveCost = getInterleaveGroupCost(&I, VF);
7472       }
7473 
7474       InstructionCost GatherScatterCost =
7475           isLegalGatherOrScatter(&I)
7476               ? getGatherScatterCost(&I, VF) * NumAccesses
7477               : InstructionCost::getInvalid();
7478 
7479       InstructionCost ScalarizationCost =
7480           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7481 
7482       // Choose better solution for the current VF,
7483       // write down this decision and use it during vectorization.
7484       InstructionCost Cost;
7485       InstWidening Decision;
7486       if (InterleaveCost <= GatherScatterCost &&
7487           InterleaveCost < ScalarizationCost) {
7488         Decision = CM_Interleave;
7489         Cost = InterleaveCost;
7490       } else if (GatherScatterCost < ScalarizationCost) {
7491         Decision = CM_GatherScatter;
7492         Cost = GatherScatterCost;
7493       } else {
7494         assert(!VF.isScalable() &&
7495                "We cannot yet scalarise for scalable vectors");
7496         Decision = CM_Scalarize;
7497         Cost = ScalarizationCost;
7498       }
7499       // If the instructions belongs to an interleave group, the whole group
7500       // receives the same decision. The whole group receives the cost, but
7501       // the cost will actually be assigned to one instruction.
7502       if (auto Group = getInterleavedAccessGroup(&I))
7503         setWideningDecision(Group, VF, Decision, Cost);
7504       else
7505         setWideningDecision(&I, VF, Decision, Cost);
7506     }
7507   }
7508 
7509   // Make sure that any load of address and any other address computation
7510   // remains scalar unless there is gather/scatter support. This avoids
7511   // inevitable extracts into address registers, and also has the benefit of
7512   // activating LSR more, since that pass can't optimize vectorized
7513   // addresses.
7514   if (TTI.prefersVectorizedAddressing())
7515     return;
7516 
7517   // Start with all scalar pointer uses.
7518   SmallPtrSet<Instruction *, 8> AddrDefs;
7519   for (BasicBlock *BB : TheLoop->blocks())
7520     for (Instruction &I : *BB) {
7521       Instruction *PtrDef =
7522         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7523       if (PtrDef && TheLoop->contains(PtrDef) &&
7524           getWideningDecision(&I, VF) != CM_GatherScatter)
7525         AddrDefs.insert(PtrDef);
7526     }
7527 
7528   // Add all instructions used to generate the addresses.
7529   SmallVector<Instruction *, 4> Worklist;
7530   append_range(Worklist, AddrDefs);
7531   while (!Worklist.empty()) {
7532     Instruction *I = Worklist.pop_back_val();
7533     for (auto &Op : I->operands())
7534       if (auto *InstOp = dyn_cast<Instruction>(Op))
7535         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7536             AddrDefs.insert(InstOp).second)
7537           Worklist.push_back(InstOp);
7538   }
7539 
7540   for (auto *I : AddrDefs) {
7541     if (isa<LoadInst>(I)) {
7542       // Setting the desired widening decision should ideally be handled in
7543       // by cost functions, but since this involves the task of finding out
7544       // if the loaded register is involved in an address computation, it is
7545       // instead changed here when we know this is the case.
7546       InstWidening Decision = getWideningDecision(I, VF);
7547       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7548         // Scalarize a widened load of address.
7549         setWideningDecision(
7550             I, VF, CM_Scalarize,
7551             (VF.getKnownMinValue() *
7552              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7553       else if (auto Group = getInterleavedAccessGroup(I)) {
7554         // Scalarize an interleave group of address loads.
7555         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7556           if (Instruction *Member = Group->getMember(I))
7557             setWideningDecision(
7558                 Member, VF, CM_Scalarize,
7559                 (VF.getKnownMinValue() *
7560                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7561         }
7562       }
7563     } else
7564       // Make sure I gets scalarized and a cost estimate without
7565       // scalarization overhead.
7566       ForcedScalars[VF].insert(I);
7567   }
7568 }
7569 
7570 InstructionCost
7571 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7572                                                Type *&VectorTy) {
7573   Type *RetTy = I->getType();
7574   if (canTruncateToMinimalBitwidth(I, VF))
7575     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7576   auto SE = PSE.getSE();
7577   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7578 
7579   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7580                                                 ElementCount VF) -> bool {
7581     if (VF.isScalar())
7582       return true;
7583 
7584     auto Scalarized = InstsToScalarize.find(VF);
7585     assert(Scalarized != InstsToScalarize.end() &&
7586            "VF not yet analyzed for scalarization profitability");
7587     return !Scalarized->second.count(I) &&
7588            llvm::all_of(I->users(), [&](User *U) {
7589              auto *UI = cast<Instruction>(U);
7590              return !Scalarized->second.count(UI);
7591            });
7592   };
7593   (void) hasSingleCopyAfterVectorization;
7594 
7595   if (isScalarAfterVectorization(I, VF)) {
7596     // With the exception of GEPs and PHIs, after scalarization there should
7597     // only be one copy of the instruction generated in the loop. This is
7598     // because the VF is either 1, or any instructions that need scalarizing
7599     // have already been dealt with by the the time we get here. As a result,
7600     // it means we don't have to multiply the instruction cost by VF.
7601     assert(I->getOpcode() == Instruction::GetElementPtr ||
7602            I->getOpcode() == Instruction::PHI ||
7603            (I->getOpcode() == Instruction::BitCast &&
7604             I->getType()->isPointerTy()) ||
7605            hasSingleCopyAfterVectorization(I, VF));
7606     VectorTy = RetTy;
7607   } else
7608     VectorTy = ToVectorTy(RetTy, VF);
7609 
7610   // TODO: We need to estimate the cost of intrinsic calls.
7611   switch (I->getOpcode()) {
7612   case Instruction::GetElementPtr:
7613     // We mark this instruction as zero-cost because the cost of GEPs in
7614     // vectorized code depends on whether the corresponding memory instruction
7615     // is scalarized or not. Therefore, we handle GEPs with the memory
7616     // instruction cost.
7617     return 0;
7618   case Instruction::Br: {
7619     // In cases of scalarized and predicated instructions, there will be VF
7620     // predicated blocks in the vectorized loop. Each branch around these
7621     // blocks requires also an extract of its vector compare i1 element.
7622     bool ScalarPredicatedBB = false;
7623     BranchInst *BI = cast<BranchInst>(I);
7624     if (VF.isVector() && BI->isConditional() &&
7625         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7626          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7627       ScalarPredicatedBB = true;
7628 
7629     if (ScalarPredicatedBB) {
7630       // Return cost for branches around scalarized and predicated blocks.
7631       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7632       auto *Vec_i1Ty =
7633           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7634       return (TTI.getScalarizationOverhead(
7635                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7636                   false, true) +
7637               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7638                VF.getKnownMinValue()));
7639     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7640       // The back-edge branch will remain, as will all scalar branches.
7641       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7642     else
7643       // This branch will be eliminated by if-conversion.
7644       return 0;
7645     // Note: We currently assume zero cost for an unconditional branch inside
7646     // a predicated block since it will become a fall-through, although we
7647     // may decide in the future to call TTI for all branches.
7648   }
7649   case Instruction::PHI: {
7650     auto *Phi = cast<PHINode>(I);
7651 
7652     // First-order recurrences are replaced by vector shuffles inside the loop.
7653     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7654     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7655       return TTI.getShuffleCost(
7656           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7657           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7658 
7659     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7660     // converted into select instructions. We require N - 1 selects per phi
7661     // node, where N is the number of incoming values.
7662     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7663       return (Phi->getNumIncomingValues() - 1) *
7664              TTI.getCmpSelInstrCost(
7665                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7666                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7667                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7668 
7669     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7670   }
7671   case Instruction::UDiv:
7672   case Instruction::SDiv:
7673   case Instruction::URem:
7674   case Instruction::SRem:
7675     // If we have a predicated instruction, it may not be executed for each
7676     // vector lane. Get the scalarization cost and scale this amount by the
7677     // probability of executing the predicated block. If the instruction is not
7678     // predicated, we fall through to the next case.
7679     if (VF.isVector() && isScalarWithPredication(I)) {
7680       InstructionCost Cost = 0;
7681 
7682       // These instructions have a non-void type, so account for the phi nodes
7683       // that we will create. This cost is likely to be zero. The phi node
7684       // cost, if any, should be scaled by the block probability because it
7685       // models a copy at the end of each predicated block.
7686       Cost += VF.getKnownMinValue() *
7687               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7688 
7689       // The cost of the non-predicated instruction.
7690       Cost += VF.getKnownMinValue() *
7691               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7692 
7693       // The cost of insertelement and extractelement instructions needed for
7694       // scalarization.
7695       Cost += getScalarizationOverhead(I, VF);
7696 
7697       // Scale the cost by the probability of executing the predicated blocks.
7698       // This assumes the predicated block for each vector lane is equally
7699       // likely.
7700       return Cost / getReciprocalPredBlockProb();
7701     }
7702     LLVM_FALLTHROUGH;
7703   case Instruction::Add:
7704   case Instruction::FAdd:
7705   case Instruction::Sub:
7706   case Instruction::FSub:
7707   case Instruction::Mul:
7708   case Instruction::FMul:
7709   case Instruction::FDiv:
7710   case Instruction::FRem:
7711   case Instruction::Shl:
7712   case Instruction::LShr:
7713   case Instruction::AShr:
7714   case Instruction::And:
7715   case Instruction::Or:
7716   case Instruction::Xor: {
7717     // Since we will replace the stride by 1 the multiplication should go away.
7718     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7719       return 0;
7720 
7721     // Detect reduction patterns
7722     InstructionCost RedCost;
7723     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7724             .isValid())
7725       return RedCost;
7726 
7727     // Certain instructions can be cheaper to vectorize if they have a constant
7728     // second vector operand. One example of this are shifts on x86.
7729     Value *Op2 = I->getOperand(1);
7730     TargetTransformInfo::OperandValueProperties Op2VP;
7731     TargetTransformInfo::OperandValueKind Op2VK =
7732         TTI.getOperandInfo(Op2, Op2VP);
7733     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7734       Op2VK = TargetTransformInfo::OK_UniformValue;
7735 
7736     SmallVector<const Value *, 4> Operands(I->operand_values());
7737     return TTI.getArithmeticInstrCost(
7738         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7739         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7740   }
7741   case Instruction::FNeg: {
7742     return TTI.getArithmeticInstrCost(
7743         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7744         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7745         TargetTransformInfo::OP_None, I->getOperand(0), I);
7746   }
7747   case Instruction::Select: {
7748     SelectInst *SI = cast<SelectInst>(I);
7749     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7750     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7751 
7752     const Value *Op0, *Op1;
7753     using namespace llvm::PatternMatch;
7754     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7755                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7756       // select x, y, false --> x & y
7757       // select x, true, y --> x | y
7758       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7759       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7760       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7761       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7762       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7763               Op1->getType()->getScalarSizeInBits() == 1);
7764 
7765       SmallVector<const Value *, 2> Operands{Op0, Op1};
7766       return TTI.getArithmeticInstrCost(
7767           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7768           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7769     }
7770 
7771     Type *CondTy = SI->getCondition()->getType();
7772     if (!ScalarCond)
7773       CondTy = VectorType::get(CondTy, VF);
7774     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7775                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7776   }
7777   case Instruction::ICmp:
7778   case Instruction::FCmp: {
7779     Type *ValTy = I->getOperand(0)->getType();
7780     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7781     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7782       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7783     VectorTy = ToVectorTy(ValTy, VF);
7784     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7785                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7786   }
7787   case Instruction::Store:
7788   case Instruction::Load: {
7789     ElementCount Width = VF;
7790     if (Width.isVector()) {
7791       InstWidening Decision = getWideningDecision(I, Width);
7792       assert(Decision != CM_Unknown &&
7793              "CM decision should be taken at this point");
7794       if (Decision == CM_Scalarize)
7795         Width = ElementCount::getFixed(1);
7796     }
7797     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7798     return getMemoryInstructionCost(I, VF);
7799   }
7800   case Instruction::BitCast:
7801     if (I->getType()->isPointerTy())
7802       return 0;
7803     LLVM_FALLTHROUGH;
7804   case Instruction::ZExt:
7805   case Instruction::SExt:
7806   case Instruction::FPToUI:
7807   case Instruction::FPToSI:
7808   case Instruction::FPExt:
7809   case Instruction::PtrToInt:
7810   case Instruction::IntToPtr:
7811   case Instruction::SIToFP:
7812   case Instruction::UIToFP:
7813   case Instruction::Trunc:
7814   case Instruction::FPTrunc: {
7815     // Computes the CastContextHint from a Load/Store instruction.
7816     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7817       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7818              "Expected a load or a store!");
7819 
7820       if (VF.isScalar() || !TheLoop->contains(I))
7821         return TTI::CastContextHint::Normal;
7822 
7823       switch (getWideningDecision(I, VF)) {
7824       case LoopVectorizationCostModel::CM_GatherScatter:
7825         return TTI::CastContextHint::GatherScatter;
7826       case LoopVectorizationCostModel::CM_Interleave:
7827         return TTI::CastContextHint::Interleave;
7828       case LoopVectorizationCostModel::CM_Scalarize:
7829       case LoopVectorizationCostModel::CM_Widen:
7830         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7831                                         : TTI::CastContextHint::Normal;
7832       case LoopVectorizationCostModel::CM_Widen_Reverse:
7833         return TTI::CastContextHint::Reversed;
7834       case LoopVectorizationCostModel::CM_Unknown:
7835         llvm_unreachable("Instr did not go through cost modelling?");
7836       }
7837 
7838       llvm_unreachable("Unhandled case!");
7839     };
7840 
7841     unsigned Opcode = I->getOpcode();
7842     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7843     // For Trunc, the context is the only user, which must be a StoreInst.
7844     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7845       if (I->hasOneUse())
7846         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7847           CCH = ComputeCCH(Store);
7848     }
7849     // For Z/Sext, the context is the operand, which must be a LoadInst.
7850     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7851              Opcode == Instruction::FPExt) {
7852       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7853         CCH = ComputeCCH(Load);
7854     }
7855 
7856     // We optimize the truncation of induction variables having constant
7857     // integer steps. The cost of these truncations is the same as the scalar
7858     // operation.
7859     if (isOptimizableIVTruncate(I, VF)) {
7860       auto *Trunc = cast<TruncInst>(I);
7861       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7862                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7863     }
7864 
7865     // Detect reduction patterns
7866     InstructionCost RedCost;
7867     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7868             .isValid())
7869       return RedCost;
7870 
7871     Type *SrcScalarTy = I->getOperand(0)->getType();
7872     Type *SrcVecTy =
7873         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7874     if (canTruncateToMinimalBitwidth(I, VF)) {
7875       // This cast is going to be shrunk. This may remove the cast or it might
7876       // turn it into slightly different cast. For example, if MinBW == 16,
7877       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7878       //
7879       // Calculate the modified src and dest types.
7880       Type *MinVecTy = VectorTy;
7881       if (Opcode == Instruction::Trunc) {
7882         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7883         VectorTy =
7884             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7885       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7886         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7887         VectorTy =
7888             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7889       }
7890     }
7891 
7892     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7893   }
7894   case Instruction::Call: {
7895     bool NeedToScalarize;
7896     CallInst *CI = cast<CallInst>(I);
7897     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7898     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7899       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7900       return std::min(CallCost, IntrinsicCost);
7901     }
7902     return CallCost;
7903   }
7904   case Instruction::ExtractValue:
7905     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7906   case Instruction::Alloca:
7907     // We cannot easily widen alloca to a scalable alloca, as
7908     // the result would need to be a vector of pointers.
7909     if (VF.isScalable())
7910       return InstructionCost::getInvalid();
7911     LLVM_FALLTHROUGH;
7912   default:
7913     // This opcode is unknown. Assume that it is the same as 'mul'.
7914     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7915   } // end of switch.
7916 }
7917 
7918 char LoopVectorize::ID = 0;
7919 
7920 static const char lv_name[] = "Loop Vectorization";
7921 
7922 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7923 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7924 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7925 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7926 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7927 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7928 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7929 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7930 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7931 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7932 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7933 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7934 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7935 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7936 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7937 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7938 
7939 namespace llvm {
7940 
7941 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7942 
7943 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7944                               bool VectorizeOnlyWhenForced) {
7945   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7946 }
7947 
7948 } // end namespace llvm
7949 
7950 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7951   // Check if the pointer operand of a load or store instruction is
7952   // consecutive.
7953   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7954     return Legal->isConsecutivePtr(Ptr);
7955   return false;
7956 }
7957 
7958 void LoopVectorizationCostModel::collectValuesToIgnore() {
7959   // Ignore ephemeral values.
7960   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7961 
7962   // Ignore type-promoting instructions we identified during reduction
7963   // detection.
7964   for (auto &Reduction : Legal->getReductionVars()) {
7965     RecurrenceDescriptor &RedDes = Reduction.second;
7966     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7967     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7968   }
7969   // Ignore type-casting instructions we identified during induction
7970   // detection.
7971   for (auto &Induction : Legal->getInductionVars()) {
7972     InductionDescriptor &IndDes = Induction.second;
7973     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7974     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7975   }
7976 }
7977 
7978 void LoopVectorizationCostModel::collectInLoopReductions() {
7979   for (auto &Reduction : Legal->getReductionVars()) {
7980     PHINode *Phi = Reduction.first;
7981     RecurrenceDescriptor &RdxDesc = Reduction.second;
7982 
7983     // We don't collect reductions that are type promoted (yet).
7984     if (RdxDesc.getRecurrenceType() != Phi->getType())
7985       continue;
7986 
7987     // If the target would prefer this reduction to happen "in-loop", then we
7988     // want to record it as such.
7989     unsigned Opcode = RdxDesc.getOpcode();
7990     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7991         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7992                                    TargetTransformInfo::ReductionFlags()))
7993       continue;
7994 
7995     // Check that we can correctly put the reductions into the loop, by
7996     // finding the chain of operations that leads from the phi to the loop
7997     // exit value.
7998     SmallVector<Instruction *, 4> ReductionOperations =
7999         RdxDesc.getReductionOpChain(Phi, TheLoop);
8000     bool InLoop = !ReductionOperations.empty();
8001     if (InLoop) {
8002       InLoopReductionChains[Phi] = ReductionOperations;
8003       // Add the elements to InLoopReductionImmediateChains for cost modelling.
8004       Instruction *LastChain = Phi;
8005       for (auto *I : ReductionOperations) {
8006         InLoopReductionImmediateChains[I] = LastChain;
8007         LastChain = I;
8008       }
8009     }
8010     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
8011                       << " reduction for phi: " << *Phi << "\n");
8012   }
8013 }
8014 
8015 // TODO: we could return a pair of values that specify the max VF and
8016 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
8017 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
8018 // doesn't have a cost model that can choose which plan to execute if
8019 // more than one is generated.
8020 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
8021                                  LoopVectorizationCostModel &CM) {
8022   unsigned WidestType;
8023   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
8024   return WidestVectorRegBits / WidestType;
8025 }
8026 
8027 VectorizationFactor
8028 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
8029   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
8030   ElementCount VF = UserVF;
8031   // Outer loop handling: They may require CFG and instruction level
8032   // transformations before even evaluating whether vectorization is profitable.
8033   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8034   // the vectorization pipeline.
8035   if (!OrigLoop->isInnermost()) {
8036     // If the user doesn't provide a vectorization factor, determine a
8037     // reasonable one.
8038     if (UserVF.isZero()) {
8039       VF = ElementCount::getFixed(determineVPlanVF(
8040           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
8041               .getFixedSize(),
8042           CM));
8043       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
8044 
8045       // Make sure we have a VF > 1 for stress testing.
8046       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
8047         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
8048                           << "overriding computed VF.\n");
8049         VF = ElementCount::getFixed(4);
8050       }
8051     }
8052     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8053     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
8054            "VF needs to be a power of two");
8055     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
8056                       << "VF " << VF << " to build VPlans.\n");
8057     buildVPlans(VF, VF);
8058 
8059     // For VPlan build stress testing, we bail out after VPlan construction.
8060     if (VPlanBuildStressTest)
8061       return VectorizationFactor::Disabled();
8062 
8063     return {VF, 0 /*Cost*/};
8064   }
8065 
8066   LLVM_DEBUG(
8067       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
8068                 "VPlan-native path.\n");
8069   return VectorizationFactor::Disabled();
8070 }
8071 
8072 Optional<VectorizationFactor>
8073 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
8074   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8075   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
8076   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
8077     return None;
8078 
8079   // Invalidate interleave groups if all blocks of loop will be predicated.
8080   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
8081       !useMaskedInterleavedAccesses(*TTI)) {
8082     LLVM_DEBUG(
8083         dbgs()
8084         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
8085            "which requires masked-interleaved support.\n");
8086     if (CM.InterleaveInfo.invalidateGroups())
8087       // Invalidating interleave groups also requires invalidating all decisions
8088       // based on them, which includes widening decisions and uniform and scalar
8089       // values.
8090       CM.invalidateCostModelingDecisions();
8091   }
8092 
8093   ElementCount MaxUserVF =
8094       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
8095   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
8096   if (!UserVF.isZero() && UserVFIsLegal) {
8097     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
8098            "VF needs to be a power of two");
8099     // Collect the instructions (and their associated costs) that will be more
8100     // profitable to scalarize.
8101     if (CM.selectUserVectorizationFactor(UserVF)) {
8102       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
8103       CM.collectInLoopReductions();
8104       buildVPlansWithVPRecipes(UserVF, UserVF);
8105       LLVM_DEBUG(printPlans(dbgs()));
8106       return {{UserVF, 0}};
8107     } else
8108       reportVectorizationInfo("UserVF ignored because of invalid costs.",
8109                               "InvalidCost", ORE, OrigLoop);
8110   }
8111 
8112   // Populate the set of Vectorization Factor Candidates.
8113   ElementCountSet VFCandidates;
8114   for (auto VF = ElementCount::getFixed(1);
8115        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
8116     VFCandidates.insert(VF);
8117   for (auto VF = ElementCount::getScalable(1);
8118        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
8119     VFCandidates.insert(VF);
8120 
8121   for (const auto &VF : VFCandidates) {
8122     // Collect Uniform and Scalar instructions after vectorization with VF.
8123     CM.collectUniformsAndScalars(VF);
8124 
8125     // Collect the instructions (and their associated costs) that will be more
8126     // profitable to scalarize.
8127     if (VF.isVector())
8128       CM.collectInstsToScalarize(VF);
8129   }
8130 
8131   CM.collectInLoopReductions();
8132   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
8133   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
8134 
8135   LLVM_DEBUG(printPlans(dbgs()));
8136   if (!MaxFactors.hasVector())
8137     return VectorizationFactor::Disabled();
8138 
8139   // Select the optimal vectorization factor.
8140   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
8141 
8142   // Check if it is profitable to vectorize with runtime checks.
8143   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8144   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8145     bool PragmaThresholdReached =
8146         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8147     bool ThresholdReached =
8148         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8149     if ((ThresholdReached && !Hints.allowReordering()) ||
8150         PragmaThresholdReached) {
8151       ORE->emit([&]() {
8152         return OptimizationRemarkAnalysisAliasing(
8153                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8154                    OrigLoop->getHeader())
8155                << "loop not vectorized: cannot prove it is safe to reorder "
8156                   "memory operations";
8157       });
8158       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8159       Hints.emitRemarkWithHints();
8160       return VectorizationFactor::Disabled();
8161     }
8162   }
8163   return SelectedVF;
8164 }
8165 
8166 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
8167   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
8168                     << '\n');
8169   BestVF = VF;
8170   BestUF = UF;
8171 
8172   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
8173     return !Plan->hasVF(VF);
8174   });
8175   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
8176 }
8177 
8178 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
8179                                            DominatorTree *DT) {
8180   // Perform the actual loop transformation.
8181 
8182   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8183   assert(BestVF.hasValue() && "Vectorization Factor is missing");
8184   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
8185 
8186   VPTransformState State{
8187       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
8188   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8189   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8190   State.CanonicalIV = ILV.Induction;
8191 
8192   ILV.printDebugTracesAtStart();
8193 
8194   //===------------------------------------------------===//
8195   //
8196   // Notice: any optimization or new instruction that go
8197   // into the code below should also be implemented in
8198   // the cost-model.
8199   //
8200   //===------------------------------------------------===//
8201 
8202   // 2. Copy and widen instructions from the old loop into the new loop.
8203   VPlans.front()->execute(&State);
8204 
8205   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8206   //    predication, updating analyses.
8207   ILV.fixVectorizedLoop(State);
8208 
8209   ILV.printDebugTracesAtEnd();
8210 }
8211 
8212 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8213 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8214   for (const auto &Plan : VPlans)
8215     if (PrintVPlansInDotFormat)
8216       Plan->printDOT(O);
8217     else
8218       Plan->print(O);
8219 }
8220 #endif
8221 
8222 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8223     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8224 
8225   // We create new control-flow for the vectorized loop, so the original exit
8226   // conditions will be dead after vectorization if it's only used by the
8227   // terminator
8228   SmallVector<BasicBlock*> ExitingBlocks;
8229   OrigLoop->getExitingBlocks(ExitingBlocks);
8230   for (auto *BB : ExitingBlocks) {
8231     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8232     if (!Cmp || !Cmp->hasOneUse())
8233       continue;
8234 
8235     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8236     if (!DeadInstructions.insert(Cmp).second)
8237       continue;
8238 
8239     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8240     // TODO: can recurse through operands in general
8241     for (Value *Op : Cmp->operands()) {
8242       if (isa<TruncInst>(Op) && Op->hasOneUse())
8243           DeadInstructions.insert(cast<Instruction>(Op));
8244     }
8245   }
8246 
8247   // We create new "steps" for induction variable updates to which the original
8248   // induction variables map. An original update instruction will be dead if
8249   // all its users except the induction variable are dead.
8250   auto *Latch = OrigLoop->getLoopLatch();
8251   for (auto &Induction : Legal->getInductionVars()) {
8252     PHINode *Ind = Induction.first;
8253     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8254 
8255     // If the tail is to be folded by masking, the primary induction variable,
8256     // if exists, isn't dead: it will be used for masking. Don't kill it.
8257     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8258       continue;
8259 
8260     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8261           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8262         }))
8263       DeadInstructions.insert(IndUpdate);
8264 
8265     // We record as "Dead" also the type-casting instructions we had identified
8266     // during induction analysis. We don't need any handling for them in the
8267     // vectorized loop because we have proven that, under a proper runtime
8268     // test guarding the vectorized loop, the value of the phi, and the casted
8269     // value of the phi, are the same. The last instruction in this casting chain
8270     // will get its scalar/vector/widened def from the scalar/vector/widened def
8271     // of the respective phi node. Any other casts in the induction def-use chain
8272     // have no other uses outside the phi update chain, and will be ignored.
8273     InductionDescriptor &IndDes = Induction.second;
8274     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8275     DeadInstructions.insert(Casts.begin(), Casts.end());
8276   }
8277 }
8278 
8279 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8280 
8281 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8282 
8283 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8284                                         Instruction::BinaryOps BinOp) {
8285   // When unrolling and the VF is 1, we only need to add a simple scalar.
8286   Type *Ty = Val->getType();
8287   assert(!Ty->isVectorTy() && "Val must be a scalar");
8288 
8289   if (Ty->isFloatingPointTy()) {
8290     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8291 
8292     // Floating-point operations inherit FMF via the builder's flags.
8293     Value *MulOp = Builder.CreateFMul(C, Step);
8294     return Builder.CreateBinOp(BinOp, Val, MulOp);
8295   }
8296   Constant *C = ConstantInt::get(Ty, StartIdx);
8297   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8298 }
8299 
8300 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8301   SmallVector<Metadata *, 4> MDs;
8302   // Reserve first location for self reference to the LoopID metadata node.
8303   MDs.push_back(nullptr);
8304   bool IsUnrollMetadata = false;
8305   MDNode *LoopID = L->getLoopID();
8306   if (LoopID) {
8307     // First find existing loop unrolling disable metadata.
8308     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8309       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8310       if (MD) {
8311         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8312         IsUnrollMetadata =
8313             S && S->getString().startswith("llvm.loop.unroll.disable");
8314       }
8315       MDs.push_back(LoopID->getOperand(i));
8316     }
8317   }
8318 
8319   if (!IsUnrollMetadata) {
8320     // Add runtime unroll disable metadata.
8321     LLVMContext &Context = L->getHeader()->getContext();
8322     SmallVector<Metadata *, 1> DisableOperands;
8323     DisableOperands.push_back(
8324         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8325     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8326     MDs.push_back(DisableNode);
8327     MDNode *NewLoopID = MDNode::get(Context, MDs);
8328     // Set operand 0 to refer to the loop id itself.
8329     NewLoopID->replaceOperandWith(0, NewLoopID);
8330     L->setLoopID(NewLoopID);
8331   }
8332 }
8333 
8334 //===--------------------------------------------------------------------===//
8335 // EpilogueVectorizerMainLoop
8336 //===--------------------------------------------------------------------===//
8337 
8338 /// This function is partially responsible for generating the control flow
8339 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8340 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8341   MDNode *OrigLoopID = OrigLoop->getLoopID();
8342   Loop *Lp = createVectorLoopSkeleton("");
8343 
8344   // Generate the code to check the minimum iteration count of the vector
8345   // epilogue (see below).
8346   EPI.EpilogueIterationCountCheck =
8347       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8348   EPI.EpilogueIterationCountCheck->setName("iter.check");
8349 
8350   // Generate the code to check any assumptions that we've made for SCEV
8351   // expressions.
8352   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8353 
8354   // Generate the code that checks at runtime if arrays overlap. We put the
8355   // checks into a separate block to make the more common case of few elements
8356   // faster.
8357   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8358 
8359   // Generate the iteration count check for the main loop, *after* the check
8360   // for the epilogue loop, so that the path-length is shorter for the case
8361   // that goes directly through the vector epilogue. The longer-path length for
8362   // the main loop is compensated for, by the gain from vectorizing the larger
8363   // trip count. Note: the branch will get updated later on when we vectorize
8364   // the epilogue.
8365   EPI.MainLoopIterationCountCheck =
8366       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8367 
8368   // Generate the induction variable.
8369   OldInduction = Legal->getPrimaryInduction();
8370   Type *IdxTy = Legal->getWidestInductionType();
8371   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8372   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8373   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8374   EPI.VectorTripCount = CountRoundDown;
8375   Induction =
8376       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8377                               getDebugLocFromInstOrOperands(OldInduction));
8378 
8379   // Skip induction resume value creation here because they will be created in
8380   // the second pass. If we created them here, they wouldn't be used anyway,
8381   // because the vplan in the second pass still contains the inductions from the
8382   // original loop.
8383 
8384   return completeLoopSkeleton(Lp, OrigLoopID);
8385 }
8386 
8387 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8388   LLVM_DEBUG({
8389     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8390            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8391            << ", Main Loop UF:" << EPI.MainLoopUF
8392            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8393            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8394   });
8395 }
8396 
8397 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8398   DEBUG_WITH_TYPE(VerboseDebug, {
8399     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8400   });
8401 }
8402 
8403 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8404     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8405   assert(L && "Expected valid Loop.");
8406   assert(Bypass && "Expected valid bypass basic block.");
8407   unsigned VFactor =
8408       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8409   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8410   Value *Count = getOrCreateTripCount(L);
8411   // Reuse existing vector loop preheader for TC checks.
8412   // Note that new preheader block is generated for vector loop.
8413   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8414   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8415 
8416   // Generate code to check if the loop's trip count is less than VF * UF of the
8417   // main vector loop.
8418   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8419       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8420 
8421   Value *CheckMinIters = Builder.CreateICmp(
8422       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8423       "min.iters.check");
8424 
8425   if (!ForEpilogue)
8426     TCCheckBlock->setName("vector.main.loop.iter.check");
8427 
8428   // Create new preheader for vector loop.
8429   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8430                                    DT, LI, nullptr, "vector.ph");
8431 
8432   if (ForEpilogue) {
8433     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8434                                  DT->getNode(Bypass)->getIDom()) &&
8435            "TC check is expected to dominate Bypass");
8436 
8437     // Update dominator for Bypass & LoopExit.
8438     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8439     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8440       // For loops with multiple exits, there's no edge from the middle block
8441       // to exit blocks (as the epilogue must run) and thus no need to update
8442       // the immediate dominator of the exit blocks.
8443       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8444 
8445     LoopBypassBlocks.push_back(TCCheckBlock);
8446 
8447     // Save the trip count so we don't have to regenerate it in the
8448     // vec.epilog.iter.check. This is safe to do because the trip count
8449     // generated here dominates the vector epilog iter check.
8450     EPI.TripCount = Count;
8451   }
8452 
8453   ReplaceInstWithInst(
8454       TCCheckBlock->getTerminator(),
8455       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8456 
8457   return TCCheckBlock;
8458 }
8459 
8460 //===--------------------------------------------------------------------===//
8461 // EpilogueVectorizerEpilogueLoop
8462 //===--------------------------------------------------------------------===//
8463 
8464 /// This function is partially responsible for generating the control flow
8465 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8466 BasicBlock *
8467 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8468   MDNode *OrigLoopID = OrigLoop->getLoopID();
8469   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8470 
8471   // Now, compare the remaining count and if there aren't enough iterations to
8472   // execute the vectorized epilogue skip to the scalar part.
8473   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8474   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8475   LoopVectorPreHeader =
8476       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8477                  LI, nullptr, "vec.epilog.ph");
8478   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8479                                           VecEpilogueIterationCountCheck);
8480 
8481   // Adjust the control flow taking the state info from the main loop
8482   // vectorization into account.
8483   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8484          "expected this to be saved from the previous pass.");
8485   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8486       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8487 
8488   DT->changeImmediateDominator(LoopVectorPreHeader,
8489                                EPI.MainLoopIterationCountCheck);
8490 
8491   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8492       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8493 
8494   if (EPI.SCEVSafetyCheck)
8495     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8496         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8497   if (EPI.MemSafetyCheck)
8498     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8499         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8500 
8501   DT->changeImmediateDominator(
8502       VecEpilogueIterationCountCheck,
8503       VecEpilogueIterationCountCheck->getSinglePredecessor());
8504 
8505   DT->changeImmediateDominator(LoopScalarPreHeader,
8506                                EPI.EpilogueIterationCountCheck);
8507   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8508     // If there is an epilogue which must run, there's no edge from the
8509     // middle block to exit blocks  and thus no need to update the immediate
8510     // dominator of the exit blocks.
8511     DT->changeImmediateDominator(LoopExitBlock,
8512                                  EPI.EpilogueIterationCountCheck);
8513 
8514   // Keep track of bypass blocks, as they feed start values to the induction
8515   // phis in the scalar loop preheader.
8516   if (EPI.SCEVSafetyCheck)
8517     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8518   if (EPI.MemSafetyCheck)
8519     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8520   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8521 
8522   // Generate a resume induction for the vector epilogue and put it in the
8523   // vector epilogue preheader
8524   Type *IdxTy = Legal->getWidestInductionType();
8525   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8526                                          LoopVectorPreHeader->getFirstNonPHI());
8527   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8528   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8529                            EPI.MainLoopIterationCountCheck);
8530 
8531   // Generate the induction variable.
8532   OldInduction = Legal->getPrimaryInduction();
8533   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8534   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8535   Value *StartIdx = EPResumeVal;
8536   Induction =
8537       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8538                               getDebugLocFromInstOrOperands(OldInduction));
8539 
8540   // Generate induction resume values. These variables save the new starting
8541   // indexes for the scalar loop. They are used to test if there are any tail
8542   // iterations left once the vector loop has completed.
8543   // Note that when the vectorized epilogue is skipped due to iteration count
8544   // check, then the resume value for the induction variable comes from
8545   // the trip count of the main vector loop, hence passing the AdditionalBypass
8546   // argument.
8547   createInductionResumeValues(Lp, CountRoundDown,
8548                               {VecEpilogueIterationCountCheck,
8549                                EPI.VectorTripCount} /* AdditionalBypass */);
8550 
8551   AddRuntimeUnrollDisableMetaData(Lp);
8552   return completeLoopSkeleton(Lp, OrigLoopID);
8553 }
8554 
8555 BasicBlock *
8556 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8557     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8558 
8559   assert(EPI.TripCount &&
8560          "Expected trip count to have been safed in the first pass.");
8561   assert(
8562       (!isa<Instruction>(EPI.TripCount) ||
8563        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8564       "saved trip count does not dominate insertion point.");
8565   Value *TC = EPI.TripCount;
8566   IRBuilder<> Builder(Insert->getTerminator());
8567   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8568 
8569   // Generate code to check if the loop's trip count is less than VF * UF of the
8570   // vector epilogue loop.
8571   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8572       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8573 
8574   Value *CheckMinIters = Builder.CreateICmp(
8575       P, Count,
8576       ConstantInt::get(Count->getType(),
8577                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8578       "min.epilog.iters.check");
8579 
8580   ReplaceInstWithInst(
8581       Insert->getTerminator(),
8582       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8583 
8584   LoopBypassBlocks.push_back(Insert);
8585   return Insert;
8586 }
8587 
8588 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8589   LLVM_DEBUG({
8590     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8591            << "Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8592            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8593   });
8594 }
8595 
8596 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8597   DEBUG_WITH_TYPE(VerboseDebug, {
8598     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8599   });
8600 }
8601 
8602 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8603     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8604   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8605   bool PredicateAtRangeStart = Predicate(Range.Start);
8606 
8607   for (ElementCount TmpVF = Range.Start * 2;
8608        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8609     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8610       Range.End = TmpVF;
8611       break;
8612     }
8613 
8614   return PredicateAtRangeStart;
8615 }
8616 
8617 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8618 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8619 /// of VF's starting at a given VF and extending it as much as possible. Each
8620 /// vectorization decision can potentially shorten this sub-range during
8621 /// buildVPlan().
8622 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8623                                            ElementCount MaxVF) {
8624   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8625   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8626     VFRange SubRange = {VF, MaxVFPlusOne};
8627     VPlans.push_back(buildVPlan(SubRange));
8628     VF = SubRange.End;
8629   }
8630 }
8631 
8632 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8633                                          VPlanPtr &Plan) {
8634   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8635 
8636   // Look for cached value.
8637   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8638   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8639   if (ECEntryIt != EdgeMaskCache.end())
8640     return ECEntryIt->second;
8641 
8642   VPValue *SrcMask = createBlockInMask(Src, Plan);
8643 
8644   // The terminator has to be a branch inst!
8645   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8646   assert(BI && "Unexpected terminator found");
8647 
8648   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8649     return EdgeMaskCache[Edge] = SrcMask;
8650 
8651   // If source is an exiting block, we know the exit edge is dynamically dead
8652   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8653   // adding uses of an otherwise potentially dead instruction.
8654   if (OrigLoop->isLoopExiting(Src))
8655     return EdgeMaskCache[Edge] = SrcMask;
8656 
8657   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8658   assert(EdgeMask && "No Edge Mask found for condition");
8659 
8660   if (BI->getSuccessor(0) != Dst)
8661     EdgeMask = Builder.createNot(EdgeMask);
8662 
8663   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8664     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8665     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8666     // The select version does not introduce new UB if SrcMask is false and
8667     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8668     VPValue *False = Plan->getOrAddVPValue(
8669         ConstantInt::getFalse(BI->getCondition()->getType()));
8670     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8671   }
8672 
8673   return EdgeMaskCache[Edge] = EdgeMask;
8674 }
8675 
8676 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8677   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8678 
8679   // Look for cached value.
8680   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8681   if (BCEntryIt != BlockMaskCache.end())
8682     return BCEntryIt->second;
8683 
8684   // All-one mask is modelled as no-mask following the convention for masked
8685   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8686   VPValue *BlockMask = nullptr;
8687 
8688   if (OrigLoop->getHeader() == BB) {
8689     if (!CM.blockNeedsPredication(BB))
8690       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8691 
8692     // Create the block in mask as the first non-phi instruction in the block.
8693     VPBuilder::InsertPointGuard Guard(Builder);
8694     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8695     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8696 
8697     // Introduce the early-exit compare IV <= BTC to form header block mask.
8698     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8699     // Start by constructing the desired canonical IV.
8700     VPValue *IV = nullptr;
8701     if (Legal->getPrimaryInduction())
8702       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8703     else {
8704       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8705       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8706       IV = IVRecipe->getVPSingleValue();
8707     }
8708     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8709     bool TailFolded = !CM.isScalarEpilogueAllowed();
8710 
8711     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8712       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8713       // as a second argument, we only pass the IV here and extract the
8714       // tripcount from the transform state where codegen of the VP instructions
8715       // happen.
8716       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8717     } else {
8718       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8719     }
8720     return BlockMaskCache[BB] = BlockMask;
8721   }
8722 
8723   // This is the block mask. We OR all incoming edges.
8724   for (auto *Predecessor : predecessors(BB)) {
8725     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8726     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8727       return BlockMaskCache[BB] = EdgeMask;
8728 
8729     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8730       BlockMask = EdgeMask;
8731       continue;
8732     }
8733 
8734     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8735   }
8736 
8737   return BlockMaskCache[BB] = BlockMask;
8738 }
8739 
8740 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8741                                                 ArrayRef<VPValue *> Operands,
8742                                                 VFRange &Range,
8743                                                 VPlanPtr &Plan) {
8744   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8745          "Must be called with either a load or store");
8746 
8747   auto willWiden = [&](ElementCount VF) -> bool {
8748     if (VF.isScalar())
8749       return false;
8750     LoopVectorizationCostModel::InstWidening Decision =
8751         CM.getWideningDecision(I, VF);
8752     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8753            "CM decision should be taken at this point.");
8754     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8755       return true;
8756     if (CM.isScalarAfterVectorization(I, VF) ||
8757         CM.isProfitableToScalarize(I, VF))
8758       return false;
8759     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8760   };
8761 
8762   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8763     return nullptr;
8764 
8765   VPValue *Mask = nullptr;
8766   if (Legal->isMaskRequired(I))
8767     Mask = createBlockInMask(I->getParent(), Plan);
8768 
8769   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8770     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8771 
8772   StoreInst *Store = cast<StoreInst>(I);
8773   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8774                                             Mask);
8775 }
8776 
8777 VPWidenIntOrFpInductionRecipe *
8778 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8779                                            ArrayRef<VPValue *> Operands) const {
8780   // Check if this is an integer or fp induction. If so, build the recipe that
8781   // produces its scalar and vector values.
8782   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8783   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8784       II.getKind() == InductionDescriptor::IK_FpInduction) {
8785     assert(II.getStartValue() ==
8786            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8787     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8788     return new VPWidenIntOrFpInductionRecipe(
8789         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8790   }
8791 
8792   return nullptr;
8793 }
8794 
8795 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8796     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8797     VPlan &Plan) const {
8798   // Optimize the special case where the source is a constant integer
8799   // induction variable. Notice that we can only optimize the 'trunc' case
8800   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8801   // (c) other casts depend on pointer size.
8802 
8803   // Determine whether \p K is a truncation based on an induction variable that
8804   // can be optimized.
8805   auto isOptimizableIVTruncate =
8806       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8807     return [=](ElementCount VF) -> bool {
8808       return CM.isOptimizableIVTruncate(K, VF);
8809     };
8810   };
8811 
8812   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8813           isOptimizableIVTruncate(I), Range)) {
8814 
8815     InductionDescriptor II =
8816         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8817     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8818     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8819                                              Start, nullptr, I);
8820   }
8821   return nullptr;
8822 }
8823 
8824 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8825                                                 ArrayRef<VPValue *> Operands,
8826                                                 VPlanPtr &Plan) {
8827   // If all incoming values are equal, the incoming VPValue can be used directly
8828   // instead of creating a new VPBlendRecipe.
8829   VPValue *FirstIncoming = Operands[0];
8830   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8831         return FirstIncoming == Inc;
8832       })) {
8833     return Operands[0];
8834   }
8835 
8836   // We know that all PHIs in non-header blocks are converted into selects, so
8837   // we don't have to worry about the insertion order and we can just use the
8838   // builder. At this point we generate the predication tree. There may be
8839   // duplications since this is a simple recursive scan, but future
8840   // optimizations will clean it up.
8841   SmallVector<VPValue *, 2> OperandsWithMask;
8842   unsigned NumIncoming = Phi->getNumIncomingValues();
8843 
8844   for (unsigned In = 0; In < NumIncoming; In++) {
8845     VPValue *EdgeMask =
8846       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8847     assert((EdgeMask || NumIncoming == 1) &&
8848            "Multiple predecessors with one having a full mask");
8849     OperandsWithMask.push_back(Operands[In]);
8850     if (EdgeMask)
8851       OperandsWithMask.push_back(EdgeMask);
8852   }
8853   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8854 }
8855 
8856 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8857                                                    ArrayRef<VPValue *> Operands,
8858                                                    VFRange &Range) const {
8859 
8860   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8861       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8862       Range);
8863 
8864   if (IsPredicated)
8865     return nullptr;
8866 
8867   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8868   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8869              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8870              ID == Intrinsic::pseudoprobe ||
8871              ID == Intrinsic::experimental_noalias_scope_decl))
8872     return nullptr;
8873 
8874   auto willWiden = [&](ElementCount VF) -> bool {
8875     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8876     // The following case may be scalarized depending on the VF.
8877     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8878     // version of the instruction.
8879     // Is it beneficial to perform intrinsic call compared to lib call?
8880     bool NeedToScalarize = false;
8881     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8882     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8883     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8884     return UseVectorIntrinsic || !NeedToScalarize;
8885   };
8886 
8887   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8888     return nullptr;
8889 
8890   ArrayRef<VPValue *> Ops = Operands.take_front(CI->getNumArgOperands());
8891   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8892 }
8893 
8894 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8895   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8896          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8897   // Instruction should be widened, unless it is scalar after vectorization,
8898   // scalarization is profitable or it is predicated.
8899   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8900     return CM.isScalarAfterVectorization(I, VF) ||
8901            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8902   };
8903   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8904                                                              Range);
8905 }
8906 
8907 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8908                                            ArrayRef<VPValue *> Operands) const {
8909   auto IsVectorizableOpcode = [](unsigned Opcode) {
8910     switch (Opcode) {
8911     case Instruction::Add:
8912     case Instruction::And:
8913     case Instruction::AShr:
8914     case Instruction::BitCast:
8915     case Instruction::FAdd:
8916     case Instruction::FCmp:
8917     case Instruction::FDiv:
8918     case Instruction::FMul:
8919     case Instruction::FNeg:
8920     case Instruction::FPExt:
8921     case Instruction::FPToSI:
8922     case Instruction::FPToUI:
8923     case Instruction::FPTrunc:
8924     case Instruction::FRem:
8925     case Instruction::FSub:
8926     case Instruction::ICmp:
8927     case Instruction::IntToPtr:
8928     case Instruction::LShr:
8929     case Instruction::Mul:
8930     case Instruction::Or:
8931     case Instruction::PtrToInt:
8932     case Instruction::SDiv:
8933     case Instruction::Select:
8934     case Instruction::SExt:
8935     case Instruction::Shl:
8936     case Instruction::SIToFP:
8937     case Instruction::SRem:
8938     case Instruction::Sub:
8939     case Instruction::Trunc:
8940     case Instruction::UDiv:
8941     case Instruction::UIToFP:
8942     case Instruction::URem:
8943     case Instruction::Xor:
8944     case Instruction::ZExt:
8945       return true;
8946     }
8947     return false;
8948   };
8949 
8950   if (!IsVectorizableOpcode(I->getOpcode()))
8951     return nullptr;
8952 
8953   // Success: widen this instruction.
8954   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8955 }
8956 
8957 void VPRecipeBuilder::fixHeaderPhis() {
8958   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8959   for (VPWidenPHIRecipe *R : PhisToFix) {
8960     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8961     VPRecipeBase *IncR =
8962         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8963     R->addOperand(IncR->getVPSingleValue());
8964   }
8965 }
8966 
8967 VPBasicBlock *VPRecipeBuilder::handleReplication(
8968     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8969     VPlanPtr &Plan) {
8970   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8971       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8972       Range);
8973 
8974   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8975       [&](ElementCount VF) { return CM.isPredicatedInst(I); }, Range);
8976 
8977   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8978                                        IsUniform, IsPredicated);
8979   setRecipe(I, Recipe);
8980   Plan->addVPValue(I, Recipe);
8981 
8982   // Find if I uses a predicated instruction. If so, it will use its scalar
8983   // value. Avoid hoisting the insert-element which packs the scalar value into
8984   // a vector value, as that happens iff all users use the vector value.
8985   for (VPValue *Op : Recipe->operands()) {
8986     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8987     if (!PredR)
8988       continue;
8989     auto *RepR =
8990         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8991     assert(RepR->isPredicated() &&
8992            "expected Replicate recipe to be predicated");
8993     RepR->setAlsoPack(false);
8994   }
8995 
8996   // Finalize the recipe for Instr, first if it is not predicated.
8997   if (!IsPredicated) {
8998     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8999     VPBB->appendRecipe(Recipe);
9000     return VPBB;
9001   }
9002   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
9003   assert(VPBB->getSuccessors().empty() &&
9004          "VPBB has successors when handling predicated replication.");
9005   // Record predicated instructions for above packing optimizations.
9006   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
9007   VPBlockUtils::insertBlockAfter(Region, VPBB);
9008   auto *RegSucc = new VPBasicBlock();
9009   VPBlockUtils::insertBlockAfter(RegSucc, Region);
9010   return RegSucc;
9011 }
9012 
9013 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
9014                                                       VPRecipeBase *PredRecipe,
9015                                                       VPlanPtr &Plan) {
9016   // Instructions marked for predication are replicated and placed under an
9017   // if-then construct to prevent side-effects.
9018 
9019   // Generate recipes to compute the block mask for this region.
9020   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
9021 
9022   // Build the triangular if-then region.
9023   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
9024   assert(Instr->getParent() && "Predicated instruction not in any basic block");
9025   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
9026   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
9027   auto *PHIRecipe = Instr->getType()->isVoidTy()
9028                         ? nullptr
9029                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
9030   if (PHIRecipe) {
9031     Plan->removeVPValueFor(Instr);
9032     Plan->addVPValue(Instr, PHIRecipe);
9033   }
9034   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
9035   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
9036   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
9037 
9038   // Note: first set Entry as region entry and then connect successors starting
9039   // from it in order, to propagate the "parent" of each VPBasicBlock.
9040   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
9041   VPBlockUtils::connectBlocks(Pred, Exit);
9042 
9043   return Region;
9044 }
9045 
9046 VPRecipeOrVPValueTy
9047 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
9048                                         ArrayRef<VPValue *> Operands,
9049                                         VFRange &Range, VPlanPtr &Plan) {
9050   // First, check for specific widening recipes that deal with calls, memory
9051   // operations, inductions and Phi nodes.
9052   if (auto *CI = dyn_cast<CallInst>(Instr))
9053     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
9054 
9055   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
9056     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
9057 
9058   VPRecipeBase *Recipe;
9059   if (auto Phi = dyn_cast<PHINode>(Instr)) {
9060     if (Phi->getParent() != OrigLoop->getHeader())
9061       return tryToBlend(Phi, Operands, Plan);
9062     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
9063       return toVPRecipeResult(Recipe);
9064 
9065     VPWidenPHIRecipe *PhiRecipe = nullptr;
9066     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
9067       VPValue *StartV = Operands[0];
9068       if (Legal->isReductionVariable(Phi)) {
9069         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9070         assert(RdxDesc.getRecurrenceStartValue() ==
9071                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
9072         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
9073                                              CM.isInLoopReduction(Phi),
9074                                              CM.useOrderedReductions(RdxDesc));
9075       } else {
9076         PhiRecipe = new VPWidenPHIRecipe(Phi, *StartV);
9077       }
9078 
9079       // Record the incoming value from the backedge, so we can add the incoming
9080       // value from the backedge after all recipes have been created.
9081       recordRecipeOf(cast<Instruction>(
9082           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
9083       PhisToFix.push_back(PhiRecipe);
9084     } else {
9085       // TODO: record start and backedge value for remaining pointer induction
9086       // phis.
9087       assert(Phi->getType()->isPointerTy() &&
9088              "only pointer phis should be handled here");
9089       PhiRecipe = new VPWidenPHIRecipe(Phi);
9090     }
9091 
9092     return toVPRecipeResult(PhiRecipe);
9093   }
9094 
9095   if (isa<TruncInst>(Instr) &&
9096       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
9097                                                Range, *Plan)))
9098     return toVPRecipeResult(Recipe);
9099 
9100   if (!shouldWiden(Instr, Range))
9101     return nullptr;
9102 
9103   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
9104     return toVPRecipeResult(new VPWidenGEPRecipe(
9105         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
9106 
9107   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
9108     bool InvariantCond =
9109         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
9110     return toVPRecipeResult(new VPWidenSelectRecipe(
9111         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
9112   }
9113 
9114   return toVPRecipeResult(tryToWiden(Instr, Operands));
9115 }
9116 
9117 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
9118                                                         ElementCount MaxVF) {
9119   assert(OrigLoop->isInnermost() && "Inner loop expected.");
9120 
9121   // Collect instructions from the original loop that will become trivially dead
9122   // in the vectorized loop. We don't need to vectorize these instructions. For
9123   // example, original induction update instructions can become dead because we
9124   // separately emit induction "steps" when generating code for the new loop.
9125   // Similarly, we create a new latch condition when setting up the structure
9126   // of the new loop, so the old one can become dead.
9127   SmallPtrSet<Instruction *, 4> DeadInstructions;
9128   collectTriviallyDeadInstructions(DeadInstructions);
9129 
9130   // Add assume instructions we need to drop to DeadInstructions, to prevent
9131   // them from being added to the VPlan.
9132   // TODO: We only need to drop assumes in blocks that get flattend. If the
9133   // control flow is preserved, we should keep them.
9134   auto &ConditionalAssumes = Legal->getConditionalAssumes();
9135   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
9136 
9137   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
9138   // Dead instructions do not need sinking. Remove them from SinkAfter.
9139   for (Instruction *I : DeadInstructions)
9140     SinkAfter.erase(I);
9141 
9142   // Cannot sink instructions after dead instructions (there won't be any
9143   // recipes for them). Instead, find the first non-dead previous instruction.
9144   for (auto &P : Legal->getSinkAfter()) {
9145     Instruction *SinkTarget = P.second;
9146     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
9147     (void)FirstInst;
9148     while (DeadInstructions.contains(SinkTarget)) {
9149       assert(
9150           SinkTarget != FirstInst &&
9151           "Must find a live instruction (at least the one feeding the "
9152           "first-order recurrence PHI) before reaching beginning of the block");
9153       SinkTarget = SinkTarget->getPrevNode();
9154       assert(SinkTarget != P.first &&
9155              "sink source equals target, no sinking required");
9156     }
9157     P.second = SinkTarget;
9158   }
9159 
9160   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9161   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9162     VFRange SubRange = {VF, MaxVFPlusOne};
9163     VPlans.push_back(
9164         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9165     VF = SubRange.End;
9166   }
9167 }
9168 
9169 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9170     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9171     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9172 
9173   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9174 
9175   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9176 
9177   // ---------------------------------------------------------------------------
9178   // Pre-construction: record ingredients whose recipes we'll need to further
9179   // process after constructing the initial VPlan.
9180   // ---------------------------------------------------------------------------
9181 
9182   // Mark instructions we'll need to sink later and their targets as
9183   // ingredients whose recipe we'll need to record.
9184   for (auto &Entry : SinkAfter) {
9185     RecipeBuilder.recordRecipeOf(Entry.first);
9186     RecipeBuilder.recordRecipeOf(Entry.second);
9187   }
9188   for (auto &Reduction : CM.getInLoopReductionChains()) {
9189     PHINode *Phi = Reduction.first;
9190     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9191     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9192 
9193     RecipeBuilder.recordRecipeOf(Phi);
9194     for (auto &R : ReductionOperations) {
9195       RecipeBuilder.recordRecipeOf(R);
9196       // For min/max reducitons, where we have a pair of icmp/select, we also
9197       // need to record the ICmp recipe, so it can be removed later.
9198       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9199         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9200     }
9201   }
9202 
9203   // For each interleave group which is relevant for this (possibly trimmed)
9204   // Range, add it to the set of groups to be later applied to the VPlan and add
9205   // placeholders for its members' Recipes which we'll be replacing with a
9206   // single VPInterleaveRecipe.
9207   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9208     auto applyIG = [IG, this](ElementCount VF) -> bool {
9209       return (VF.isVector() && // Query is illegal for VF == 1
9210               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9211                   LoopVectorizationCostModel::CM_Interleave);
9212     };
9213     if (!getDecisionAndClampRange(applyIG, Range))
9214       continue;
9215     InterleaveGroups.insert(IG);
9216     for (unsigned i = 0; i < IG->getFactor(); i++)
9217       if (Instruction *Member = IG->getMember(i))
9218         RecipeBuilder.recordRecipeOf(Member);
9219   };
9220 
9221   // ---------------------------------------------------------------------------
9222   // Build initial VPlan: Scan the body of the loop in a topological order to
9223   // visit each basic block after having visited its predecessor basic blocks.
9224   // ---------------------------------------------------------------------------
9225 
9226   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
9227   auto Plan = std::make_unique<VPlan>();
9228   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
9229   Plan->setEntry(VPBB);
9230 
9231   // Scan the body of the loop in a topological order to visit each basic block
9232   // after having visited its predecessor basic blocks.
9233   LoopBlocksDFS DFS(OrigLoop);
9234   DFS.perform(LI);
9235 
9236   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9237     // Relevant instructions from basic block BB will be grouped into VPRecipe
9238     // ingredients and fill a new VPBasicBlock.
9239     unsigned VPBBsForBB = 0;
9240     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9241     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9242     VPBB = FirstVPBBForBB;
9243     Builder.setInsertPoint(VPBB);
9244 
9245     // Introduce each ingredient into VPlan.
9246     // TODO: Model and preserve debug instrinsics in VPlan.
9247     for (Instruction &I : BB->instructionsWithoutDebug()) {
9248       Instruction *Instr = &I;
9249 
9250       // First filter out irrelevant instructions, to ensure no recipes are
9251       // built for them.
9252       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9253         continue;
9254 
9255       SmallVector<VPValue *, 4> Operands;
9256       auto *Phi = dyn_cast<PHINode>(Instr);
9257       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9258         Operands.push_back(Plan->getOrAddVPValue(
9259             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9260       } else {
9261         auto OpRange = Plan->mapToVPValues(Instr->operands());
9262         Operands = {OpRange.begin(), OpRange.end()};
9263       }
9264       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9265               Instr, Operands, Range, Plan)) {
9266         // If Instr can be simplified to an existing VPValue, use it.
9267         if (RecipeOrValue.is<VPValue *>()) {
9268           auto *VPV = RecipeOrValue.get<VPValue *>();
9269           Plan->addVPValue(Instr, VPV);
9270           // If the re-used value is a recipe, register the recipe for the
9271           // instruction, in case the recipe for Instr needs to be recorded.
9272           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9273             RecipeBuilder.setRecipe(Instr, R);
9274           continue;
9275         }
9276         // Otherwise, add the new recipe.
9277         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9278         for (auto *Def : Recipe->definedValues()) {
9279           auto *UV = Def->getUnderlyingValue();
9280           Plan->addVPValue(UV, Def);
9281         }
9282 
9283         RecipeBuilder.setRecipe(Instr, Recipe);
9284         VPBB->appendRecipe(Recipe);
9285         continue;
9286       }
9287 
9288       // Otherwise, if all widening options failed, Instruction is to be
9289       // replicated. This may create a successor for VPBB.
9290       VPBasicBlock *NextVPBB =
9291           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9292       if (NextVPBB != VPBB) {
9293         VPBB = NextVPBB;
9294         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9295                                     : "");
9296       }
9297     }
9298   }
9299 
9300   RecipeBuilder.fixHeaderPhis();
9301 
9302   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
9303   // may also be empty, such as the last one VPBB, reflecting original
9304   // basic-blocks with no recipes.
9305   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9306   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9307   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9308   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9309   delete PreEntry;
9310 
9311   // ---------------------------------------------------------------------------
9312   // Transform initial VPlan: Apply previously taken decisions, in order, to
9313   // bring the VPlan to its final state.
9314   // ---------------------------------------------------------------------------
9315 
9316   // Apply Sink-After legal constraints.
9317   for (auto &Entry : SinkAfter) {
9318     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9319     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9320 
9321     auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9322       auto *Region =
9323           dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9324       if (Region && Region->isReplicator()) {
9325         assert(Region->getNumSuccessors() == 1 &&
9326                Region->getNumPredecessors() == 1 && "Expected SESE region!");
9327         assert(R->getParent()->size() == 1 &&
9328                "A recipe in an original replicator region must be the only "
9329                "recipe in its block");
9330         return Region;
9331       }
9332       return nullptr;
9333     };
9334     auto *TargetRegion = GetReplicateRegion(Target);
9335     auto *SinkRegion = GetReplicateRegion(Sink);
9336     if (!SinkRegion) {
9337       // If the sink source is not a replicate region, sink the recipe directly.
9338       if (TargetRegion) {
9339         // The target is in a replication region, make sure to move Sink to
9340         // the block after it, not into the replication region itself.
9341         VPBasicBlock *NextBlock =
9342             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9343         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9344       } else
9345         Sink->moveAfter(Target);
9346       continue;
9347     }
9348 
9349     // The sink source is in a replicate region. Unhook the region from the CFG.
9350     auto *SinkPred = SinkRegion->getSinglePredecessor();
9351     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9352     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9353     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9354     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9355 
9356     if (TargetRegion) {
9357       // The target recipe is also in a replicate region, move the sink region
9358       // after the target region.
9359       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9360       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9361       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9362       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9363     } else {
9364       // The sink source is in a replicate region, we need to move the whole
9365       // replicate region, which should only contain a single recipe in the main
9366       // block.
9367       auto *SplitBlock =
9368           Target->getParent()->splitAt(std::next(Target->getIterator()));
9369 
9370       auto *SplitPred = SplitBlock->getSinglePredecessor();
9371 
9372       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9373       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9374       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9375       if (VPBB == SplitPred)
9376         VPBB = SplitBlock;
9377     }
9378   }
9379 
9380   // Interleave memory: for each Interleave Group we marked earlier as relevant
9381   // for this VPlan, replace the Recipes widening its memory instructions with a
9382   // single VPInterleaveRecipe at its insertion point.
9383   for (auto IG : InterleaveGroups) {
9384     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9385         RecipeBuilder.getRecipe(IG->getInsertPos()));
9386     SmallVector<VPValue *, 4> StoredValues;
9387     for (unsigned i = 0; i < IG->getFactor(); ++i)
9388       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
9389         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
9390 
9391     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9392                                         Recipe->getMask());
9393     VPIG->insertBefore(Recipe);
9394     unsigned J = 0;
9395     for (unsigned i = 0; i < IG->getFactor(); ++i)
9396       if (Instruction *Member = IG->getMember(i)) {
9397         if (!Member->getType()->isVoidTy()) {
9398           VPValue *OriginalV = Plan->getVPValue(Member);
9399           Plan->removeVPValueFor(Member);
9400           Plan->addVPValue(Member, VPIG->getVPValue(J));
9401           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9402           J++;
9403         }
9404         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9405       }
9406   }
9407 
9408   // Adjust the recipes for any inloop reductions.
9409   adjustRecipesForInLoopReductions(Plan, RecipeBuilder, Range.Start);
9410 
9411   // Finally, if tail is folded by masking, introduce selects between the phi
9412   // and the live-out instruction of each reduction, at the end of the latch.
9413   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
9414     Builder.setInsertPoint(VPBB);
9415     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9416     for (auto &Reduction : Legal->getReductionVars()) {
9417       if (CM.isInLoopReduction(Reduction.first))
9418         continue;
9419       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
9420       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
9421       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
9422     }
9423   }
9424 
9425   VPlanTransforms::sinkScalarOperands(*Plan);
9426   VPlanTransforms::mergeReplicateRegions(*Plan);
9427 
9428   std::string PlanName;
9429   raw_string_ostream RSO(PlanName);
9430   ElementCount VF = Range.Start;
9431   Plan->addVF(VF);
9432   RSO << "Initial VPlan for VF={" << VF;
9433   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9434     Plan->addVF(VF);
9435     RSO << "," << VF;
9436   }
9437   RSO << "},UF>=1";
9438   RSO.flush();
9439   Plan->setName(PlanName);
9440 
9441   return Plan;
9442 }
9443 
9444 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9445   // Outer loop handling: They may require CFG and instruction level
9446   // transformations before even evaluating whether vectorization is profitable.
9447   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9448   // the vectorization pipeline.
9449   assert(!OrigLoop->isInnermost());
9450   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9451 
9452   // Create new empty VPlan
9453   auto Plan = std::make_unique<VPlan>();
9454 
9455   // Build hierarchical CFG
9456   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9457   HCFGBuilder.buildHierarchicalCFG();
9458 
9459   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9460        VF *= 2)
9461     Plan->addVF(VF);
9462 
9463   if (EnableVPlanPredication) {
9464     VPlanPredicator VPP(*Plan);
9465     VPP.predicate();
9466 
9467     // Avoid running transformation to recipes until masked code generation in
9468     // VPlan-native path is in place.
9469     return Plan;
9470   }
9471 
9472   SmallPtrSet<Instruction *, 1> DeadInstructions;
9473   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9474                                              Legal->getInductionVars(),
9475                                              DeadInstructions, *PSE.getSE());
9476   return Plan;
9477 }
9478 
9479 // Adjust the recipes for any inloop reductions. The chain of instructions
9480 // leading from the loop exit instr to the phi need to be converted to
9481 // reductions, with one operand being vector and the other being the scalar
9482 // reduction chain.
9483 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
9484     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
9485   for (auto &Reduction : CM.getInLoopReductionChains()) {
9486     PHINode *Phi = Reduction.first;
9487     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9488     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9489 
9490     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9491       continue;
9492 
9493     // ReductionOperations are orders top-down from the phi's use to the
9494     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9495     // which of the two operands will remain scalar and which will be reduced.
9496     // For minmax the chain will be the select instructions.
9497     Instruction *Chain = Phi;
9498     for (Instruction *R : ReductionOperations) {
9499       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9500       RecurKind Kind = RdxDesc.getRecurrenceKind();
9501 
9502       VPValue *ChainOp = Plan->getVPValue(Chain);
9503       unsigned FirstOpId;
9504       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9505         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9506                "Expected to replace a VPWidenSelectSC");
9507         FirstOpId = 1;
9508       } else {
9509         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe)) &&
9510                "Expected to replace a VPWidenSC");
9511         FirstOpId = 0;
9512       }
9513       unsigned VecOpId =
9514           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9515       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9516 
9517       auto *CondOp = CM.foldTailByMasking()
9518                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9519                          : nullptr;
9520       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9521           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9522       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9523       Plan->removeVPValueFor(R);
9524       Plan->addVPValue(R, RedRecipe);
9525       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9526       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9527       WidenRecipe->eraseFromParent();
9528 
9529       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9530         VPRecipeBase *CompareRecipe =
9531             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9532         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9533                "Expected to replace a VPWidenSC");
9534         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9535                "Expected no remaining users");
9536         CompareRecipe->eraseFromParent();
9537       }
9538       Chain = R;
9539     }
9540   }
9541 }
9542 
9543 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9544 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9545                                VPSlotTracker &SlotTracker) const {
9546   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9547   IG->getInsertPos()->printAsOperand(O, false);
9548   O << ", ";
9549   getAddr()->printAsOperand(O, SlotTracker);
9550   VPValue *Mask = getMask();
9551   if (Mask) {
9552     O << ", ";
9553     Mask->printAsOperand(O, SlotTracker);
9554   }
9555   for (unsigned i = 0; i < IG->getFactor(); ++i)
9556     if (Instruction *I = IG->getMember(i))
9557       O << "\n" << Indent << "  " << VPlanIngredient(I) << " " << i;
9558 }
9559 #endif
9560 
9561 void VPWidenCallRecipe::execute(VPTransformState &State) {
9562   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9563                                   *this, State);
9564 }
9565 
9566 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9567   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9568                                     this, *this, InvariantCond, State);
9569 }
9570 
9571 void VPWidenRecipe::execute(VPTransformState &State) {
9572   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9573 }
9574 
9575 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9576   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9577                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9578                       IsIndexLoopInvariant, State);
9579 }
9580 
9581 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9582   assert(!State.Instance && "Int or FP induction being replicated.");
9583   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9584                                    getTruncInst(), getVPValue(0),
9585                                    getCastValue(), State);
9586 }
9587 
9588 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9589   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9590                                  State);
9591 }
9592 
9593 void VPBlendRecipe::execute(VPTransformState &State) {
9594   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9595   // We know that all PHIs in non-header blocks are converted into
9596   // selects, so we don't have to worry about the insertion order and we
9597   // can just use the builder.
9598   // At this point we generate the predication tree. There may be
9599   // duplications since this is a simple recursive scan, but future
9600   // optimizations will clean it up.
9601 
9602   unsigned NumIncoming = getNumIncomingValues();
9603 
9604   // Generate a sequence of selects of the form:
9605   // SELECT(Mask3, In3,
9606   //        SELECT(Mask2, In2,
9607   //               SELECT(Mask1, In1,
9608   //                      In0)))
9609   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9610   // are essentially undef are taken from In0.
9611   InnerLoopVectorizer::VectorParts Entry(State.UF);
9612   for (unsigned In = 0; In < NumIncoming; ++In) {
9613     for (unsigned Part = 0; Part < State.UF; ++Part) {
9614       // We might have single edge PHIs (blocks) - use an identity
9615       // 'select' for the first PHI operand.
9616       Value *In0 = State.get(getIncomingValue(In), Part);
9617       if (In == 0)
9618         Entry[Part] = In0; // Initialize with the first incoming value.
9619       else {
9620         // Select between the current value and the previous incoming edge
9621         // based on the incoming mask.
9622         Value *Cond = State.get(getMask(In), Part);
9623         Entry[Part] =
9624             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9625       }
9626     }
9627   }
9628   for (unsigned Part = 0; Part < State.UF; ++Part)
9629     State.set(this, Entry[Part], Part);
9630 }
9631 
9632 void VPInterleaveRecipe::execute(VPTransformState &State) {
9633   assert(!State.Instance && "Interleave group being replicated.");
9634   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9635                                       getStoredValues(), getMask());
9636 }
9637 
9638 void VPReductionRecipe::execute(VPTransformState &State) {
9639   assert(!State.Instance && "Reduction being replicated.");
9640   Value *PrevInChain = State.get(getChainOp(), 0);
9641   for (unsigned Part = 0; Part < State.UF; ++Part) {
9642     RecurKind Kind = RdxDesc->getRecurrenceKind();
9643     bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9644     Value *NewVecOp = State.get(getVecOp(), Part);
9645     if (VPValue *Cond = getCondOp()) {
9646       Value *NewCond = State.get(Cond, Part);
9647       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9648       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9649           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9650       Constant *IdenVec =
9651           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9652       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9653       NewVecOp = Select;
9654     }
9655     Value *NewRed;
9656     Value *NextInChain;
9657     if (IsOrdered) {
9658       if (State.VF.isVector())
9659         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9660                                         PrevInChain);
9661       else
9662         NewRed = State.Builder.CreateBinOp(
9663             (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(),
9664             PrevInChain, NewVecOp);
9665       PrevInChain = NewRed;
9666     } else {
9667       PrevInChain = State.get(getChainOp(), Part);
9668       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9669     }
9670     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9671       NextInChain =
9672           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9673                          NewRed, PrevInChain);
9674     } else if (IsOrdered)
9675       NextInChain = NewRed;
9676     else {
9677       NextInChain = State.Builder.CreateBinOp(
9678           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9679           PrevInChain);
9680     }
9681     State.set(this, NextInChain, Part);
9682   }
9683 }
9684 
9685 void VPReplicateRecipe::execute(VPTransformState &State) {
9686   if (State.Instance) { // Generate a single instance.
9687     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9688     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9689                                     *State.Instance, IsPredicated, State);
9690     // Insert scalar instance packing it into a vector.
9691     if (AlsoPack && State.VF.isVector()) {
9692       // If we're constructing lane 0, initialize to start from poison.
9693       if (State.Instance->Lane.isFirstLane()) {
9694         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9695         Value *Poison = PoisonValue::get(
9696             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9697         State.set(this, Poison, State.Instance->Part);
9698       }
9699       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9700     }
9701     return;
9702   }
9703 
9704   // Generate scalar instances for all VF lanes of all UF parts, unless the
9705   // instruction is uniform inwhich case generate only the first lane for each
9706   // of the UF parts.
9707   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9708   assert((!State.VF.isScalable() || IsUniform) &&
9709          "Can't scalarize a scalable vector");
9710   for (unsigned Part = 0; Part < State.UF; ++Part)
9711     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9712       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9713                                       VPIteration(Part, Lane), IsPredicated,
9714                                       State);
9715 }
9716 
9717 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9718   assert(State.Instance && "Branch on Mask works only on single instance.");
9719 
9720   unsigned Part = State.Instance->Part;
9721   unsigned Lane = State.Instance->Lane.getKnownLane();
9722 
9723   Value *ConditionBit = nullptr;
9724   VPValue *BlockInMask = getMask();
9725   if (BlockInMask) {
9726     ConditionBit = State.get(BlockInMask, Part);
9727     if (ConditionBit->getType()->isVectorTy())
9728       ConditionBit = State.Builder.CreateExtractElement(
9729           ConditionBit, State.Builder.getInt32(Lane));
9730   } else // Block in mask is all-one.
9731     ConditionBit = State.Builder.getTrue();
9732 
9733   // Replace the temporary unreachable terminator with a new conditional branch,
9734   // whose two destinations will be set later when they are created.
9735   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9736   assert(isa<UnreachableInst>(CurrentTerminator) &&
9737          "Expected to replace unreachable terminator with conditional branch.");
9738   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9739   CondBr->setSuccessor(0, nullptr);
9740   ReplaceInstWithInst(CurrentTerminator, CondBr);
9741 }
9742 
9743 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9744   assert(State.Instance && "Predicated instruction PHI works per instance.");
9745   Instruction *ScalarPredInst =
9746       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9747   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9748   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9749   assert(PredicatingBB && "Predicated block has no single predecessor.");
9750   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9751          "operand must be VPReplicateRecipe");
9752 
9753   // By current pack/unpack logic we need to generate only a single phi node: if
9754   // a vector value for the predicated instruction exists at this point it means
9755   // the instruction has vector users only, and a phi for the vector value is
9756   // needed. In this case the recipe of the predicated instruction is marked to
9757   // also do that packing, thereby "hoisting" the insert-element sequence.
9758   // Otherwise, a phi node for the scalar value is needed.
9759   unsigned Part = State.Instance->Part;
9760   if (State.hasVectorValue(getOperand(0), Part)) {
9761     Value *VectorValue = State.get(getOperand(0), Part);
9762     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9763     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9764     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9765     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9766     if (State.hasVectorValue(this, Part))
9767       State.reset(this, VPhi, Part);
9768     else
9769       State.set(this, VPhi, Part);
9770     // NOTE: Currently we need to update the value of the operand, so the next
9771     // predicated iteration inserts its generated value in the correct vector.
9772     State.reset(getOperand(0), VPhi, Part);
9773   } else {
9774     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9775     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9776     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9777                      PredicatingBB);
9778     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9779     if (State.hasScalarValue(this, *State.Instance))
9780       State.reset(this, Phi, *State.Instance);
9781     else
9782       State.set(this, Phi, *State.Instance);
9783     // NOTE: Currently we need to update the value of the operand, so the next
9784     // predicated iteration inserts its generated value in the correct vector.
9785     State.reset(getOperand(0), Phi, *State.Instance);
9786   }
9787 }
9788 
9789 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9790   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9791   State.ILV->vectorizeMemoryInstruction(
9792       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9793       StoredValue, getMask());
9794 }
9795 
9796 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9797 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9798 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9799 // for predication.
9800 static ScalarEpilogueLowering getScalarEpilogueLowering(
9801     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9802     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9803     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9804     LoopVectorizationLegality &LVL) {
9805   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9806   // don't look at hints or options, and don't request a scalar epilogue.
9807   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9808   // LoopAccessInfo (due to code dependency and not being able to reliably get
9809   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9810   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9811   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9812   // back to the old way and vectorize with versioning when forced. See D81345.)
9813   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9814                                                       PGSOQueryType::IRPass) &&
9815                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9816     return CM_ScalarEpilogueNotAllowedOptSize;
9817 
9818   // 2) If set, obey the directives
9819   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9820     switch (PreferPredicateOverEpilogue) {
9821     case PreferPredicateTy::ScalarEpilogue:
9822       return CM_ScalarEpilogueAllowed;
9823     case PreferPredicateTy::PredicateElseScalarEpilogue:
9824       return CM_ScalarEpilogueNotNeededUsePredicate;
9825     case PreferPredicateTy::PredicateOrDontVectorize:
9826       return CM_ScalarEpilogueNotAllowedUsePredicate;
9827     };
9828   }
9829 
9830   // 3) If set, obey the hints
9831   switch (Hints.getPredicate()) {
9832   case LoopVectorizeHints::FK_Enabled:
9833     return CM_ScalarEpilogueNotNeededUsePredicate;
9834   case LoopVectorizeHints::FK_Disabled:
9835     return CM_ScalarEpilogueAllowed;
9836   };
9837 
9838   // 4) if the TTI hook indicates this is profitable, request predication.
9839   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9840                                        LVL.getLAI()))
9841     return CM_ScalarEpilogueNotNeededUsePredicate;
9842 
9843   return CM_ScalarEpilogueAllowed;
9844 }
9845 
9846 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9847   // If Values have been set for this Def return the one relevant for \p Part.
9848   if (hasVectorValue(Def, Part))
9849     return Data.PerPartOutput[Def][Part];
9850 
9851   if (!hasScalarValue(Def, {Part, 0})) {
9852     Value *IRV = Def->getLiveInIRValue();
9853     Value *B = ILV->getBroadcastInstrs(IRV);
9854     set(Def, B, Part);
9855     return B;
9856   }
9857 
9858   Value *ScalarValue = get(Def, {Part, 0});
9859   // If we aren't vectorizing, we can just copy the scalar map values over
9860   // to the vector map.
9861   if (VF.isScalar()) {
9862     set(Def, ScalarValue, Part);
9863     return ScalarValue;
9864   }
9865 
9866   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9867   bool IsUniform = RepR && RepR->isUniform();
9868 
9869   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9870   // Check if there is a scalar value for the selected lane.
9871   if (!hasScalarValue(Def, {Part, LastLane})) {
9872     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9873     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9874            "unexpected recipe found to be invariant");
9875     IsUniform = true;
9876     LastLane = 0;
9877   }
9878 
9879   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9880   // Set the insert point after the last scalarized instruction or after the
9881   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
9882   // will directly follow the scalar definitions.
9883   auto OldIP = Builder.saveIP();
9884   auto NewIP =
9885       isa<PHINode>(LastInst)
9886           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
9887           : std::next(BasicBlock::iterator(LastInst));
9888   Builder.SetInsertPoint(&*NewIP);
9889 
9890   // However, if we are vectorizing, we need to construct the vector values.
9891   // If the value is known to be uniform after vectorization, we can just
9892   // broadcast the scalar value corresponding to lane zero for each unroll
9893   // iteration. Otherwise, we construct the vector values using
9894   // insertelement instructions. Since the resulting vectors are stored in
9895   // State, we will only generate the insertelements once.
9896   Value *VectorValue = nullptr;
9897   if (IsUniform) {
9898     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9899     set(Def, VectorValue, Part);
9900   } else {
9901     // Initialize packing with insertelements to start from undef.
9902     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9903     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9904     set(Def, Undef, Part);
9905     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9906       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9907     VectorValue = get(Def, Part);
9908   }
9909   Builder.restoreIP(OldIP);
9910   return VectorValue;
9911 }
9912 
9913 // Process the loop in the VPlan-native vectorization path. This path builds
9914 // VPlan upfront in the vectorization pipeline, which allows to apply
9915 // VPlan-to-VPlan transformations from the very beginning without modifying the
9916 // input LLVM IR.
9917 static bool processLoopInVPlanNativePath(
9918     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9919     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9920     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9921     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9922     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9923     LoopVectorizationRequirements &Requirements) {
9924 
9925   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9926     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9927     return false;
9928   }
9929   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9930   Function *F = L->getHeader()->getParent();
9931   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9932 
9933   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9934       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9935 
9936   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9937                                 &Hints, IAI);
9938   // Use the planner for outer loop vectorization.
9939   // TODO: CM is not used at this point inside the planner. Turn CM into an
9940   // optional argument if we don't need it in the future.
9941   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
9942                                Requirements, ORE);
9943 
9944   // Get user vectorization factor.
9945   ElementCount UserVF = Hints.getWidth();
9946 
9947   CM.collectElementTypesForWidening();
9948 
9949   // Plan how to best vectorize, return the best VF and its cost.
9950   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9951 
9952   // If we are stress testing VPlan builds, do not attempt to generate vector
9953   // code. Masked vector code generation support will follow soon.
9954   // Also, do not attempt to vectorize if no vector code will be produced.
9955   if (VPlanBuildStressTest || EnableVPlanPredication ||
9956       VectorizationFactor::Disabled() == VF)
9957     return false;
9958 
9959   LVP.setBestPlan(VF.Width, 1);
9960 
9961   {
9962     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9963                              F->getParent()->getDataLayout());
9964     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9965                            &CM, BFI, PSI, Checks);
9966     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9967                       << L->getHeader()->getParent()->getName() << "\"\n");
9968     LVP.executePlan(LB, DT);
9969   }
9970 
9971   // Mark the loop as already vectorized to avoid vectorizing again.
9972   Hints.setAlreadyVectorized();
9973   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9974   return true;
9975 }
9976 
9977 // Emit a remark if there are stores to floats that required a floating point
9978 // extension. If the vectorized loop was generated with floating point there
9979 // will be a performance penalty from the conversion overhead and the change in
9980 // the vector width.
9981 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9982   SmallVector<Instruction *, 4> Worklist;
9983   for (BasicBlock *BB : L->getBlocks()) {
9984     for (Instruction &Inst : *BB) {
9985       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9986         if (S->getValueOperand()->getType()->isFloatTy())
9987           Worklist.push_back(S);
9988       }
9989     }
9990   }
9991 
9992   // Traverse the floating point stores upwards searching, for floating point
9993   // conversions.
9994   SmallPtrSet<const Instruction *, 4> Visited;
9995   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9996   while (!Worklist.empty()) {
9997     auto *I = Worklist.pop_back_val();
9998     if (!L->contains(I))
9999       continue;
10000     if (!Visited.insert(I).second)
10001       continue;
10002 
10003     // Emit a remark if the floating point store required a floating
10004     // point conversion.
10005     // TODO: More work could be done to identify the root cause such as a
10006     // constant or a function return type and point the user to it.
10007     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10008       ORE->emit([&]() {
10009         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10010                                           I->getDebugLoc(), L->getHeader())
10011                << "floating point conversion changes vector width. "
10012                << "Mixed floating point precision requires an up/down "
10013                << "cast that will negatively impact performance.";
10014       });
10015 
10016     for (Use &Op : I->operands())
10017       if (auto *OpI = dyn_cast<Instruction>(Op))
10018         Worklist.push_back(OpI);
10019   }
10020 }
10021 
10022 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10023     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10024                                !EnableLoopInterleaving),
10025       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10026                               !EnableLoopVectorization) {}
10027 
10028 bool LoopVectorizePass::processLoop(Loop *L) {
10029   assert((EnableVPlanNativePath || L->isInnermost()) &&
10030          "VPlan-native path is not enabled. Only process inner loops.");
10031 
10032 #ifndef NDEBUG
10033   const std::string DebugLocStr = getDebugLocString(L);
10034 #endif /* NDEBUG */
10035 
10036   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
10037                     << L->getHeader()->getParent()->getName() << "\" from "
10038                     << DebugLocStr << "\n");
10039 
10040   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
10041 
10042   LLVM_DEBUG(
10043       dbgs() << "LV: Loop hints:"
10044              << " force="
10045              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10046                      ? "disabled"
10047                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10048                             ? "enabled"
10049                             : "?"))
10050              << " width=" << Hints.getWidth()
10051              << " interleave=" << Hints.getInterleave() << "\n");
10052 
10053   // Function containing loop
10054   Function *F = L->getHeader()->getParent();
10055 
10056   // Looking at the diagnostic output is the only way to determine if a loop
10057   // was vectorized (other than looking at the IR or machine code), so it
10058   // is important to generate an optimization remark for each loop. Most of
10059   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10060   // generated as OptimizationRemark and OptimizationRemarkMissed are
10061   // less verbose reporting vectorized loops and unvectorized loops that may
10062   // benefit from vectorization, respectively.
10063 
10064   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10065     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10066     return false;
10067   }
10068 
10069   PredicatedScalarEvolution PSE(*SE, *L);
10070 
10071   // Check if it is legal to vectorize the loop.
10072   LoopVectorizationRequirements Requirements;
10073   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10074                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10075   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10076     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10077     Hints.emitRemarkWithHints();
10078     return false;
10079   }
10080 
10081   // Check the function attributes and profiles to find out if this function
10082   // should be optimized for size.
10083   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10084       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10085 
10086   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10087   // here. They may require CFG and instruction level transformations before
10088   // even evaluating whether vectorization is profitable. Since we cannot modify
10089   // the incoming IR, we need to build VPlan upfront in the vectorization
10090   // pipeline.
10091   if (!L->isInnermost())
10092     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10093                                         ORE, BFI, PSI, Hints, Requirements);
10094 
10095   assert(L->isInnermost() && "Inner loop expected.");
10096 
10097   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10098   // count by optimizing for size, to minimize overheads.
10099   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10100   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10101     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10102                       << "This loop is worth vectorizing only if no scalar "
10103                       << "iteration overheads are incurred.");
10104     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10105       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10106     else {
10107       LLVM_DEBUG(dbgs() << "\n");
10108       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10109     }
10110   }
10111 
10112   // Check the function attributes to see if implicit floats are allowed.
10113   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10114   // an integer loop and the vector instructions selected are purely integer
10115   // vector instructions?
10116   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10117     reportVectorizationFailure(
10118         "Can't vectorize when the NoImplicitFloat attribute is used",
10119         "loop not vectorized due to NoImplicitFloat attribute",
10120         "NoImplicitFloat", ORE, L);
10121     Hints.emitRemarkWithHints();
10122     return false;
10123   }
10124 
10125   // Check if the target supports potentially unsafe FP vectorization.
10126   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10127   // for the target we're vectorizing for, to make sure none of the
10128   // additional fp-math flags can help.
10129   if (Hints.isPotentiallyUnsafe() &&
10130       TTI->isFPVectorizationPotentiallyUnsafe()) {
10131     reportVectorizationFailure(
10132         "Potentially unsafe FP op prevents vectorization",
10133         "loop not vectorized due to unsafe FP support.",
10134         "UnsafeFP", ORE, L);
10135     Hints.emitRemarkWithHints();
10136     return false;
10137   }
10138 
10139   if (!LVL.canVectorizeFPMath(EnableStrictReductions)) {
10140     ORE->emit([&]() {
10141       auto *ExactFPMathInst = Requirements.getExactFPInst();
10142       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10143                                                  ExactFPMathInst->getDebugLoc(),
10144                                                  ExactFPMathInst->getParent())
10145              << "loop not vectorized: cannot prove it is safe to reorder "
10146                 "floating-point operations";
10147     });
10148     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10149                          "reorder floating-point operations\n");
10150     Hints.emitRemarkWithHints();
10151     return false;
10152   }
10153 
10154   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10155   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10156 
10157   // If an override option has been passed in for interleaved accesses, use it.
10158   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10159     UseInterleaved = EnableInterleavedMemAccesses;
10160 
10161   // Analyze interleaved memory accesses.
10162   if (UseInterleaved) {
10163     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10164   }
10165 
10166   // Use the cost model.
10167   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10168                                 F, &Hints, IAI);
10169   CM.collectValuesToIgnore();
10170   CM.collectElementTypesForWidening();
10171 
10172   // Use the planner for vectorization.
10173   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10174                                Requirements, ORE);
10175 
10176   // Get user vectorization factor and interleave count.
10177   ElementCount UserVF = Hints.getWidth();
10178   unsigned UserIC = Hints.getInterleave();
10179 
10180   // Plan how to best vectorize, return the best VF and its cost.
10181   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10182 
10183   VectorizationFactor VF = VectorizationFactor::Disabled();
10184   unsigned IC = 1;
10185 
10186   if (MaybeVF) {
10187     VF = *MaybeVF;
10188     // Select the interleave count.
10189     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10190   }
10191 
10192   // Identify the diagnostic messages that should be produced.
10193   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10194   bool VectorizeLoop = true, InterleaveLoop = true;
10195   if (VF.Width.isScalar()) {
10196     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10197     VecDiagMsg = std::make_pair(
10198         "VectorizationNotBeneficial",
10199         "the cost-model indicates that vectorization is not beneficial");
10200     VectorizeLoop = false;
10201   }
10202 
10203   if (!MaybeVF && UserIC > 1) {
10204     // Tell the user interleaving was avoided up-front, despite being explicitly
10205     // requested.
10206     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10207                          "interleaving should be avoided up front\n");
10208     IntDiagMsg = std::make_pair(
10209         "InterleavingAvoided",
10210         "Ignoring UserIC, because interleaving was avoided up front");
10211     InterleaveLoop = false;
10212   } else if (IC == 1 && UserIC <= 1) {
10213     // Tell the user interleaving is not beneficial.
10214     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10215     IntDiagMsg = std::make_pair(
10216         "InterleavingNotBeneficial",
10217         "the cost-model indicates that interleaving is not beneficial");
10218     InterleaveLoop = false;
10219     if (UserIC == 1) {
10220       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10221       IntDiagMsg.second +=
10222           " and is explicitly disabled or interleave count is set to 1";
10223     }
10224   } else if (IC > 1 && UserIC == 1) {
10225     // Tell the user interleaving is beneficial, but it explicitly disabled.
10226     LLVM_DEBUG(
10227         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10228     IntDiagMsg = std::make_pair(
10229         "InterleavingBeneficialButDisabled",
10230         "the cost-model indicates that interleaving is beneficial "
10231         "but is explicitly disabled or interleave count is set to 1");
10232     InterleaveLoop = false;
10233   }
10234 
10235   // Override IC if user provided an interleave count.
10236   IC = UserIC > 0 ? UserIC : IC;
10237 
10238   // Emit diagnostic messages, if any.
10239   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10240   if (!VectorizeLoop && !InterleaveLoop) {
10241     // Do not vectorize or interleaving the loop.
10242     ORE->emit([&]() {
10243       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10244                                       L->getStartLoc(), L->getHeader())
10245              << VecDiagMsg.second;
10246     });
10247     ORE->emit([&]() {
10248       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10249                                       L->getStartLoc(), L->getHeader())
10250              << IntDiagMsg.second;
10251     });
10252     return false;
10253   } else if (!VectorizeLoop && InterleaveLoop) {
10254     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10255     ORE->emit([&]() {
10256       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10257                                         L->getStartLoc(), L->getHeader())
10258              << VecDiagMsg.second;
10259     });
10260   } else if (VectorizeLoop && !InterleaveLoop) {
10261     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10262                       << ") in " << DebugLocStr << '\n');
10263     ORE->emit([&]() {
10264       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10265                                         L->getStartLoc(), L->getHeader())
10266              << IntDiagMsg.second;
10267     });
10268   } else if (VectorizeLoop && InterleaveLoop) {
10269     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10270                       << ") in " << DebugLocStr << '\n');
10271     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10272   }
10273 
10274   bool DisableRuntimeUnroll = false;
10275   MDNode *OrigLoopID = L->getLoopID();
10276   {
10277     // Optimistically generate runtime checks. Drop them if they turn out to not
10278     // be profitable. Limit the scope of Checks, so the cleanup happens
10279     // immediately after vector codegeneration is done.
10280     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10281                              F->getParent()->getDataLayout());
10282     if (!VF.Width.isScalar() || IC > 1)
10283       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10284     LVP.setBestPlan(VF.Width, IC);
10285 
10286     using namespace ore;
10287     if (!VectorizeLoop) {
10288       assert(IC > 1 && "interleave count should not be 1 or 0");
10289       // If we decided that it is not legal to vectorize the loop, then
10290       // interleave it.
10291       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10292                                  &CM, BFI, PSI, Checks);
10293       LVP.executePlan(Unroller, DT);
10294 
10295       ORE->emit([&]() {
10296         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10297                                   L->getHeader())
10298                << "interleaved loop (interleaved count: "
10299                << NV("InterleaveCount", IC) << ")";
10300       });
10301     } else {
10302       // If we decided that it is *legal* to vectorize the loop, then do it.
10303 
10304       // Consider vectorizing the epilogue too if it's profitable.
10305       VectorizationFactor EpilogueVF =
10306           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10307       if (EpilogueVF.Width.isVector()) {
10308 
10309         // The first pass vectorizes the main loop and creates a scalar epilogue
10310         // to be vectorized by executing the plan (potentially with a different
10311         // factor) again shortly afterwards.
10312         EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
10313                                           EpilogueVF.Width.getKnownMinValue(),
10314                                           1);
10315         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10316                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10317 
10318         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
10319         LVP.executePlan(MainILV, DT);
10320         ++LoopsVectorized;
10321 
10322         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10323         formLCSSARecursively(*L, *DT, LI, SE);
10324 
10325         // Second pass vectorizes the epilogue and adjusts the control flow
10326         // edges from the first pass.
10327         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
10328         EPI.MainLoopVF = EPI.EpilogueVF;
10329         EPI.MainLoopUF = EPI.EpilogueUF;
10330         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10331                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10332                                                  Checks);
10333         LVP.executePlan(EpilogILV, DT);
10334         ++LoopsEpilogueVectorized;
10335 
10336         if (!MainILV.areSafetyChecksAdded())
10337           DisableRuntimeUnroll = true;
10338       } else {
10339         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10340                                &LVL, &CM, BFI, PSI, Checks);
10341         LVP.executePlan(LB, DT);
10342         ++LoopsVectorized;
10343 
10344         // Add metadata to disable runtime unrolling a scalar loop when there
10345         // are no runtime checks about strides and memory. A scalar loop that is
10346         // rarely used is not worth unrolling.
10347         if (!LB.areSafetyChecksAdded())
10348           DisableRuntimeUnroll = true;
10349       }
10350       // Report the vectorization decision.
10351       ORE->emit([&]() {
10352         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10353                                   L->getHeader())
10354                << "vectorized loop (vectorization width: "
10355                << NV("VectorizationFactor", VF.Width)
10356                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10357       });
10358     }
10359 
10360     if (ORE->allowExtraAnalysis(LV_NAME))
10361       checkMixedPrecision(L, ORE);
10362   }
10363 
10364   Optional<MDNode *> RemainderLoopID =
10365       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10366                                       LLVMLoopVectorizeFollowupEpilogue});
10367   if (RemainderLoopID.hasValue()) {
10368     L->setLoopID(RemainderLoopID.getValue());
10369   } else {
10370     if (DisableRuntimeUnroll)
10371       AddRuntimeUnrollDisableMetaData(L);
10372 
10373     // Mark the loop as already vectorized to avoid vectorizing again.
10374     Hints.setAlreadyVectorized();
10375   }
10376 
10377   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10378   return true;
10379 }
10380 
10381 LoopVectorizeResult LoopVectorizePass::runImpl(
10382     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10383     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10384     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10385     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10386     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10387   SE = &SE_;
10388   LI = &LI_;
10389   TTI = &TTI_;
10390   DT = &DT_;
10391   BFI = &BFI_;
10392   TLI = TLI_;
10393   AA = &AA_;
10394   AC = &AC_;
10395   GetLAA = &GetLAA_;
10396   DB = &DB_;
10397   ORE = &ORE_;
10398   PSI = PSI_;
10399 
10400   // Don't attempt if
10401   // 1. the target claims to have no vector registers, and
10402   // 2. interleaving won't help ILP.
10403   //
10404   // The second condition is necessary because, even if the target has no
10405   // vector registers, loop vectorization may still enable scalar
10406   // interleaving.
10407   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10408       TTI->getMaxInterleaveFactor(1) < 2)
10409     return LoopVectorizeResult(false, false);
10410 
10411   bool Changed = false, CFGChanged = false;
10412 
10413   // The vectorizer requires loops to be in simplified form.
10414   // Since simplification may add new inner loops, it has to run before the
10415   // legality and profitability checks. This means running the loop vectorizer
10416   // will simplify all loops, regardless of whether anything end up being
10417   // vectorized.
10418   for (auto &L : *LI)
10419     Changed |= CFGChanged |=
10420         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10421 
10422   // Build up a worklist of inner-loops to vectorize. This is necessary as
10423   // the act of vectorizing or partially unrolling a loop creates new loops
10424   // and can invalidate iterators across the loops.
10425   SmallVector<Loop *, 8> Worklist;
10426 
10427   for (Loop *L : *LI)
10428     collectSupportedLoops(*L, LI, ORE, Worklist);
10429 
10430   LoopsAnalyzed += Worklist.size();
10431 
10432   // Now walk the identified inner loops.
10433   while (!Worklist.empty()) {
10434     Loop *L = Worklist.pop_back_val();
10435 
10436     // For the inner loops we actually process, form LCSSA to simplify the
10437     // transform.
10438     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10439 
10440     Changed |= CFGChanged |= processLoop(L);
10441   }
10442 
10443   // Process each loop nest in the function.
10444   return LoopVectorizeResult(Changed, CFGChanged);
10445 }
10446 
10447 PreservedAnalyses LoopVectorizePass::run(Function &F,
10448                                          FunctionAnalysisManager &AM) {
10449     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10450     auto &LI = AM.getResult<LoopAnalysis>(F);
10451     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10452     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10453     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10454     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10455     auto &AA = AM.getResult<AAManager>(F);
10456     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10457     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10458     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10459     MemorySSA *MSSA = EnableMSSALoopDependency
10460                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
10461                           : nullptr;
10462 
10463     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10464     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10465         [&](Loop &L) -> const LoopAccessInfo & {
10466       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
10467                                         TLI, TTI, nullptr, MSSA};
10468       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10469     };
10470     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10471     ProfileSummaryInfo *PSI =
10472         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10473     LoopVectorizeResult Result =
10474         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10475     if (!Result.MadeAnyChange)
10476       return PreservedAnalyses::all();
10477     PreservedAnalyses PA;
10478 
10479     // We currently do not preserve loopinfo/dominator analyses with outer loop
10480     // vectorization. Until this is addressed, mark these analyses as preserved
10481     // only for non-VPlan-native path.
10482     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10483     if (!EnableVPlanNativePath) {
10484       PA.preserve<LoopAnalysis>();
10485       PA.preserve<DominatorTreeAnalysis>();
10486     }
10487     if (!Result.MadeCFGChange)
10488       PA.preserveSet<CFGAnalyses>();
10489     return PA;
10490 }
10491