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 "VPlanTransforms.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DenseMapInfo.h"
66 #include "llvm/ADT/Hashing.h"
67 #include "llvm/ADT/MapVector.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallPtrSet.h"
72 #include "llvm/ADT/SmallSet.h"
73 #include "llvm/ADT/SmallVector.h"
74 #include "llvm/ADT/Statistic.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/ADT/Twine.h"
77 #include "llvm/ADT/iterator_range.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/BasicAliasAnalysis.h"
80 #include "llvm/Analysis/BlockFrequencyInfo.h"
81 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/CodeMetrics.h"
83 #include "llvm/Analysis/DemandedBits.h"
84 #include "llvm/Analysis/GlobalsModRef.h"
85 #include "llvm/Analysis/LoopAccessAnalysis.h"
86 #include "llvm/Analysis/LoopAnalysisManager.h"
87 #include "llvm/Analysis/LoopInfo.h"
88 #include "llvm/Analysis/LoopIterator.h"
89 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
90 #include "llvm/Analysis/ProfileSummaryInfo.h"
91 #include "llvm/Analysis/ScalarEvolution.h"
92 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
93 #include "llvm/Analysis/TargetLibraryInfo.h"
94 #include "llvm/Analysis/TargetTransformInfo.h"
95 #include "llvm/Analysis/ValueTracking.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/Metadata.h"
116 #include "llvm/IR/Module.h"
117 #include "llvm/IR/Operator.h"
118 #include "llvm/IR/PatternMatch.h"
119 #include "llvm/IR/Type.h"
120 #include "llvm/IR/Use.h"
121 #include "llvm/IR/User.h"
122 #include "llvm/IR/Value.h"
123 #include "llvm/IR/ValueHandle.h"
124 #include "llvm/IR/Verifier.h"
125 #include "llvm/InitializePasses.h"
126 #include "llvm/Pass.h"
127 #include "llvm/Support/Casting.h"
128 #include "llvm/Support/CommandLine.h"
129 #include "llvm/Support/Compiler.h"
130 #include "llvm/Support/Debug.h"
131 #include "llvm/Support/ErrorHandling.h"
132 #include "llvm/Support/InstructionCost.h"
133 #include "llvm/Support/MathExtras.h"
134 #include "llvm/Support/raw_ostream.h"
135 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
136 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
137 #include "llvm/Transforms/Utils/LoopSimplify.h"
138 #include "llvm/Transforms/Utils/LoopUtils.h"
139 #include "llvm/Transforms/Utils/LoopVersioning.h"
140 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
141 #include "llvm/Transforms/Utils/SizeOpts.h"
142 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
143 #include <algorithm>
144 #include <cassert>
145 #include <cstdint>
146 #include <functional>
147 #include <iterator>
148 #include <limits>
149 #include <map>
150 #include <memory>
151 #include <string>
152 #include <tuple>
153 #include <utility>
154 
155 using namespace llvm;
156 
157 #define LV_NAME "loop-vectorize"
158 #define DEBUG_TYPE LV_NAME
159 
160 #ifndef NDEBUG
161 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
162 #endif
163 
164 /// @{
165 /// Metadata attribute names
166 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
167 const char LLVMLoopVectorizeFollowupVectorized[] =
168     "llvm.loop.vectorize.followup_vectorized";
169 const char LLVMLoopVectorizeFollowupEpilogue[] =
170     "llvm.loop.vectorize.followup_epilogue";
171 /// @}
172 
173 STATISTIC(LoopsVectorized, "Number of loops vectorized");
174 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
175 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
176 
177 static cl::opt<bool> EnableEpilogueVectorization(
178     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
179     cl::desc("Enable vectorization of epilogue loops."));
180 
181 static cl::opt<unsigned> EpilogueVectorizationForceVF(
182     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
183     cl::desc("When epilogue vectorization is enabled, and a value greater than "
184              "1 is specified, forces the given VF for all applicable epilogue "
185              "loops."));
186 
187 static cl::opt<unsigned> EpilogueVectorizationMinVF(
188     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
189     cl::desc("Only loops with vectorization factor equal to or larger than "
190              "the specified value are considered for epilogue vectorization."));
191 
192 /// Loops with a known constant trip count below this number are vectorized only
193 /// if no scalar iteration overheads are incurred.
194 static cl::opt<unsigned> TinyTripCountVectorThreshold(
195     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
196     cl::desc("Loops with a constant trip count that is smaller than this "
197              "value are vectorized only if no scalar iteration overheads "
198              "are incurred."));
199 
200 static cl::opt<unsigned> VectorizeMemoryCheckThreshold(
201     "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
202     cl::desc("The maximum allowed number of runtime memory checks"));
203 
204 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
205 // that predication is preferred, and this lists all options. I.e., the
206 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
207 // and predicate the instructions accordingly. If tail-folding fails, there are
208 // different fallback strategies depending on these values:
209 namespace PreferPredicateTy {
210   enum Option {
211     ScalarEpilogue = 0,
212     PredicateElseScalarEpilogue,
213     PredicateOrDontVectorize
214   };
215 } // namespace PreferPredicateTy
216 
217 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
218     "prefer-predicate-over-epilogue",
219     cl::init(PreferPredicateTy::ScalarEpilogue),
220     cl::Hidden,
221     cl::desc("Tail-folding and predication preferences over creating a scalar "
222              "epilogue loop."),
223     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
224                          "scalar-epilogue",
225                          "Don't tail-predicate loops, create scalar epilogue"),
226               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
227                          "predicate-else-scalar-epilogue",
228                          "prefer tail-folding, create scalar epilogue if tail "
229                          "folding fails."),
230               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
231                          "predicate-dont-vectorize",
232                          "prefers tail-folding, don't attempt vectorization if "
233                          "tail-folding fails.")));
234 
235 static cl::opt<bool> MaximizeBandwidth(
236     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
237     cl::desc("Maximize bandwidth when selecting vectorization factor which "
238              "will be determined by the smallest type in loop."));
239 
240 static cl::opt<bool> EnableInterleavedMemAccesses(
241     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
242     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
243 
244 /// An interleave-group may need masking if it resides in a block that needs
245 /// predication, or in order to mask away gaps.
246 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
247     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
248     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
249 
250 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
251     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
252     cl::desc("We don't interleave loops with a estimated constant trip count "
253              "below this number"));
254 
255 static cl::opt<unsigned> ForceTargetNumScalarRegs(
256     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
257     cl::desc("A flag that overrides the target's number of scalar registers."));
258 
259 static cl::opt<unsigned> ForceTargetNumVectorRegs(
260     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
261     cl::desc("A flag that overrides the target's number of vector registers."));
262 
263 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
264     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
265     cl::desc("A flag that overrides the target's max interleave factor for "
266              "scalar loops."));
267 
268 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
269     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
270     cl::desc("A flag that overrides the target's max interleave factor for "
271              "vectorized loops."));
272 
273 static cl::opt<unsigned> ForceTargetInstructionCost(
274     "force-target-instruction-cost", cl::init(0), cl::Hidden,
275     cl::desc("A flag that overrides the target's expected cost for "
276              "an instruction to a single constant value. Mostly "
277              "useful for getting consistent testing."));
278 
279 static cl::opt<bool> ForceTargetSupportsScalableVectors(
280     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
281     cl::desc(
282         "Pretend that scalable vectors are supported, even if the target does "
283         "not support them. This flag should only be used for testing."));
284 
285 static cl::opt<unsigned> SmallLoopCost(
286     "small-loop-cost", cl::init(20), cl::Hidden,
287     cl::desc(
288         "The cost of a loop that is considered 'small' by the interleaver."));
289 
290 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
291     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
292     cl::desc("Enable the use of the block frequency analysis to access PGO "
293              "heuristics minimizing code growth in cold regions and being more "
294              "aggressive in hot regions."));
295 
296 // Runtime interleave loops for load/store throughput.
297 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
298     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
299     cl::desc(
300         "Enable runtime interleaving until load/store ports are saturated"));
301 
302 /// Interleave small loops with scalar reductions.
303 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
304     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
305     cl::desc("Enable interleaving for loops with small iteration counts that "
306              "contain scalar reductions to expose ILP."));
307 
308 /// The number of stores in a loop that are allowed to need predication.
309 static cl::opt<unsigned> NumberOfStoresToPredicate(
310     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
311     cl::desc("Max number of stores to be predicated behind an if."));
312 
313 static cl::opt<bool> EnableIndVarRegisterHeur(
314     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
315     cl::desc("Count the induction variable only once when interleaving"));
316 
317 static cl::opt<bool> EnableCondStoresVectorization(
318     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
319     cl::desc("Enable if predication of stores during vectorization."));
320 
321 static cl::opt<unsigned> MaxNestedScalarReductionIC(
322     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
323     cl::desc("The maximum interleave count to use when interleaving a scalar "
324              "reduction in a nested loop."));
325 
326 static cl::opt<bool>
327     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
328                            cl::Hidden,
329                            cl::desc("Prefer in-loop vector reductions, "
330                                     "overriding the targets preference."));
331 
332 static cl::opt<bool> ForceOrderedReductions(
333     "force-ordered-reductions", cl::init(false), cl::Hidden,
334     cl::desc("Enable the vectorisation of loops with in-order (strict) "
335              "FP reductions"));
336 
337 static cl::opt<bool> PreferPredicatedReductionSelect(
338     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
339     cl::desc(
340         "Prefer predicating a reduction operation over an after loop select."));
341 
342 cl::opt<bool> EnableVPlanNativePath(
343     "enable-vplan-native-path", cl::init(false), cl::Hidden,
344     cl::desc("Enable VPlan-native vectorization path with "
345              "support for outer loop vectorization."));
346 
347 // This flag enables the stress testing of the VPlan H-CFG construction in the
348 // VPlan-native vectorization path. It must be used in conjuction with
349 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
350 // verification of the H-CFGs built.
351 static cl::opt<bool> VPlanBuildStressTest(
352     "vplan-build-stress-test", cl::init(false), cl::Hidden,
353     cl::desc(
354         "Build VPlan for every supported loop nest in the function and bail "
355         "out right after the build (stress test the VPlan H-CFG construction "
356         "in the VPlan-native vectorization path)."));
357 
358 cl::opt<bool> llvm::EnableLoopInterleaving(
359     "interleave-loops", cl::init(true), cl::Hidden,
360     cl::desc("Enable loop interleaving in Loop vectorization passes"));
361 cl::opt<bool> llvm::EnableLoopVectorization(
362     "vectorize-loops", cl::init(true), cl::Hidden,
363     cl::desc("Run the Loop vectorization passes"));
364 
365 cl::opt<bool> PrintVPlansInDotFormat(
366     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
367     cl::desc("Use dot format instead of plain text when dumping VPlans"));
368 
369 /// A helper function that returns true if the given type is irregular. The
370 /// type is irregular if its allocated size doesn't equal the store size of an
371 /// element of the corresponding vector type.
372 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
373   // Determine if an array of N elements of type Ty is "bitcast compatible"
374   // with a <N x Ty> vector.
375   // This is only true if there is no padding between the array elements.
376   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
377 }
378 
379 /// A helper function that returns the reciprocal of the block probability of
380 /// predicated blocks. If we return X, we are assuming the predicated block
381 /// will execute once for every X iterations of the loop header.
382 ///
383 /// TODO: We should use actual block probability here, if available. Currently,
384 ///       we always assume predicated blocks have a 50% chance of executing.
385 static unsigned getReciprocalPredBlockProb() { return 2; }
386 
387 /// A helper function that returns an integer or floating-point constant with
388 /// value C.
389 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
390   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
391                            : ConstantFP::get(Ty, C);
392 }
393 
394 /// Returns "best known" trip count for the specified loop \p L as defined by
395 /// the following procedure:
396 ///   1) Returns exact trip count if it is known.
397 ///   2) Returns expected trip count according to profile data if any.
398 ///   3) Returns upper bound estimate if it is known.
399 ///   4) Returns None if all of the above failed.
400 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
401   // Check if exact trip count is known.
402   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
403     return ExpectedTC;
404 
405   // Check if there is an expected trip count available from profile data.
406   if (LoopVectorizeWithBlockFrequency)
407     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
408       return EstimatedTC;
409 
410   // Check if upper bound estimate is known.
411   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
412     return ExpectedTC;
413 
414   return None;
415 }
416 
417 // Forward declare GeneratedRTChecks.
418 class GeneratedRTChecks;
419 
420 namespace llvm {
421 
422 AnalysisKey ShouldRunExtraVectorPasses::Key;
423 
424 /// InnerLoopVectorizer vectorizes loops which contain only one basic
425 /// block to a specified vectorization factor (VF).
426 /// This class performs the widening of scalars into vectors, or multiple
427 /// scalars. This class also implements the following features:
428 /// * It inserts an epilogue loop for handling loops that don't have iteration
429 ///   counts that are known to be a multiple of the vectorization factor.
430 /// * It handles the code generation for reduction variables.
431 /// * Scalarization (implementation using scalars) of un-vectorizable
432 ///   instructions.
433 /// InnerLoopVectorizer does not perform any vectorization-legality
434 /// checks, and relies on the caller to check for the different legality
435 /// aspects. The InnerLoopVectorizer relies on the
436 /// LoopVectorizationLegality class to provide information about the induction
437 /// and reduction variables that were found to a given vectorization factor.
438 class InnerLoopVectorizer {
439 public:
440   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
441                       LoopInfo *LI, DominatorTree *DT,
442                       const TargetLibraryInfo *TLI,
443                       const TargetTransformInfo *TTI, AssumptionCache *AC,
444                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
445                       ElementCount MinProfitableTripCount,
446                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
447                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
448                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
449       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
450         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
451         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
452         PSI(PSI), RTChecks(RTChecks) {
453     // Query this against the original loop and save it here because the profile
454     // of the original loop header may change as the transformation happens.
455     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
456         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
457 
458     if (MinProfitableTripCount.isZero())
459       this->MinProfitableTripCount = VecWidth;
460     else
461       this->MinProfitableTripCount = MinProfitableTripCount;
462   }
463 
464   virtual ~InnerLoopVectorizer() = default;
465 
466   /// Create a new empty loop that will contain vectorized instructions later
467   /// on, while the old loop will be used as the scalar remainder. Control flow
468   /// is generated around the vectorized (and scalar epilogue) loops consisting
469   /// of various checks and bypasses. Return the pre-header block of the new
470   /// loop and the start value for the canonical induction, if it is != 0. The
471   /// latter is the case when vectorizing the epilogue loop. In the case of
472   /// epilogue vectorization, this function is overriden to handle the more
473   /// complex control flow around the loops.
474   virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
475 
476   /// Widen a single call instruction within the innermost loop.
477   void widenCallInstruction(CallInst &CI, VPValue *Def, VPUser &ArgOperands,
478                             VPTransformState &State);
479 
480   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
481   void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
482 
483   // Return true if any runtime check is added.
484   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
485 
486   /// A type for vectorized values in the new loop. Each value from the
487   /// original loop, when vectorized, is represented by UF vector values in the
488   /// new unrolled loop, where UF is the unroll factor.
489   using VectorParts = SmallVector<Value *, 2>;
490 
491   /// A helper function to scalarize a single Instruction in the innermost loop.
492   /// Generates a sequence of scalar instances for each lane between \p MinLane
493   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
494   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
495   /// Instr's operands.
496   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
497                             const VPIteration &Instance, bool IfPredicateInstr,
498                             VPTransformState &State);
499 
500   /// Construct the vector value of a scalarized value \p V one lane at a time.
501   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
502                                  VPTransformState &State);
503 
504   /// Try to vectorize interleaved access group \p Group with the base address
505   /// given in \p Addr, optionally masking the vector operations if \p
506   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
507   /// values in the vectorized loop.
508   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
509                                 ArrayRef<VPValue *> VPDefs,
510                                 VPTransformState &State, VPValue *Addr,
511                                 ArrayRef<VPValue *> StoredValues,
512                                 VPValue *BlockInMask = nullptr);
513 
514   /// Fix the non-induction PHIs in \p Plan.
515   void fixNonInductionPHIs(VPlan &Plan, VPTransformState &State);
516 
517   /// Returns true if the reordering of FP operations is not allowed, but we are
518   /// able to vectorize with strict in-order reductions for the given RdxDesc.
519   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
520 
521   /// Create a broadcast instruction. This method generates a broadcast
522   /// instruction (shuffle) for loop invariant values and for the induction
523   /// value. If this is the induction variable then we extend it to N, N+1, ...
524   /// this is needed because each iteration in the loop corresponds to a SIMD
525   /// element.
526   virtual Value *getBroadcastInstrs(Value *V);
527 
528   // Returns the resume value (bc.merge.rdx) for a reduction as
529   // generated by fixReduction.
530   PHINode *getReductionResumeValue(const RecurrenceDescriptor &RdxDesc);
531 
532 protected:
533   friend class LoopVectorizationPlanner;
534 
535   /// A small list of PHINodes.
536   using PhiVector = SmallVector<PHINode *, 4>;
537 
538   /// A type for scalarized values in the new loop. Each value from the
539   /// original loop, when scalarized, is represented by UF x VF scalar values
540   /// in the new unrolled loop, where UF is the unroll factor and VF is the
541   /// vectorization factor.
542   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
543 
544   /// Set up the values of the IVs correctly when exiting the vector loop.
545   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
546                     Value *VectorTripCount, Value *EndValue,
547                     BasicBlock *MiddleBlock, BasicBlock *VectorHeader,
548                     VPlan &Plan);
549 
550   /// Handle all cross-iteration phis in the header.
551   void fixCrossIterationPHIs(VPTransformState &State);
552 
553   /// Create the exit value of first order recurrences in the middle block and
554   /// update their users.
555   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
556                                VPTransformState &State);
557 
558   /// Create code for the loop exit value of the reduction.
559   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
560 
561   /// Clear NSW/NUW flags from reduction instructions if necessary.
562   void clearReductionWrapFlags(VPReductionPHIRecipe *PhiR,
563                                VPTransformState &State);
564 
565   /// Iteratively sink the scalarized operands of a predicated instruction into
566   /// the block that was created for it.
567   void sinkScalarOperands(Instruction *PredInst);
568 
569   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
570   /// represented as.
571   void truncateToMinimalBitwidths(VPTransformState &State);
572 
573   /// Returns (and creates if needed) the original loop trip count.
574   Value *getOrCreateTripCount(BasicBlock *InsertBlock);
575 
576   /// Returns (and creates if needed) the trip count of the widened loop.
577   Value *getOrCreateVectorTripCount(BasicBlock *InsertBlock);
578 
579   /// Returns a bitcasted value to the requested vector type.
580   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
581   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
582                                 const DataLayout &DL);
583 
584   /// Emit a bypass check to see if the vector trip count is zero, including if
585   /// it overflows.
586   void emitIterationCountCheck(BasicBlock *Bypass);
587 
588   /// Emit a bypass check to see if all of the SCEV assumptions we've
589   /// had to make are correct. Returns the block containing the checks or
590   /// nullptr if no checks have been added.
591   BasicBlock *emitSCEVChecks(BasicBlock *Bypass);
592 
593   /// Emit bypass checks to check any memory assumptions we may have made.
594   /// Returns the block containing the checks or nullptr if no checks have been
595   /// added.
596   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass);
597 
598   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
599   /// vector loop preheader, middle block and scalar preheader.
600   void createVectorLoopSkeleton(StringRef Prefix);
601 
602   /// Create new phi nodes for the induction variables to resume iteration count
603   /// in the scalar epilogue, from where the vectorized loop left off.
604   /// In cases where the loop skeleton is more complicated (eg. epilogue
605   /// vectorization) and the resume values can come from an additional bypass
606   /// block, the \p AdditionalBypass pair provides information about the bypass
607   /// block and the end value on the edge from bypass to this loop.
608   void createInductionResumeValues(
609       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
610 
611   /// Complete the loop skeleton by adding debug MDs, creating appropriate
612   /// conditional branches in the middle block, preparing the builder and
613   /// running the verifier. Return the preheader of the completed vector loop.
614   BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
615 
616   /// Collect poison-generating recipes that may generate a poison value that is
617   /// used after vectorization, even when their operands are not poison. Those
618   /// recipes meet the following conditions:
619   ///  * Contribute to the address computation of a recipe generating a widen
620   ///    memory load/store (VPWidenMemoryInstructionRecipe or
621   ///    VPInterleaveRecipe).
622   ///  * Such a widen memory load/store has at least one underlying Instruction
623   ///    that is in a basic block that needs predication and after vectorization
624   ///    the generated instruction won't be predicated.
625   void collectPoisonGeneratingRecipes(VPTransformState &State);
626 
627   /// Allow subclasses to override and print debug traces before/after vplan
628   /// execution, when trace information is requested.
629   virtual void printDebugTracesAtStart(){};
630   virtual void printDebugTracesAtEnd(){};
631 
632   /// The original loop.
633   Loop *OrigLoop;
634 
635   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
636   /// dynamic knowledge to simplify SCEV expressions and converts them to a
637   /// more usable form.
638   PredicatedScalarEvolution &PSE;
639 
640   /// Loop Info.
641   LoopInfo *LI;
642 
643   /// Dominator Tree.
644   DominatorTree *DT;
645 
646   /// Alias Analysis.
647   AAResults *AA;
648 
649   /// Target Library Info.
650   const TargetLibraryInfo *TLI;
651 
652   /// Target Transform Info.
653   const TargetTransformInfo *TTI;
654 
655   /// Assumption Cache.
656   AssumptionCache *AC;
657 
658   /// Interface to emit optimization remarks.
659   OptimizationRemarkEmitter *ORE;
660 
661   /// The vectorization SIMD factor to use. Each vector will have this many
662   /// vector elements.
663   ElementCount VF;
664 
665   ElementCount MinProfitableTripCount;
666 
667   /// The vectorization unroll factor to use. Each scalar is vectorized to this
668   /// many different vector instructions.
669   unsigned UF;
670 
671   /// The builder that we use
672   IRBuilder<> Builder;
673 
674   // --- Vectorization state ---
675 
676   /// The vector-loop preheader.
677   BasicBlock *LoopVectorPreHeader;
678 
679   /// The scalar-loop preheader.
680   BasicBlock *LoopScalarPreHeader;
681 
682   /// Middle Block between the vector and the scalar.
683   BasicBlock *LoopMiddleBlock;
684 
685   /// The unique ExitBlock of the scalar loop if one exists.  Note that
686   /// there can be multiple exiting edges reaching this block.
687   BasicBlock *LoopExitBlock;
688 
689   /// The scalar loop body.
690   BasicBlock *LoopScalarBody;
691 
692   /// A list of all bypass blocks. The first block is the entry of the loop.
693   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
694 
695   /// Store instructions that were predicated.
696   SmallVector<Instruction *, 4> PredicatedInstructions;
697 
698   /// Trip count of the original loop.
699   Value *TripCount = nullptr;
700 
701   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
702   Value *VectorTripCount = nullptr;
703 
704   /// The legality analysis.
705   LoopVectorizationLegality *Legal;
706 
707   /// The profitablity analysis.
708   LoopVectorizationCostModel *Cost;
709 
710   // Record whether runtime checks are added.
711   bool AddedSafetyChecks = false;
712 
713   // Holds the end values for each induction variable. We save the end values
714   // so we can later fix-up the external users of the induction variables.
715   DenseMap<PHINode *, Value *> IVEndValues;
716 
717   /// BFI and PSI are used to check for profile guided size optimizations.
718   BlockFrequencyInfo *BFI;
719   ProfileSummaryInfo *PSI;
720 
721   // Whether this loop should be optimized for size based on profile guided size
722   // optimizatios.
723   bool OptForSizeBasedOnProfile;
724 
725   /// Structure to hold information about generated runtime checks, responsible
726   /// for cleaning the checks, if vectorization turns out unprofitable.
727   GeneratedRTChecks &RTChecks;
728 
729   // Holds the resume values for reductions in the loops, used to set the
730   // correct start value of reduction PHIs when vectorizing the epilogue.
731   SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
732       ReductionResumeValues;
733 };
734 
735 class InnerLoopUnroller : public InnerLoopVectorizer {
736 public:
737   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
738                     LoopInfo *LI, DominatorTree *DT,
739                     const TargetLibraryInfo *TLI,
740                     const TargetTransformInfo *TTI, AssumptionCache *AC,
741                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
742                     LoopVectorizationLegality *LVL,
743                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
744                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
745       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
746                             ElementCount::getFixed(1),
747                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
748                             BFI, PSI, Check) {}
749 
750 private:
751   Value *getBroadcastInstrs(Value *V) override;
752 };
753 
754 /// Encapsulate information regarding vectorization of a loop and its epilogue.
755 /// This information is meant to be updated and used across two stages of
756 /// epilogue vectorization.
757 struct EpilogueLoopVectorizationInfo {
758   ElementCount MainLoopVF = ElementCount::getFixed(0);
759   unsigned MainLoopUF = 0;
760   ElementCount EpilogueVF = ElementCount::getFixed(0);
761   unsigned EpilogueUF = 0;
762   BasicBlock *MainLoopIterationCountCheck = nullptr;
763   BasicBlock *EpilogueIterationCountCheck = nullptr;
764   BasicBlock *SCEVSafetyCheck = nullptr;
765   BasicBlock *MemSafetyCheck = nullptr;
766   Value *TripCount = nullptr;
767   Value *VectorTripCount = nullptr;
768 
769   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
770                                 ElementCount EVF, unsigned EUF)
771       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
772     assert(EUF == 1 &&
773            "A high UF for the epilogue loop is likely not beneficial.");
774   }
775 };
776 
777 /// An extension of the inner loop vectorizer that creates a skeleton for a
778 /// vectorized loop that has its epilogue (residual) also vectorized.
779 /// The idea is to run the vplan on a given loop twice, firstly to setup the
780 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
781 /// from the first step and vectorize the epilogue.  This is achieved by
782 /// deriving two concrete strategy classes from this base class and invoking
783 /// them in succession from the loop vectorizer planner.
784 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
785 public:
786   InnerLoopAndEpilogueVectorizer(
787       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
788       DominatorTree *DT, const TargetLibraryInfo *TLI,
789       const TargetTransformInfo *TTI, AssumptionCache *AC,
790       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
791       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
792       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
793       GeneratedRTChecks &Checks)
794       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
795                             EPI.MainLoopVF, EPI.MainLoopVF, EPI.MainLoopUF, LVL,
796                             CM, BFI, PSI, Checks),
797         EPI(EPI) {}
798 
799   // Override this function to handle the more complex control flow around the
800   // three loops.
801   std::pair<BasicBlock *, Value *>
802   createVectorizedLoopSkeleton() final override {
803     return createEpilogueVectorizedLoopSkeleton();
804   }
805 
806   /// The interface for creating a vectorized skeleton using one of two
807   /// different strategies, each corresponding to one execution of the vplan
808   /// as described above.
809   virtual std::pair<BasicBlock *, Value *>
810   createEpilogueVectorizedLoopSkeleton() = 0;
811 
812   /// Holds and updates state information required to vectorize the main loop
813   /// and its epilogue in two separate passes. This setup helps us avoid
814   /// regenerating and recomputing runtime safety checks. It also helps us to
815   /// shorten the iteration-count-check path length for the cases where the
816   /// iteration count of the loop is so small that the main vector loop is
817   /// completely skipped.
818   EpilogueLoopVectorizationInfo &EPI;
819 };
820 
821 /// A specialized derived class of inner loop vectorizer that performs
822 /// vectorization of *main* loops in the process of vectorizing loops and their
823 /// epilogues.
824 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
825 public:
826   EpilogueVectorizerMainLoop(
827       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
828       DominatorTree *DT, const TargetLibraryInfo *TLI,
829       const TargetTransformInfo *TTI, AssumptionCache *AC,
830       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
831       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
832       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
833       GeneratedRTChecks &Check)
834       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
835                                        EPI, LVL, CM, BFI, PSI, Check) {}
836   /// Implements the interface for creating a vectorized skeleton using the
837   /// *main loop* strategy (ie the first pass of vplan execution).
838   std::pair<BasicBlock *, Value *>
839   createEpilogueVectorizedLoopSkeleton() final override;
840 
841 protected:
842   /// Emits an iteration count bypass check once for the main loop (when \p
843   /// ForEpilogue is false) and once for the epilogue loop (when \p
844   /// ForEpilogue is true).
845   BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
846   void printDebugTracesAtStart() override;
847   void printDebugTracesAtEnd() override;
848 };
849 
850 // A specialized derived class of inner loop vectorizer that performs
851 // vectorization of *epilogue* loops in the process of vectorizing loops and
852 // their epilogues.
853 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
854 public:
855   EpilogueVectorizerEpilogueLoop(
856       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
857       DominatorTree *DT, const TargetLibraryInfo *TLI,
858       const TargetTransformInfo *TTI, AssumptionCache *AC,
859       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
860       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
861       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
862       GeneratedRTChecks &Checks)
863       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
864                                        EPI, LVL, CM, BFI, PSI, Checks) {
865     TripCount = EPI.TripCount;
866   }
867   /// Implements the interface for creating a vectorized skeleton using the
868   /// *epilogue loop* strategy (ie the second pass of vplan execution).
869   std::pair<BasicBlock *, Value *>
870   createEpilogueVectorizedLoopSkeleton() final override;
871 
872 protected:
873   /// Emits an iteration count bypass check after the main vector loop has
874   /// finished to see if there are any iterations left to execute by either
875   /// the vector epilogue or the scalar epilogue.
876   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
877                                                       BasicBlock *Bypass,
878                                                       BasicBlock *Insert);
879   void printDebugTracesAtStart() override;
880   void printDebugTracesAtEnd() override;
881 };
882 } // end namespace llvm
883 
884 /// Look for a meaningful debug location on the instruction or it's
885 /// operands.
886 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
887   if (!I)
888     return I;
889 
890   DebugLoc Empty;
891   if (I->getDebugLoc() != Empty)
892     return I;
893 
894   for (Use &Op : I->operands()) {
895     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
896       if (OpInst->getDebugLoc() != Empty)
897         return OpInst;
898   }
899 
900   return I;
901 }
902 
903 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
904 /// is passed, the message relates to that particular instruction.
905 #ifndef NDEBUG
906 static void debugVectorizationMessage(const StringRef Prefix,
907                                       const StringRef DebugMsg,
908                                       Instruction *I) {
909   dbgs() << "LV: " << Prefix << DebugMsg;
910   if (I != nullptr)
911     dbgs() << " " << *I;
912   else
913     dbgs() << '.';
914   dbgs() << '\n';
915 }
916 #endif
917 
918 /// Create an analysis remark that explains why vectorization failed
919 ///
920 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
921 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
922 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
923 /// the location of the remark.  \return the remark object that can be
924 /// streamed to.
925 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
926     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
927   Value *CodeRegion = TheLoop->getHeader();
928   DebugLoc DL = TheLoop->getStartLoc();
929 
930   if (I) {
931     CodeRegion = I->getParent();
932     // If there is no debug location attached to the instruction, revert back to
933     // using the loop's.
934     if (I->getDebugLoc())
935       DL = I->getDebugLoc();
936   }
937 
938   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
939 }
940 
941 namespace llvm {
942 
943 /// Return a value for Step multiplied by VF.
944 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
945                        int64_t Step) {
946   assert(Ty->isIntegerTy() && "Expected an integer step");
947   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
948   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
949 }
950 
951 /// Return the runtime value for VF.
952 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF) {
953   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
954   return VF.isScalable() ? B.CreateVScale(EC) : EC;
955 }
956 
957 static Value *getRuntimeVFAsFloat(IRBuilderBase &B, Type *FTy,
958                                   ElementCount VF) {
959   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
960   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
961   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
962   return B.CreateUIToFP(RuntimeVF, FTy);
963 }
964 
965 void reportVectorizationFailure(const StringRef DebugMsg,
966                                 const StringRef OREMsg, const StringRef ORETag,
967                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
968                                 Instruction *I) {
969   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
970   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
971   ORE->emit(
972       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
973       << "loop not vectorized: " << OREMsg);
974 }
975 
976 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
977                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
978                              Instruction *I) {
979   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
980   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
981   ORE->emit(
982       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
983       << Msg);
984 }
985 
986 } // end namespace llvm
987 
988 #ifndef NDEBUG
989 /// \return string containing a file name and a line # for the given loop.
990 static std::string getDebugLocString(const Loop *L) {
991   std::string Result;
992   if (L) {
993     raw_string_ostream OS(Result);
994     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
995       LoopDbgLoc.print(OS);
996     else
997       // Just print the module name.
998       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
999     OS.flush();
1000   }
1001   return Result;
1002 }
1003 #endif
1004 
1005 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1006     VPTransformState &State) {
1007 
1008   // Collect recipes in the backward slice of `Root` that may generate a poison
1009   // value that is used after vectorization.
1010   SmallPtrSet<VPRecipeBase *, 16> Visited;
1011   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1012     SmallVector<VPRecipeBase *, 16> Worklist;
1013     Worklist.push_back(Root);
1014 
1015     // Traverse the backward slice of Root through its use-def chain.
1016     while (!Worklist.empty()) {
1017       VPRecipeBase *CurRec = Worklist.back();
1018       Worklist.pop_back();
1019 
1020       if (!Visited.insert(CurRec).second)
1021         continue;
1022 
1023       // Prune search if we find another recipe generating a widen memory
1024       // instruction. Widen memory instructions involved in address computation
1025       // will lead to gather/scatter instructions, which don't need to be
1026       // handled.
1027       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1028           isa<VPInterleaveRecipe>(CurRec) ||
1029           isa<VPScalarIVStepsRecipe>(CurRec) ||
1030           isa<VPCanonicalIVPHIRecipe>(CurRec) ||
1031           isa<VPActiveLaneMaskPHIRecipe>(CurRec))
1032         continue;
1033 
1034       // This recipe contributes to the address computation of a widen
1035       // load/store. Collect recipe if its underlying instruction has
1036       // poison-generating flags.
1037       Instruction *Instr = CurRec->getUnderlyingInstr();
1038       if (Instr && Instr->hasPoisonGeneratingFlags())
1039         State.MayGeneratePoisonRecipes.insert(CurRec);
1040 
1041       // Add new definitions to the worklist.
1042       for (VPValue *operand : CurRec->operands())
1043         if (VPDef *OpDef = operand->getDef())
1044           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1045     }
1046   });
1047 
1048   // Traverse all the recipes in the VPlan and collect the poison-generating
1049   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1050   // VPInterleaveRecipe.
1051   auto Iter = depth_first(
1052       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1053   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1054     for (VPRecipeBase &Recipe : *VPBB) {
1055       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1056         Instruction &UnderlyingInstr = WidenRec->getIngredient();
1057         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1058         if (AddrDef && WidenRec->isConsecutive() &&
1059             Legal->blockNeedsPredication(UnderlyingInstr.getParent()))
1060           collectPoisonGeneratingInstrsInBackwardSlice(
1061               cast<VPRecipeBase>(AddrDef));
1062       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1063         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1064         if (AddrDef) {
1065           // Check if any member of the interleave group needs predication.
1066           const InterleaveGroup<Instruction> *InterGroup =
1067               InterleaveRec->getInterleaveGroup();
1068           bool NeedPredication = false;
1069           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1070                I < NumMembers; ++I) {
1071             Instruction *Member = InterGroup->getMember(I);
1072             if (Member)
1073               NeedPredication |=
1074                   Legal->blockNeedsPredication(Member->getParent());
1075           }
1076 
1077           if (NeedPredication)
1078             collectPoisonGeneratingInstrsInBackwardSlice(
1079                 cast<VPRecipeBase>(AddrDef));
1080         }
1081       }
1082     }
1083   }
1084 }
1085 
1086 PHINode *InnerLoopVectorizer::getReductionResumeValue(
1087     const RecurrenceDescriptor &RdxDesc) {
1088   auto It = ReductionResumeValues.find(&RdxDesc);
1089   assert(It != ReductionResumeValues.end() &&
1090          "Expected to find a resume value for the reduction.");
1091   return It->second;
1092 }
1093 
1094 namespace llvm {
1095 
1096 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1097 // lowered.
1098 enum ScalarEpilogueLowering {
1099 
1100   // The default: allowing scalar epilogues.
1101   CM_ScalarEpilogueAllowed,
1102 
1103   // Vectorization with OptForSize: don't allow epilogues.
1104   CM_ScalarEpilogueNotAllowedOptSize,
1105 
1106   // A special case of vectorisation with OptForSize: loops with a very small
1107   // trip count are considered for vectorization under OptForSize, thereby
1108   // making sure the cost of their loop body is dominant, free of runtime
1109   // guards and scalar iteration overheads.
1110   CM_ScalarEpilogueNotAllowedLowTripLoop,
1111 
1112   // Loop hint predicate indicating an epilogue is undesired.
1113   CM_ScalarEpilogueNotNeededUsePredicate,
1114 
1115   // Directive indicating we must either tail fold or not vectorize
1116   CM_ScalarEpilogueNotAllowedUsePredicate
1117 };
1118 
1119 /// ElementCountComparator creates a total ordering for ElementCount
1120 /// for the purposes of using it in a set structure.
1121 struct ElementCountComparator {
1122   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1123     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1124            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1125   }
1126 };
1127 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1128 
1129 /// LoopVectorizationCostModel - estimates the expected speedups due to
1130 /// vectorization.
1131 /// In many cases vectorization is not profitable. This can happen because of
1132 /// a number of reasons. In this class we mainly attempt to predict the
1133 /// expected speedup/slowdowns due to the supported instruction set. We use the
1134 /// TargetTransformInfo to query the different backends for the cost of
1135 /// different operations.
1136 class LoopVectorizationCostModel {
1137 public:
1138   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1139                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1140                              LoopVectorizationLegality *Legal,
1141                              const TargetTransformInfo &TTI,
1142                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1143                              AssumptionCache *AC,
1144                              OptimizationRemarkEmitter *ORE, const Function *F,
1145                              const LoopVectorizeHints *Hints,
1146                              InterleavedAccessInfo &IAI)
1147       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1148         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1149         Hints(Hints), InterleaveInfo(IAI) {}
1150 
1151   /// \return An upper bound for the vectorization factors (both fixed and
1152   /// scalable). If the factors are 0, vectorization and interleaving should be
1153   /// avoided up front.
1154   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1155 
1156   /// \return True if runtime checks are required for vectorization, and false
1157   /// otherwise.
1158   bool runtimeChecksRequired();
1159 
1160   /// \return The most profitable vectorization factor and the cost of that VF.
1161   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1162   /// then this vectorization factor will be selected if vectorization is
1163   /// possible.
1164   VectorizationFactor
1165   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1166 
1167   VectorizationFactor
1168   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1169                                     const LoopVectorizationPlanner &LVP);
1170 
1171   /// Setup cost-based decisions for user vectorization factor.
1172   /// \return true if the UserVF is a feasible VF to be chosen.
1173   bool selectUserVectorizationFactor(ElementCount UserVF) {
1174     collectUniformsAndScalars(UserVF);
1175     collectInstsToScalarize(UserVF);
1176     return expectedCost(UserVF).first.isValid();
1177   }
1178 
1179   /// \return The size (in bits) of the smallest and widest types in the code
1180   /// that needs to be vectorized. We ignore values that remain scalar such as
1181   /// 64 bit loop indices.
1182   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1183 
1184   /// \return The desired interleave count.
1185   /// If interleave count has been specified by metadata it will be returned.
1186   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1187   /// are the selected vectorization factor and the cost of the selected VF.
1188   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1189 
1190   /// Memory access instruction may be vectorized in more than one way.
1191   /// Form of instruction after vectorization depends on cost.
1192   /// This function takes cost-based decisions for Load/Store instructions
1193   /// and collects them in a map. This decisions map is used for building
1194   /// the lists of loop-uniform and loop-scalar instructions.
1195   /// The calculated cost is saved with widening decision in order to
1196   /// avoid redundant calculations.
1197   void setCostBasedWideningDecision(ElementCount VF);
1198 
1199   /// A struct that represents some properties of the register usage
1200   /// of a loop.
1201   struct RegisterUsage {
1202     /// Holds the number of loop invariant values that are used in the loop.
1203     /// The key is ClassID of target-provided register class.
1204     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1205     /// Holds the maximum number of concurrent live intervals in the loop.
1206     /// The key is ClassID of target-provided register class.
1207     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1208   };
1209 
1210   /// \return Returns information about the register usages of the loop for the
1211   /// given vectorization factors.
1212   SmallVector<RegisterUsage, 8>
1213   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1214 
1215   /// Collect values we want to ignore in the cost model.
1216   void collectValuesToIgnore();
1217 
1218   /// Collect all element types in the loop for which widening is needed.
1219   void collectElementTypesForWidening();
1220 
1221   /// Split reductions into those that happen in the loop, and those that happen
1222   /// outside. In loop reductions are collected into InLoopReductionChains.
1223   void collectInLoopReductions();
1224 
1225   /// Returns true if we should use strict in-order reductions for the given
1226   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1227   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1228   /// of FP operations.
1229   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
1230     return !Hints->allowReordering() && RdxDesc.isOrdered();
1231   }
1232 
1233   /// \returns The smallest bitwidth each instruction can be represented with.
1234   /// The vector equivalents of these instructions should be truncated to this
1235   /// type.
1236   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1237     return MinBWs;
1238   }
1239 
1240   /// \returns True if it is more profitable to scalarize instruction \p I for
1241   /// vectorization factor \p VF.
1242   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1243     assert(VF.isVector() &&
1244            "Profitable to scalarize relevant only for VF > 1.");
1245 
1246     // Cost model is not run in the VPlan-native path - return conservative
1247     // result until this changes.
1248     if (EnableVPlanNativePath)
1249       return false;
1250 
1251     auto Scalars = InstsToScalarize.find(VF);
1252     assert(Scalars != InstsToScalarize.end() &&
1253            "VF not yet analyzed for scalarization profitability");
1254     return Scalars->second.find(I) != Scalars->second.end();
1255   }
1256 
1257   /// Returns true if \p I is known to be uniform after vectorization.
1258   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1259     if (VF.isScalar())
1260       return true;
1261 
1262     // Cost model is not run in the VPlan-native path - return conservative
1263     // result until this changes.
1264     if (EnableVPlanNativePath)
1265       return false;
1266 
1267     auto UniformsPerVF = Uniforms.find(VF);
1268     assert(UniformsPerVF != Uniforms.end() &&
1269            "VF not yet analyzed for uniformity");
1270     return UniformsPerVF->second.count(I);
1271   }
1272 
1273   /// Returns true if \p I is known to be scalar after vectorization.
1274   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1275     if (VF.isScalar())
1276       return true;
1277 
1278     // Cost model is not run in the VPlan-native path - return conservative
1279     // result until this changes.
1280     if (EnableVPlanNativePath)
1281       return false;
1282 
1283     auto ScalarsPerVF = Scalars.find(VF);
1284     assert(ScalarsPerVF != Scalars.end() &&
1285            "Scalar values are not calculated for VF");
1286     return ScalarsPerVF->second.count(I);
1287   }
1288 
1289   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1290   /// for vectorization factor \p VF.
1291   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1292     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1293            !isProfitableToScalarize(I, VF) &&
1294            !isScalarAfterVectorization(I, VF);
1295   }
1296 
1297   /// Decision that was taken during cost calculation for memory instruction.
1298   enum InstWidening {
1299     CM_Unknown,
1300     CM_Widen,         // For consecutive accesses with stride +1.
1301     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1302     CM_Interleave,
1303     CM_GatherScatter,
1304     CM_Scalarize
1305   };
1306 
1307   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1308   /// instruction \p I and vector width \p VF.
1309   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1310                            InstructionCost Cost) {
1311     assert(VF.isVector() && "Expected VF >=2");
1312     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1313   }
1314 
1315   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1316   /// interleaving group \p Grp and vector width \p VF.
1317   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1318                            ElementCount VF, InstWidening W,
1319                            InstructionCost Cost) {
1320     assert(VF.isVector() && "Expected VF >=2");
1321     /// Broadcast this decicion to all instructions inside the group.
1322     /// But the cost will be assigned to one instruction only.
1323     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1324       if (auto *I = Grp->getMember(i)) {
1325         if (Grp->getInsertPos() == I)
1326           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1327         else
1328           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1329       }
1330     }
1331   }
1332 
1333   /// Return the cost model decision for the given instruction \p I and vector
1334   /// width \p VF. Return CM_Unknown if this instruction did not pass
1335   /// through the cost modeling.
1336   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1337     assert(VF.isVector() && "Expected VF to be a vector VF");
1338     // Cost model is not run in the VPlan-native path - return conservative
1339     // result until this changes.
1340     if (EnableVPlanNativePath)
1341       return CM_GatherScatter;
1342 
1343     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1344     auto Itr = WideningDecisions.find(InstOnVF);
1345     if (Itr == WideningDecisions.end())
1346       return CM_Unknown;
1347     return Itr->second.first;
1348   }
1349 
1350   /// Return the vectorization cost for the given instruction \p I and vector
1351   /// width \p VF.
1352   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1353     assert(VF.isVector() && "Expected VF >=2");
1354     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1355     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1356            "The cost is not calculated");
1357     return WideningDecisions[InstOnVF].second;
1358   }
1359 
1360   /// Return True if instruction \p I is an optimizable truncate whose operand
1361   /// is an induction variable. Such a truncate will be removed by adding a new
1362   /// induction variable with the destination type.
1363   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1364     // If the instruction is not a truncate, return false.
1365     auto *Trunc = dyn_cast<TruncInst>(I);
1366     if (!Trunc)
1367       return false;
1368 
1369     // Get the source and destination types of the truncate.
1370     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1371     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1372 
1373     // If the truncate is free for the given types, return false. Replacing a
1374     // free truncate with an induction variable would add an induction variable
1375     // update instruction to each iteration of the loop. We exclude from this
1376     // check the primary induction variable since it will need an update
1377     // instruction regardless.
1378     Value *Op = Trunc->getOperand(0);
1379     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1380       return false;
1381 
1382     // If the truncated value is not an induction variable, return false.
1383     return Legal->isInductionPhi(Op);
1384   }
1385 
1386   /// Collects the instructions to scalarize for each predicated instruction in
1387   /// the loop.
1388   void collectInstsToScalarize(ElementCount VF);
1389 
1390   /// Collect Uniform and Scalar values for the given \p VF.
1391   /// The sets depend on CM decision for Load/Store instructions
1392   /// that may be vectorized as interleave, gather-scatter or scalarized.
1393   void collectUniformsAndScalars(ElementCount VF) {
1394     // Do the analysis once.
1395     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1396       return;
1397     setCostBasedWideningDecision(VF);
1398     collectLoopUniforms(VF);
1399     collectLoopScalars(VF);
1400   }
1401 
1402   /// Returns true if the target machine supports masked store operation
1403   /// for the given \p DataType and kind of access to \p Ptr.
1404   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1405     return Legal->isConsecutivePtr(DataType, Ptr) &&
1406            TTI.isLegalMaskedStore(DataType, Alignment);
1407   }
1408 
1409   /// Returns true if the target machine supports masked load operation
1410   /// for the given \p DataType and kind of access to \p Ptr.
1411   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1412     return Legal->isConsecutivePtr(DataType, Ptr) &&
1413            TTI.isLegalMaskedLoad(DataType, Alignment);
1414   }
1415 
1416   /// Returns true if the target machine can represent \p V as a masked gather
1417   /// or scatter operation.
1418   bool isLegalGatherOrScatter(Value *V,
1419                               ElementCount VF = ElementCount::getFixed(1)) {
1420     bool LI = isa<LoadInst>(V);
1421     bool SI = isa<StoreInst>(V);
1422     if (!LI && !SI)
1423       return false;
1424     auto *Ty = getLoadStoreType(V);
1425     Align Align = getLoadStoreAlignment(V);
1426     if (VF.isVector())
1427       Ty = VectorType::get(Ty, VF);
1428     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1429            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1430   }
1431 
1432   /// Returns true if the target machine supports all of the reduction
1433   /// variables found for the given VF.
1434   bool canVectorizeReductions(ElementCount VF) const {
1435     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1436       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1437       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1438     }));
1439   }
1440 
1441   /// Returns true if \p I is an instruction that will be scalarized with
1442   /// predication when vectorizing \p I with vectorization factor \p VF. Such
1443   /// instructions include conditional stores and instructions that may divide
1444   /// by zero.
1445   bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1446 
1447   // Returns true if \p I is an instruction that will be predicated either
1448   // through scalar predication or masked load/store or masked gather/scatter.
1449   // \p VF is the vectorization factor that will be used to vectorize \p I.
1450   // Superset of instructions that return true for isScalarWithPredication.
1451   bool isPredicatedInst(Instruction *I, ElementCount VF) {
1452     // When we know the load's address is loop invariant and the instruction
1453     // in the original scalar loop was unconditionally executed then we
1454     // don't need to mark it as a predicated instruction. Tail folding may
1455     // introduce additional predication, but we're guaranteed to always have
1456     // at least one active lane.  We call Legal->blockNeedsPredication here
1457     // because it doesn't query tail-folding.
1458     if (Legal->isUniformMemOp(*I) && isa<LoadInst>(I) &&
1459         !Legal->blockNeedsPredication(I->getParent()))
1460       return false;
1461     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1462       return false;
1463     // Loads and stores that need some form of masked operation are predicated
1464     // instructions.
1465     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1466       return Legal->isMaskRequired(I);
1467     return isScalarWithPredication(I, VF);
1468   }
1469 
1470   /// Returns true if \p I is a memory instruction with consecutive memory
1471   /// access that can be widened.
1472   bool
1473   memoryInstructionCanBeWidened(Instruction *I,
1474                                 ElementCount VF = ElementCount::getFixed(1));
1475 
1476   /// Returns true if \p I is a memory instruction in an interleaved-group
1477   /// of memory accesses that can be vectorized with wide vector loads/stores
1478   /// and shuffles.
1479   bool
1480   interleavedAccessCanBeWidened(Instruction *I,
1481                                 ElementCount VF = ElementCount::getFixed(1));
1482 
1483   /// Check if \p Instr belongs to any interleaved access group.
1484   bool isAccessInterleaved(Instruction *Instr) {
1485     return InterleaveInfo.isInterleaved(Instr);
1486   }
1487 
1488   /// Get the interleaved access group that \p Instr belongs to.
1489   const InterleaveGroup<Instruction> *
1490   getInterleavedAccessGroup(Instruction *Instr) {
1491     return InterleaveInfo.getInterleaveGroup(Instr);
1492   }
1493 
1494   /// Returns true if we're required to use a scalar epilogue for at least
1495   /// the final iteration of the original loop.
1496   bool requiresScalarEpilogue(ElementCount VF) const {
1497     if (!isScalarEpilogueAllowed())
1498       return false;
1499     // If we might exit from anywhere but the latch, must run the exiting
1500     // iteration in scalar form.
1501     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1502       return true;
1503     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1504   }
1505 
1506   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1507   /// loop hint annotation.
1508   bool isScalarEpilogueAllowed() const {
1509     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1510   }
1511 
1512   /// Returns true if all loop blocks should be masked to fold tail loop.
1513   bool foldTailByMasking() const { return FoldTailByMasking; }
1514 
1515   /// Returns true if were tail-folding and want to use the active lane mask
1516   /// for vector loop control flow.
1517   bool useActiveLaneMaskForControlFlow() const {
1518     return FoldTailByMasking &&
1519            TTI.emitGetActiveLaneMask() == PredicationStyle::DataAndControlFlow;
1520   }
1521 
1522   /// Returns true if the instructions in this block requires predication
1523   /// for any reason, e.g. because tail folding now requires a predicate
1524   /// or because the block in the original loop was predicated.
1525   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1526     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1527   }
1528 
1529   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1530   /// nodes to the chain of instructions representing the reductions. Uses a
1531   /// MapVector to ensure deterministic iteration order.
1532   using ReductionChainMap =
1533       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1534 
1535   /// Return the chain of instructions representing an inloop reduction.
1536   const ReductionChainMap &getInLoopReductionChains() const {
1537     return InLoopReductionChains;
1538   }
1539 
1540   /// Returns true if the Phi is part of an inloop reduction.
1541   bool isInLoopReduction(PHINode *Phi) const {
1542     return InLoopReductionChains.count(Phi);
1543   }
1544 
1545   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1546   /// with factor VF.  Return the cost of the instruction, including
1547   /// scalarization overhead if it's needed.
1548   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1549 
1550   /// Estimate cost of a call instruction CI if it were vectorized with factor
1551   /// VF. Return the cost of the instruction, including scalarization overhead
1552   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1553   /// scalarized -
1554   /// i.e. either vector version isn't available, or is too expensive.
1555   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1556                                     bool &NeedToScalarize) const;
1557 
1558   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1559   /// that of B.
1560   bool isMoreProfitable(const VectorizationFactor &A,
1561                         const VectorizationFactor &B) const;
1562 
1563   /// Invalidates decisions already taken by the cost model.
1564   void invalidateCostModelingDecisions() {
1565     WideningDecisions.clear();
1566     Uniforms.clear();
1567     Scalars.clear();
1568   }
1569 
1570   /// Convenience function that returns the value of vscale_range iff
1571   /// vscale_range.min == vscale_range.max or otherwise returns the value
1572   /// returned by the corresponding TLI method.
1573   Optional<unsigned> getVScaleForTuning() const;
1574 
1575 private:
1576   unsigned NumPredStores = 0;
1577 
1578   /// \return An upper bound for the vectorization factors for both
1579   /// fixed and scalable vectorization, where the minimum-known number of
1580   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1581   /// disabled or unsupported, then the scalable part will be equal to
1582   /// ElementCount::getScalable(0).
1583   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1584                                            ElementCount UserVF,
1585                                            bool FoldTailByMasking);
1586 
1587   /// \return the maximized element count based on the targets vector
1588   /// registers and the loop trip-count, but limited to a maximum safe VF.
1589   /// This is a helper function of computeFeasibleMaxVF.
1590   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1591                                        unsigned SmallestType,
1592                                        unsigned WidestType,
1593                                        ElementCount MaxSafeVF,
1594                                        bool FoldTailByMasking);
1595 
1596   /// \return the maximum legal scalable VF, based on the safe max number
1597   /// of elements.
1598   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1599 
1600   /// The vectorization cost is a combination of the cost itself and a boolean
1601   /// indicating whether any of the contributing operations will actually
1602   /// operate on vector values after type legalization in the backend. If this
1603   /// latter value is false, then all operations will be scalarized (i.e. no
1604   /// vectorization has actually taken place).
1605   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1606 
1607   /// Returns the expected execution cost. The unit of the cost does
1608   /// not matter because we use the 'cost' units to compare different
1609   /// vector widths. The cost that is returned is *not* normalized by
1610   /// the factor width. If \p Invalid is not nullptr, this function
1611   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1612   /// each instruction that has an Invalid cost for the given VF.
1613   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1614   VectorizationCostTy
1615   expectedCost(ElementCount VF,
1616                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1617 
1618   /// Returns the execution time cost of an instruction for a given vector
1619   /// width. Vector width of one means scalar.
1620   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1621 
1622   /// The cost-computation logic from getInstructionCost which provides
1623   /// the vector type as an output parameter.
1624   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1625                                      Type *&VectorTy);
1626 
1627   /// Return the cost of instructions in an inloop reduction pattern, if I is
1628   /// part of that pattern.
1629   Optional<InstructionCost>
1630   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1631                           TTI::TargetCostKind CostKind);
1632 
1633   /// Calculate vectorization cost of memory instruction \p I.
1634   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1635 
1636   /// The cost computation for scalarized memory instruction.
1637   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1638 
1639   /// The cost computation for interleaving group of memory instructions.
1640   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1641 
1642   /// The cost computation for Gather/Scatter instruction.
1643   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1644 
1645   /// The cost computation for widening instruction \p I with consecutive
1646   /// memory access.
1647   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1648 
1649   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1650   /// Load: scalar load + broadcast.
1651   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1652   /// element)
1653   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1654 
1655   /// Estimate the overhead of scalarizing an instruction. This is a
1656   /// convenience wrapper for the type-based getScalarizationOverhead API.
1657   InstructionCost getScalarizationOverhead(Instruction *I,
1658                                            ElementCount VF) const;
1659 
1660   /// Returns whether the instruction is a load or store and will be a emitted
1661   /// as a vector operation.
1662   bool isConsecutiveLoadOrStore(Instruction *I);
1663 
1664   /// Returns true if an artificially high cost for emulated masked memrefs
1665   /// should be used.
1666   bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1667 
1668   /// Map of scalar integer values to the smallest bitwidth they can be legally
1669   /// represented as. The vector equivalents of these values should be truncated
1670   /// to this type.
1671   MapVector<Instruction *, uint64_t> MinBWs;
1672 
1673   /// A type representing the costs for instructions if they were to be
1674   /// scalarized rather than vectorized. The entries are Instruction-Cost
1675   /// pairs.
1676   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1677 
1678   /// A set containing all BasicBlocks that are known to present after
1679   /// vectorization as a predicated block.
1680   DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1681       PredicatedBBsAfterVectorization;
1682 
1683   /// Records whether it is allowed to have the original scalar loop execute at
1684   /// least once. This may be needed as a fallback loop in case runtime
1685   /// aliasing/dependence checks fail, or to handle the tail/remainder
1686   /// iterations when the trip count is unknown or doesn't divide by the VF,
1687   /// or as a peel-loop to handle gaps in interleave-groups.
1688   /// Under optsize and when the trip count is very small we don't allow any
1689   /// iterations to execute in the scalar loop.
1690   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1691 
1692   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1693   bool FoldTailByMasking = false;
1694 
1695   /// A map holding scalar costs for different vectorization factors. The
1696   /// presence of a cost for an instruction in the mapping indicates that the
1697   /// instruction will be scalarized when vectorizing with the associated
1698   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1699   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1700 
1701   /// Holds the instructions known to be uniform after vectorization.
1702   /// The data is collected per VF.
1703   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1704 
1705   /// Holds the instructions known to be scalar after vectorization.
1706   /// The data is collected per VF.
1707   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1708 
1709   /// Holds the instructions (address computations) that are forced to be
1710   /// scalarized.
1711   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1712 
1713   /// PHINodes of the reductions that should be expanded in-loop along with
1714   /// their associated chains of reduction operations, in program order from top
1715   /// (PHI) to bottom
1716   ReductionChainMap InLoopReductionChains;
1717 
1718   /// A Map of inloop reduction operations and their immediate chain operand.
1719   /// FIXME: This can be removed once reductions can be costed correctly in
1720   /// vplan. This was added to allow quick lookup to the inloop operations,
1721   /// without having to loop through InLoopReductionChains.
1722   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1723 
1724   /// Returns the expected difference in cost from scalarizing the expression
1725   /// feeding a predicated instruction \p PredInst. The instructions to
1726   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1727   /// non-negative return value implies the expression will be scalarized.
1728   /// Currently, only single-use chains are considered for scalarization.
1729   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1730                               ElementCount VF);
1731 
1732   /// Collect the instructions that are uniform after vectorization. An
1733   /// instruction is uniform if we represent it with a single scalar value in
1734   /// the vectorized loop corresponding to each vector iteration. Examples of
1735   /// uniform instructions include pointer operands of consecutive or
1736   /// interleaved memory accesses. Note that although uniformity implies an
1737   /// instruction will be scalar, the reverse is not true. In general, a
1738   /// scalarized instruction will be represented by VF scalar values in the
1739   /// vectorized loop, each corresponding to an iteration of the original
1740   /// scalar loop.
1741   void collectLoopUniforms(ElementCount VF);
1742 
1743   /// Collect the instructions that are scalar after vectorization. An
1744   /// instruction is scalar if it is known to be uniform or will be scalarized
1745   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1746   /// to the list if they are used by a load/store instruction that is marked as
1747   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1748   /// VF values in the vectorized loop, each corresponding to an iteration of
1749   /// the original scalar loop.
1750   void collectLoopScalars(ElementCount VF);
1751 
1752   /// Keeps cost model vectorization decision and cost for instructions.
1753   /// Right now it is used for memory instructions only.
1754   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1755                                 std::pair<InstWidening, InstructionCost>>;
1756 
1757   DecisionList WideningDecisions;
1758 
1759   /// Returns true if \p V is expected to be vectorized and it needs to be
1760   /// extracted.
1761   bool needsExtract(Value *V, ElementCount VF) const {
1762     Instruction *I = dyn_cast<Instruction>(V);
1763     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1764         TheLoop->isLoopInvariant(I))
1765       return false;
1766 
1767     // Assume we can vectorize V (and hence we need extraction) if the
1768     // scalars are not computed yet. This can happen, because it is called
1769     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1770     // the scalars are collected. That should be a safe assumption in most
1771     // cases, because we check if the operands have vectorizable types
1772     // beforehand in LoopVectorizationLegality.
1773     return Scalars.find(VF) == Scalars.end() ||
1774            !isScalarAfterVectorization(I, VF);
1775   };
1776 
1777   /// Returns a range containing only operands needing to be extracted.
1778   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1779                                                    ElementCount VF) const {
1780     return SmallVector<Value *, 4>(make_filter_range(
1781         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1782   }
1783 
1784   /// Determines if we have the infrastructure to vectorize loop \p L and its
1785   /// epilogue, assuming the main loop is vectorized by \p VF.
1786   bool isCandidateForEpilogueVectorization(const Loop &L,
1787                                            const ElementCount VF) const;
1788 
1789   /// Returns true if epilogue vectorization is considered profitable, and
1790   /// false otherwise.
1791   /// \p VF is the vectorization factor chosen for the original loop.
1792   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1793 
1794 public:
1795   /// The loop that we evaluate.
1796   Loop *TheLoop;
1797 
1798   /// Predicated scalar evolution analysis.
1799   PredicatedScalarEvolution &PSE;
1800 
1801   /// Loop Info analysis.
1802   LoopInfo *LI;
1803 
1804   /// Vectorization legality.
1805   LoopVectorizationLegality *Legal;
1806 
1807   /// Vector target information.
1808   const TargetTransformInfo &TTI;
1809 
1810   /// Target Library Info.
1811   const TargetLibraryInfo *TLI;
1812 
1813   /// Demanded bits analysis.
1814   DemandedBits *DB;
1815 
1816   /// Assumption cache.
1817   AssumptionCache *AC;
1818 
1819   /// Interface to emit optimization remarks.
1820   OptimizationRemarkEmitter *ORE;
1821 
1822   const Function *TheFunction;
1823 
1824   /// Loop Vectorize Hint.
1825   const LoopVectorizeHints *Hints;
1826 
1827   /// The interleave access information contains groups of interleaved accesses
1828   /// with the same stride and close to each other.
1829   InterleavedAccessInfo &InterleaveInfo;
1830 
1831   /// Values to ignore in the cost model.
1832   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1833 
1834   /// Values to ignore in the cost model when VF > 1.
1835   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1836 
1837   /// All element types found in the loop.
1838   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1839 
1840   /// Profitable vector factors.
1841   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1842 };
1843 } // end namespace llvm
1844 
1845 /// Helper struct to manage generating runtime checks for vectorization.
1846 ///
1847 /// The runtime checks are created up-front in temporary blocks to allow better
1848 /// estimating the cost and un-linked from the existing IR. After deciding to
1849 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1850 /// temporary blocks are completely removed.
1851 class GeneratedRTChecks {
1852   /// Basic block which contains the generated SCEV checks, if any.
1853   BasicBlock *SCEVCheckBlock = nullptr;
1854 
1855   /// The value representing the result of the generated SCEV checks. If it is
1856   /// nullptr, either no SCEV checks have been generated or they have been used.
1857   Value *SCEVCheckCond = nullptr;
1858 
1859   /// Basic block which contains the generated memory runtime checks, if any.
1860   BasicBlock *MemCheckBlock = nullptr;
1861 
1862   /// The value representing the result of the generated memory runtime checks.
1863   /// If it is nullptr, either no memory runtime checks have been generated or
1864   /// they have been used.
1865   Value *MemRuntimeCheckCond = nullptr;
1866 
1867   DominatorTree *DT;
1868   LoopInfo *LI;
1869   TargetTransformInfo *TTI;
1870 
1871   SCEVExpander SCEVExp;
1872   SCEVExpander MemCheckExp;
1873 
1874   bool CostTooHigh = false;
1875 
1876 public:
1877   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1878                     TargetTransformInfo *TTI, const DataLayout &DL)
1879       : DT(DT), LI(LI), TTI(TTI), SCEVExp(SE, DL, "scev.check"),
1880         MemCheckExp(SE, DL, "scev.check") {}
1881 
1882   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1883   /// accurately estimate the cost of the runtime checks. The blocks are
1884   /// un-linked from the IR and is added back during vector code generation. If
1885   /// there is no vector code generation, the check blocks are removed
1886   /// completely.
1887   void Create(Loop *L, const LoopAccessInfo &LAI,
1888               const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1889 
1890     // Hard cutoff to limit compile-time increase in case a very large number of
1891     // runtime checks needs to be generated.
1892     // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1893     // profile info.
1894     CostTooHigh =
1895         LAI.getNumRuntimePointerChecks() > VectorizeMemoryCheckThreshold;
1896     if (CostTooHigh)
1897       return;
1898 
1899     BasicBlock *LoopHeader = L->getHeader();
1900     BasicBlock *Preheader = L->getLoopPreheader();
1901 
1902     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1903     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1904     // may be used by SCEVExpander. The blocks will be un-linked from their
1905     // predecessors and removed from LI & DT at the end of the function.
1906     if (!UnionPred.isAlwaysTrue()) {
1907       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1908                                   nullptr, "vector.scevcheck");
1909 
1910       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1911           &UnionPred, SCEVCheckBlock->getTerminator());
1912     }
1913 
1914     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1915     if (RtPtrChecking.Need) {
1916       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1917       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1918                                  "vector.memcheck");
1919 
1920       auto DiffChecks = RtPtrChecking.getDiffChecks();
1921       if (DiffChecks) {
1922         Value *RuntimeVF = nullptr;
1923         MemRuntimeCheckCond = addDiffRuntimeChecks(
1924             MemCheckBlock->getTerminator(), L, *DiffChecks, MemCheckExp,
1925             [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1926               if (!RuntimeVF)
1927                 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1928               return RuntimeVF;
1929             },
1930             IC);
1931       } else {
1932         MemRuntimeCheckCond =
1933             addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1934                              RtPtrChecking.getChecks(), MemCheckExp);
1935       }
1936       assert(MemRuntimeCheckCond &&
1937              "no RT checks generated although RtPtrChecking "
1938              "claimed checks are required");
1939     }
1940 
1941     if (!MemCheckBlock && !SCEVCheckBlock)
1942       return;
1943 
1944     // Unhook the temporary block with the checks, update various places
1945     // accordingly.
1946     if (SCEVCheckBlock)
1947       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1948     if (MemCheckBlock)
1949       MemCheckBlock->replaceAllUsesWith(Preheader);
1950 
1951     if (SCEVCheckBlock) {
1952       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1953       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1954       Preheader->getTerminator()->eraseFromParent();
1955     }
1956     if (MemCheckBlock) {
1957       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1958       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1959       Preheader->getTerminator()->eraseFromParent();
1960     }
1961 
1962     DT->changeImmediateDominator(LoopHeader, Preheader);
1963     if (MemCheckBlock) {
1964       DT->eraseNode(MemCheckBlock);
1965       LI->removeBlock(MemCheckBlock);
1966     }
1967     if (SCEVCheckBlock) {
1968       DT->eraseNode(SCEVCheckBlock);
1969       LI->removeBlock(SCEVCheckBlock);
1970     }
1971   }
1972 
1973   InstructionCost getCost() {
1974     if (SCEVCheckBlock || MemCheckBlock)
1975       LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1976 
1977     if (CostTooHigh) {
1978       InstructionCost Cost;
1979       Cost.setInvalid();
1980       LLVM_DEBUG(dbgs() << "  number of checks exceeded threshold\n");
1981       return Cost;
1982     }
1983 
1984     InstructionCost RTCheckCost = 0;
1985     if (SCEVCheckBlock)
1986       for (Instruction &I : *SCEVCheckBlock) {
1987         if (SCEVCheckBlock->getTerminator() == &I)
1988           continue;
1989         InstructionCost C =
1990             TTI->getInstructionCost(&I, TTI::TCK_RecipThroughput);
1991         LLVM_DEBUG(dbgs() << "  " << C << "  for " << I << "\n");
1992         RTCheckCost += C;
1993       }
1994     if (MemCheckBlock)
1995       for (Instruction &I : *MemCheckBlock) {
1996         if (MemCheckBlock->getTerminator() == &I)
1997           continue;
1998         InstructionCost C =
1999             TTI->getInstructionCost(&I, TTI::TCK_RecipThroughput);
2000         LLVM_DEBUG(dbgs() << "  " << C << "  for " << I << "\n");
2001         RTCheckCost += C;
2002       }
2003 
2004     if (SCEVCheckBlock || MemCheckBlock)
2005       LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2006                         << "\n");
2007 
2008     return RTCheckCost;
2009   }
2010 
2011   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2012   /// unused.
2013   ~GeneratedRTChecks() {
2014     SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2015     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2016     if (!SCEVCheckCond)
2017       SCEVCleaner.markResultUsed();
2018 
2019     if (!MemRuntimeCheckCond)
2020       MemCheckCleaner.markResultUsed();
2021 
2022     if (MemRuntimeCheckCond) {
2023       auto &SE = *MemCheckExp.getSE();
2024       // Memory runtime check generation creates compares that use expanded
2025       // values. Remove them before running the SCEVExpanderCleaners.
2026       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2027         if (MemCheckExp.isInsertedInstruction(&I))
2028           continue;
2029         SE.forgetValue(&I);
2030         I.eraseFromParent();
2031       }
2032     }
2033     MemCheckCleaner.cleanup();
2034     SCEVCleaner.cleanup();
2035 
2036     if (SCEVCheckCond)
2037       SCEVCheckBlock->eraseFromParent();
2038     if (MemRuntimeCheckCond)
2039       MemCheckBlock->eraseFromParent();
2040   }
2041 
2042   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2043   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2044   /// depending on the generated condition.
2045   BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2046                              BasicBlock *LoopVectorPreHeader,
2047                              BasicBlock *LoopExitBlock) {
2048     if (!SCEVCheckCond)
2049       return nullptr;
2050 
2051     Value *Cond = SCEVCheckCond;
2052     // Mark the check as used, to prevent it from being removed during cleanup.
2053     SCEVCheckCond = nullptr;
2054     if (auto *C = dyn_cast<ConstantInt>(Cond))
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(SCEVCheckBlock->getTerminator(),
2074                         BranchInst::Create(Bypass, LoopVectorPreHeader, Cond));
2075     return SCEVCheckBlock;
2076   }
2077 
2078   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2079   /// the branches to branch to the vector preheader or \p Bypass, depending on
2080   /// the generated condition.
2081   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2082                                    BasicBlock *LoopVectorPreHeader) {
2083     // Check if we generated code that checks in runtime if arrays overlap.
2084     if (!MemRuntimeCheckCond)
2085       return nullptr;
2086 
2087     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2088     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2089                                                 MemCheckBlock);
2090 
2091     DT->addNewBlock(MemCheckBlock, Pred);
2092     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2093     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2094 
2095     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2096       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2097 
2098     ReplaceInstWithInst(
2099         MemCheckBlock->getTerminator(),
2100         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2101     MemCheckBlock->getTerminator()->setDebugLoc(
2102         Pred->getTerminator()->getDebugLoc());
2103 
2104     // Mark the check as used, to prevent it from being removed during cleanup.
2105     MemRuntimeCheckCond = nullptr;
2106     return MemCheckBlock;
2107   }
2108 };
2109 
2110 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2111 // vectorization. The loop needs to be annotated with #pragma omp simd
2112 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2113 // vector length information is not provided, vectorization is not considered
2114 // explicit. Interleave hints are not allowed either. These limitations will be
2115 // relaxed in the future.
2116 // Please, note that we are currently forced to abuse the pragma 'clang
2117 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2118 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2119 // provides *explicit vectorization hints* (LV can bypass legal checks and
2120 // assume that vectorization is legal). However, both hints are implemented
2121 // using the same metadata (llvm.loop.vectorize, processed by
2122 // LoopVectorizeHints). This will be fixed in the future when the native IR
2123 // representation for pragma 'omp simd' is introduced.
2124 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2125                                    OptimizationRemarkEmitter *ORE) {
2126   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2127   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2128 
2129   // Only outer loops with an explicit vectorization hint are supported.
2130   // Unannotated outer loops are ignored.
2131   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2132     return false;
2133 
2134   Function *Fn = OuterLp->getHeader()->getParent();
2135   if (!Hints.allowVectorization(Fn, OuterLp,
2136                                 true /*VectorizeOnlyWhenForced*/)) {
2137     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2138     return false;
2139   }
2140 
2141   if (Hints.getInterleave() > 1) {
2142     // TODO: Interleave support is future work.
2143     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2144                          "outer loops.\n");
2145     Hints.emitRemarkWithHints();
2146     return false;
2147   }
2148 
2149   return true;
2150 }
2151 
2152 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2153                                   OptimizationRemarkEmitter *ORE,
2154                                   SmallVectorImpl<Loop *> &V) {
2155   // Collect inner loops and outer loops without irreducible control flow. For
2156   // now, only collect outer loops that have explicit vectorization hints. If we
2157   // are stress testing the VPlan H-CFG construction, we collect the outermost
2158   // loop of every loop nest.
2159   if (L.isInnermost() || VPlanBuildStressTest ||
2160       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2161     LoopBlocksRPO RPOT(&L);
2162     RPOT.perform(LI);
2163     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2164       V.push_back(&L);
2165       // TODO: Collect inner loops inside marked outer loops in case
2166       // vectorization fails for the outer loop. Do not invoke
2167       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2168       // already known to be reducible. We can use an inherited attribute for
2169       // that.
2170       return;
2171     }
2172   }
2173   for (Loop *InnerL : L)
2174     collectSupportedLoops(*InnerL, LI, ORE, V);
2175 }
2176 
2177 namespace {
2178 
2179 /// The LoopVectorize Pass.
2180 struct LoopVectorize : public FunctionPass {
2181   /// Pass identification, replacement for typeid
2182   static char ID;
2183 
2184   LoopVectorizePass Impl;
2185 
2186   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2187                          bool VectorizeOnlyWhenForced = false)
2188       : FunctionPass(ID),
2189         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2190     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2191   }
2192 
2193   bool runOnFunction(Function &F) override {
2194     if (skipFunction(F))
2195       return false;
2196 
2197     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2198     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2199     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2200     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2201     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2202     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2203     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2204     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2205     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2206     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2207     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2208     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2209     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2210 
2211     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2212         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2213 
2214     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2215                         GetLAA, *ORE, PSI).MadeAnyChange;
2216   }
2217 
2218   void getAnalysisUsage(AnalysisUsage &AU) const override {
2219     AU.addRequired<AssumptionCacheTracker>();
2220     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2221     AU.addRequired<DominatorTreeWrapperPass>();
2222     AU.addRequired<LoopInfoWrapperPass>();
2223     AU.addRequired<ScalarEvolutionWrapperPass>();
2224     AU.addRequired<TargetTransformInfoWrapperPass>();
2225     AU.addRequired<AAResultsWrapperPass>();
2226     AU.addRequired<LoopAccessLegacyAnalysis>();
2227     AU.addRequired<DemandedBitsWrapperPass>();
2228     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2229     AU.addRequired<InjectTLIMappingsLegacy>();
2230 
2231     // We currently do not preserve loopinfo/dominator analyses with outer loop
2232     // vectorization. Until this is addressed, mark these analyses as preserved
2233     // only for non-VPlan-native path.
2234     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2235     if (!EnableVPlanNativePath) {
2236       AU.addPreserved<LoopInfoWrapperPass>();
2237       AU.addPreserved<DominatorTreeWrapperPass>();
2238     }
2239 
2240     AU.addPreserved<BasicAAWrapperPass>();
2241     AU.addPreserved<GlobalsAAWrapperPass>();
2242     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2243   }
2244 };
2245 
2246 } // end anonymous namespace
2247 
2248 //===----------------------------------------------------------------------===//
2249 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2250 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2251 //===----------------------------------------------------------------------===//
2252 
2253 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2254   // We need to place the broadcast of invariant variables outside the loop,
2255   // but only if it's proven safe to do so. Else, broadcast will be inside
2256   // vector loop body.
2257   Instruction *Instr = dyn_cast<Instruction>(V);
2258   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2259                      (!Instr ||
2260                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2261   // Place the code for broadcasting invariant variables in the new preheader.
2262   IRBuilder<>::InsertPointGuard Guard(Builder);
2263   if (SafeToHoist)
2264     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2265 
2266   // Broadcast the scalar into all locations in the vector.
2267   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2268 
2269   return Shuf;
2270 }
2271 
2272 /// This function adds
2273 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2274 /// to each vector element of Val. The sequence starts at StartIndex.
2275 /// \p Opcode is relevant for FP induction variable.
2276 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2277                             Instruction::BinaryOps BinOp, ElementCount VF,
2278                             IRBuilderBase &Builder) {
2279   assert(VF.isVector() && "only vector VFs are supported");
2280 
2281   // Create and check the types.
2282   auto *ValVTy = cast<VectorType>(Val->getType());
2283   ElementCount VLen = ValVTy->getElementCount();
2284 
2285   Type *STy = Val->getType()->getScalarType();
2286   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2287          "Induction Step must be an integer or FP");
2288   assert(Step->getType() == STy && "Step has wrong type");
2289 
2290   SmallVector<Constant *, 8> Indices;
2291 
2292   // Create a vector of consecutive numbers from zero to VF.
2293   VectorType *InitVecValVTy = ValVTy;
2294   if (STy->isFloatingPointTy()) {
2295     Type *InitVecValSTy =
2296         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2297     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2298   }
2299   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2300 
2301   // Splat the StartIdx
2302   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2303 
2304   if (STy->isIntegerTy()) {
2305     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2306     Step = Builder.CreateVectorSplat(VLen, Step);
2307     assert(Step->getType() == Val->getType() && "Invalid step vec");
2308     // FIXME: The newly created binary instructions should contain nsw/nuw
2309     // flags, which can be found from the original scalar operations.
2310     Step = Builder.CreateMul(InitVec, Step);
2311     return Builder.CreateAdd(Val, Step, "induction");
2312   }
2313 
2314   // Floating point induction.
2315   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2316          "Binary Opcode should be specified for FP induction");
2317   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2318   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2319 
2320   Step = Builder.CreateVectorSplat(VLen, Step);
2321   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2322   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2323 }
2324 
2325 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2326 /// variable on which to base the steps, \p Step is the size of the step.
2327 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2328                              const InductionDescriptor &ID, VPValue *Def,
2329                              VPTransformState &State) {
2330   IRBuilderBase &Builder = State.Builder;
2331   // We shouldn't have to build scalar steps if we aren't vectorizing.
2332   assert(State.VF.isVector() && "VF should be greater than one");
2333   // Get the value type and ensure it and the step have the same integer type.
2334   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2335   assert(ScalarIVTy == Step->getType() &&
2336          "Val and Step should have the same type");
2337 
2338   // We build scalar steps for both integer and floating-point induction
2339   // variables. Here, we determine the kind of arithmetic we will perform.
2340   Instruction::BinaryOps AddOp;
2341   Instruction::BinaryOps MulOp;
2342   if (ScalarIVTy->isIntegerTy()) {
2343     AddOp = Instruction::Add;
2344     MulOp = Instruction::Mul;
2345   } else {
2346     AddOp = ID.getInductionOpcode();
2347     MulOp = Instruction::FMul;
2348   }
2349 
2350   // Determine the number of scalars we need to generate for each unroll
2351   // iteration.
2352   bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2353   unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2354   // Compute the scalar steps and save the results in State.
2355   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2356                                      ScalarIVTy->getScalarSizeInBits());
2357   Type *VecIVTy = nullptr;
2358   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2359   if (!FirstLaneOnly && State.VF.isScalable()) {
2360     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2361     UnitStepVec =
2362         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2363     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2364     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2365   }
2366 
2367   for (unsigned Part = 0; Part < State.UF; ++Part) {
2368     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2369 
2370     if (!FirstLaneOnly && State.VF.isScalable()) {
2371       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2372       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2373       if (ScalarIVTy->isFloatingPointTy())
2374         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2375       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2376       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2377       State.set(Def, Add, Part);
2378       // It's useful to record the lane values too for the known minimum number
2379       // of elements so we do those below. This improves the code quality when
2380       // trying to extract the first element, for example.
2381     }
2382 
2383     if (ScalarIVTy->isFloatingPointTy())
2384       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2385 
2386     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2387       Value *StartIdx = Builder.CreateBinOp(
2388           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2389       // The step returned by `createStepForVF` is a runtime-evaluated value
2390       // when VF is scalable. Otherwise, it should be folded into a Constant.
2391       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2392              "Expected StartIdx to be folded to a constant when VF is not "
2393              "scalable");
2394       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2395       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2396       State.set(Def, Add, VPIteration(Part, Lane));
2397     }
2398   }
2399 }
2400 
2401 // Generate code for the induction step. Note that induction steps are
2402 // required to be loop-invariant
2403 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2404                               Instruction *InsertBefore,
2405                               Loop *OrigLoop = nullptr) {
2406   const DataLayout &DL = SE.getDataLayout();
2407   assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2408          "Induction step should be loop invariant");
2409   if (auto *E = dyn_cast<SCEVUnknown>(Step))
2410     return E->getValue();
2411 
2412   SCEVExpander Exp(SE, DL, "induction");
2413   return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2414 }
2415 
2416 /// Compute the transformed value of Index at offset StartValue using step
2417 /// StepValue.
2418 /// For integer induction, returns StartValue + Index * StepValue.
2419 /// For pointer induction, returns StartValue[Index * StepValue].
2420 /// FIXME: The newly created binary instructions should contain nsw/nuw
2421 /// flags, which can be found from the original scalar operations.
2422 static Value *emitTransformedIndex(IRBuilderBase &B, Value *Index,
2423                                    Value *StartValue, Value *Step,
2424                                    const InductionDescriptor &ID) {
2425   assert(Index->getType()->getScalarType() == Step->getType() &&
2426          "Index scalar type does not match StepValue type");
2427 
2428   // Note: the IR at this point is broken. We cannot use SE to create any new
2429   // SCEV and then expand it, hoping that SCEV's simplification will give us
2430   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2431   // lead to various SCEV crashes. So all we can do is to use builder and rely
2432   // on InstCombine for future simplifications. Here we handle some trivial
2433   // cases only.
2434   auto CreateAdd = [&B](Value *X, Value *Y) {
2435     assert(X->getType() == Y->getType() && "Types don't match!");
2436     if (auto *CX = dyn_cast<ConstantInt>(X))
2437       if (CX->isZero())
2438         return Y;
2439     if (auto *CY = dyn_cast<ConstantInt>(Y))
2440       if (CY->isZero())
2441         return X;
2442     return B.CreateAdd(X, Y);
2443   };
2444 
2445   // We allow X to be a vector type, in which case Y will potentially be
2446   // splatted into a vector with the same element count.
2447   auto CreateMul = [&B](Value *X, Value *Y) {
2448     assert(X->getType()->getScalarType() == Y->getType() &&
2449            "Types don't match!");
2450     if (auto *CX = dyn_cast<ConstantInt>(X))
2451       if (CX->isOne())
2452         return Y;
2453     if (auto *CY = dyn_cast<ConstantInt>(Y))
2454       if (CY->isOne())
2455         return X;
2456     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2457     if (XVTy && !isa<VectorType>(Y->getType()))
2458       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2459     return B.CreateMul(X, Y);
2460   };
2461 
2462   switch (ID.getKind()) {
2463   case InductionDescriptor::IK_IntInduction: {
2464     assert(!isa<VectorType>(Index->getType()) &&
2465            "Vector indices not supported for integer inductions yet");
2466     assert(Index->getType() == StartValue->getType() &&
2467            "Index type does not match StartValue type");
2468     if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2469       return B.CreateSub(StartValue, Index);
2470     auto *Offset = CreateMul(Index, Step);
2471     return CreateAdd(StartValue, Offset);
2472   }
2473   case InductionDescriptor::IK_PtrInduction: {
2474     assert(isa<Constant>(Step) &&
2475            "Expected constant step for pointer induction");
2476     return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2477   }
2478   case InductionDescriptor::IK_FpInduction: {
2479     assert(!isa<VectorType>(Index->getType()) &&
2480            "Vector indices not supported for FP inductions yet");
2481     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2482     auto InductionBinOp = ID.getInductionBinOp();
2483     assert(InductionBinOp &&
2484            (InductionBinOp->getOpcode() == Instruction::FAdd ||
2485             InductionBinOp->getOpcode() == Instruction::FSub) &&
2486            "Original bin op should be defined for FP induction");
2487 
2488     Value *MulExp = B.CreateFMul(Step, Index);
2489     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2490                          "induction");
2491   }
2492   case InductionDescriptor::IK_NoInduction:
2493     return nullptr;
2494   }
2495   llvm_unreachable("invalid enum");
2496 }
2497 
2498 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2499                                                     const VPIteration &Instance,
2500                                                     VPTransformState &State) {
2501   Value *ScalarInst = State.get(Def, Instance);
2502   Value *VectorValue = State.get(Def, Instance.Part);
2503   VectorValue = Builder.CreateInsertElement(
2504       VectorValue, ScalarInst,
2505       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2506   State.set(Def, VectorValue, Instance.Part);
2507 }
2508 
2509 // Return whether we allow using masked interleave-groups (for dealing with
2510 // strided loads/stores that reside in predicated blocks, or for dealing
2511 // with gaps).
2512 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2513   // If an override option has been passed in for interleaved accesses, use it.
2514   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2515     return EnableMaskedInterleavedMemAccesses;
2516 
2517   return TTI.enableMaskedInterleavedAccessVectorization();
2518 }
2519 
2520 // Try to vectorize the interleave group that \p Instr belongs to.
2521 //
2522 // E.g. Translate following interleaved load group (factor = 3):
2523 //   for (i = 0; i < N; i+=3) {
2524 //     R = Pic[i];             // Member of index 0
2525 //     G = Pic[i+1];           // Member of index 1
2526 //     B = Pic[i+2];           // Member of index 2
2527 //     ... // do something to R, G, B
2528 //   }
2529 // To:
2530 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2531 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2532 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2533 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2534 //
2535 // Or translate following interleaved store group (factor = 3):
2536 //   for (i = 0; i < N; i+=3) {
2537 //     ... do something to R, G, B
2538 //     Pic[i]   = R;           // Member of index 0
2539 //     Pic[i+1] = G;           // Member of index 1
2540 //     Pic[i+2] = B;           // Member of index 2
2541 //   }
2542 // To:
2543 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2544 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2545 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2546 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2547 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2548 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2549     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2550     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2551     VPValue *BlockInMask) {
2552   Instruction *Instr = Group->getInsertPos();
2553   const DataLayout &DL = Instr->getModule()->getDataLayout();
2554 
2555   // Prepare for the vector type of the interleaved load/store.
2556   Type *ScalarTy = getLoadStoreType(Instr);
2557   unsigned InterleaveFactor = Group->getFactor();
2558   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2559   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2560 
2561   // Prepare for the new pointers.
2562   SmallVector<Value *, 2> AddrParts;
2563   unsigned Index = Group->getIndex(Instr);
2564 
2565   // TODO: extend the masked interleaved-group support to reversed access.
2566   assert((!BlockInMask || !Group->isReverse()) &&
2567          "Reversed masked interleave-group not supported.");
2568 
2569   // If the group is reverse, adjust the index to refer to the last vector lane
2570   // instead of the first. We adjust the index from the first vector lane,
2571   // rather than directly getting the pointer for lane VF - 1, because the
2572   // pointer operand of the interleaved access is supposed to be uniform. For
2573   // uniform instructions, we're only required to generate a value for the
2574   // first vector lane in each unroll iteration.
2575   if (Group->isReverse())
2576     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2577 
2578   for (unsigned Part = 0; Part < UF; Part++) {
2579     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2580     State.setDebugLocFromInst(AddrPart);
2581 
2582     // Notice current instruction could be any index. Need to adjust the address
2583     // to the member of index 0.
2584     //
2585     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2586     //       b = A[i];       // Member of index 0
2587     // Current pointer is pointed to A[i+1], adjust it to A[i].
2588     //
2589     // E.g.  A[i+1] = a;     // Member of index 1
2590     //       A[i]   = b;     // Member of index 0
2591     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2592     // Current pointer is pointed to A[i+2], adjust it to A[i].
2593 
2594     bool InBounds = false;
2595     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2596       InBounds = gep->isInBounds();
2597     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2598     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2599 
2600     // Cast to the vector pointer type.
2601     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2602     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2603     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2604   }
2605 
2606   State.setDebugLocFromInst(Instr);
2607   Value *PoisonVec = PoisonValue::get(VecTy);
2608 
2609   Value *MaskForGaps = nullptr;
2610   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2611     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2612     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2613   }
2614 
2615   // Vectorize the interleaved load group.
2616   if (isa<LoadInst>(Instr)) {
2617     // For each unroll part, create a wide load for the group.
2618     SmallVector<Value *, 2> NewLoads;
2619     for (unsigned Part = 0; Part < UF; Part++) {
2620       Instruction *NewLoad;
2621       if (BlockInMask || MaskForGaps) {
2622         assert(useMaskedInterleavedAccesses(*TTI) &&
2623                "masked interleaved groups are not allowed.");
2624         Value *GroupMask = MaskForGaps;
2625         if (BlockInMask) {
2626           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2627           Value *ShuffledMask = Builder.CreateShuffleVector(
2628               BlockInMaskPart,
2629               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2630               "interleaved.mask");
2631           GroupMask = MaskForGaps
2632                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2633                                                 MaskForGaps)
2634                           : ShuffledMask;
2635         }
2636         NewLoad =
2637             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2638                                      GroupMask, PoisonVec, "wide.masked.vec");
2639       }
2640       else
2641         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2642                                             Group->getAlign(), "wide.vec");
2643       Group->addMetadata(NewLoad);
2644       NewLoads.push_back(NewLoad);
2645     }
2646 
2647     // For each member in the group, shuffle out the appropriate data from the
2648     // wide loads.
2649     unsigned J = 0;
2650     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2651       Instruction *Member = Group->getMember(I);
2652 
2653       // Skip the gaps in the group.
2654       if (!Member)
2655         continue;
2656 
2657       auto StrideMask =
2658           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2659       for (unsigned Part = 0; Part < UF; Part++) {
2660         Value *StridedVec = Builder.CreateShuffleVector(
2661             NewLoads[Part], StrideMask, "strided.vec");
2662 
2663         // If this member has different type, cast the result type.
2664         if (Member->getType() != ScalarTy) {
2665           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2666           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2667           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2668         }
2669 
2670         if (Group->isReverse())
2671           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2672 
2673         State.set(VPDefs[J], StridedVec, Part);
2674       }
2675       ++J;
2676     }
2677     return;
2678   }
2679 
2680   // The sub vector type for current instruction.
2681   auto *SubVT = VectorType::get(ScalarTy, VF);
2682 
2683   // Vectorize the interleaved store group.
2684   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2685   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2686          "masked interleaved groups are not allowed.");
2687   assert((!MaskForGaps || !VF.isScalable()) &&
2688          "masking gaps for scalable vectors is not yet supported.");
2689   for (unsigned Part = 0; Part < UF; Part++) {
2690     // Collect the stored vector from each member.
2691     SmallVector<Value *, 4> StoredVecs;
2692     for (unsigned i = 0; i < InterleaveFactor; i++) {
2693       assert((Group->getMember(i) || MaskForGaps) &&
2694              "Fail to get a member from an interleaved store group");
2695       Instruction *Member = Group->getMember(i);
2696 
2697       // Skip the gaps in the group.
2698       if (!Member) {
2699         Value *Undef = PoisonValue::get(SubVT);
2700         StoredVecs.push_back(Undef);
2701         continue;
2702       }
2703 
2704       Value *StoredVec = State.get(StoredValues[i], Part);
2705 
2706       if (Group->isReverse())
2707         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2708 
2709       // If this member has different type, cast it to a unified type.
2710 
2711       if (StoredVec->getType() != SubVT)
2712         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2713 
2714       StoredVecs.push_back(StoredVec);
2715     }
2716 
2717     // Concatenate all vectors into a wide vector.
2718     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2719 
2720     // Interleave the elements in the wide vector.
2721     Value *IVec = Builder.CreateShuffleVector(
2722         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2723         "interleaved.vec");
2724 
2725     Instruction *NewStoreInstr;
2726     if (BlockInMask || MaskForGaps) {
2727       Value *GroupMask = MaskForGaps;
2728       if (BlockInMask) {
2729         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2730         Value *ShuffledMask = Builder.CreateShuffleVector(
2731             BlockInMaskPart,
2732             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2733             "interleaved.mask");
2734         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2735                                                       ShuffledMask, MaskForGaps)
2736                                 : ShuffledMask;
2737       }
2738       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2739                                                 Group->getAlign(), GroupMask);
2740     } else
2741       NewStoreInstr =
2742           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2743 
2744     Group->addMetadata(NewStoreInstr);
2745   }
2746 }
2747 
2748 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2749                                                VPReplicateRecipe *RepRecipe,
2750                                                const VPIteration &Instance,
2751                                                bool IfPredicateInstr,
2752                                                VPTransformState &State) {
2753   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2754 
2755   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2756   // the first lane and part.
2757   if (isa<NoAliasScopeDeclInst>(Instr))
2758     if (!Instance.isFirstIteration())
2759       return;
2760 
2761   // Does this instruction return a value ?
2762   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2763 
2764   Instruction *Cloned = Instr->clone();
2765   if (!IsVoidRetTy)
2766     Cloned->setName(Instr->getName() + ".cloned");
2767 
2768   // If the scalarized instruction contributes to the address computation of a
2769   // widen masked load/store which was in a basic block that needed predication
2770   // and is not predicated after vectorization, we can't propagate
2771   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2772   // instruction could feed a poison value to the base address of the widen
2773   // load/store.
2774   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2775     Cloned->dropPoisonGeneratingFlags();
2776 
2777   if (Instr->getDebugLoc())
2778     State.setDebugLocFromInst(Instr);
2779 
2780   // Replace the operands of the cloned instructions with their scalar
2781   // equivalents in the new loop.
2782   for (auto &I : enumerate(RepRecipe->operands())) {
2783     auto InputInstance = Instance;
2784     VPValue *Operand = I.value();
2785     VPReplicateRecipe *OperandR = dyn_cast<VPReplicateRecipe>(Operand);
2786     if (OperandR && OperandR->isUniform())
2787       InputInstance.Lane = VPLane::getFirstLane();
2788     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2789   }
2790   State.addNewMetadata(Cloned, Instr);
2791 
2792   // Place the cloned scalar in the new loop.
2793   State.Builder.Insert(Cloned);
2794 
2795   State.set(RepRecipe, Cloned, Instance);
2796 
2797   // If we just cloned a new assumption, add it the assumption cache.
2798   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2799     AC->registerAssumption(II);
2800 
2801   // End if-block.
2802   if (IfPredicateInstr)
2803     PredicatedInstructions.push_back(Cloned);
2804 }
2805 
2806 Value *InnerLoopVectorizer::getOrCreateTripCount(BasicBlock *InsertBlock) {
2807   if (TripCount)
2808     return TripCount;
2809 
2810   assert(InsertBlock);
2811   IRBuilder<> Builder(InsertBlock->getTerminator());
2812   // Find the loop boundaries.
2813   ScalarEvolution *SE = PSE.getSE();
2814   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2815   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2816          "Invalid loop count");
2817 
2818   Type *IdxTy = Legal->getWidestInductionType();
2819   assert(IdxTy && "No type for induction");
2820 
2821   // The exit count might have the type of i64 while the phi is i32. This can
2822   // happen if we have an induction variable that is sign extended before the
2823   // compare. The only way that we get a backedge taken count is that the
2824   // induction variable was signed and as such will not overflow. In such a case
2825   // truncation is legal.
2826   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2827       IdxTy->getPrimitiveSizeInBits())
2828     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2829   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2830 
2831   // Get the total trip count from the count by adding 1.
2832   const SCEV *ExitCount = SE->getAddExpr(
2833       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2834 
2835   const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2836 
2837   // Expand the trip count and place the new instructions in the preheader.
2838   // Notice that the pre-header does not change, only the loop body.
2839   SCEVExpander Exp(*SE, DL, "induction");
2840 
2841   // Count holds the overall loop count (N).
2842   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2843                                 InsertBlock->getTerminator());
2844 
2845   if (TripCount->getType()->isPointerTy())
2846     TripCount =
2847         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2848                                     InsertBlock->getTerminator());
2849 
2850   return TripCount;
2851 }
2852 
2853 Value *
2854 InnerLoopVectorizer::getOrCreateVectorTripCount(BasicBlock *InsertBlock) {
2855   if (VectorTripCount)
2856     return VectorTripCount;
2857 
2858   Value *TC = getOrCreateTripCount(InsertBlock);
2859   IRBuilder<> Builder(InsertBlock->getTerminator());
2860 
2861   Type *Ty = TC->getType();
2862   // This is where we can make the step a runtime constant.
2863   Value *Step = createStepForVF(Builder, Ty, VF, UF);
2864 
2865   // If the tail is to be folded by masking, round the number of iterations N
2866   // up to a multiple of Step instead of rounding down. This is done by first
2867   // adding Step-1 and then rounding down. Note that it's ok if this addition
2868   // overflows: the vector induction variable will eventually wrap to zero given
2869   // that it starts at zero and its Step is a power of two; the loop will then
2870   // exit, with the last early-exit vector comparison also producing all-true.
2871   // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2872   // is accounted for in emitIterationCountCheck that adds an overflow check.
2873   if (Cost->foldTailByMasking()) {
2874     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2875            "VF*UF must be a power of 2 when folding tail by masking");
2876     Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2877     TC = Builder.CreateAdd(
2878         TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2879   }
2880 
2881   // Now we need to generate the expression for the part of the loop that the
2882   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2883   // iterations are not required for correctness, or N - Step, otherwise. Step
2884   // is equal to the vectorization factor (number of SIMD elements) times the
2885   // unroll factor (number of SIMD instructions).
2886   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2887 
2888   // There are cases where we *must* run at least one iteration in the remainder
2889   // loop.  See the cost model for when this can happen.  If the step evenly
2890   // divides the trip count, we set the remainder to be equal to the step. If
2891   // the step does not evenly divide the trip count, no adjustment is necessary
2892   // since there will already be scalar iterations. Note that the minimum
2893   // iterations check ensures that N >= Step.
2894   if (Cost->requiresScalarEpilogue(VF)) {
2895     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2896     R = Builder.CreateSelect(IsZero, Step, R);
2897   }
2898 
2899   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2900 
2901   return VectorTripCount;
2902 }
2903 
2904 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2905                                                    const DataLayout &DL) {
2906   // Verify that V is a vector type with same number of elements as DstVTy.
2907   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2908   unsigned VF = DstFVTy->getNumElements();
2909   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2910   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2911   Type *SrcElemTy = SrcVecTy->getElementType();
2912   Type *DstElemTy = DstFVTy->getElementType();
2913   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2914          "Vector elements must have same size");
2915 
2916   // Do a direct cast if element types are castable.
2917   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2918     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2919   }
2920   // V cannot be directly casted to desired vector type.
2921   // May happen when V is a floating point vector but DstVTy is a vector of
2922   // pointers or vice-versa. Handle this using a two-step bitcast using an
2923   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2924   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2925          "Only one type should be a pointer type");
2926   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2927          "Only one type should be a floating point type");
2928   Type *IntTy =
2929       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2930   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2931   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2932   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2933 }
2934 
2935 void InnerLoopVectorizer::emitIterationCountCheck(BasicBlock *Bypass) {
2936   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
2937   // Reuse existing vector loop preheader for TC checks.
2938   // Note that new preheader block is generated for vector loop.
2939   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2940   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2941 
2942   // Generate code to check if the loop's trip count is less than VF * UF, or
2943   // equal to it in case a scalar epilogue is required; this implies that the
2944   // vector trip count is zero. This check also covers the case where adding one
2945   // to the backedge-taken count overflowed leading to an incorrect trip count
2946   // of zero. In this case we will also jump to the scalar loop.
2947   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
2948                                             : ICmpInst::ICMP_ULT;
2949 
2950   // If tail is to be folded, vector loop takes care of all iterations.
2951   Type *CountTy = Count->getType();
2952   Value *CheckMinIters = Builder.getFalse();
2953   auto CreateStep = [&]() -> Value * {
2954     // Create step with max(MinProTripCount, UF * VF).
2955     if (UF * VF.getKnownMinValue() >= MinProfitableTripCount.getKnownMinValue())
2956       return createStepForVF(Builder, CountTy, VF, UF);
2957 
2958     Value *MinProfTC =
2959         createStepForVF(Builder, CountTy, MinProfitableTripCount, 1);
2960     if (!VF.isScalable())
2961       return MinProfTC;
2962     return Builder.CreateBinaryIntrinsic(
2963         Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2964   };
2965 
2966   if (!Cost->foldTailByMasking())
2967     CheckMinIters =
2968         Builder.CreateICmp(P, Count, CreateStep(), "min.iters.check");
2969   else if (VF.isScalable()) {
2970     // vscale is not necessarily a power-of-2, which means we cannot guarantee
2971     // an overflow to zero when updating induction variables and so an
2972     // additional overflow check is required before entering the vector loop.
2973 
2974     // Get the maximum unsigned value for the type.
2975     Value *MaxUIntTripCount =
2976         ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2977     Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2978 
2979     // Don't execute the vector loop if (UMax - n) < (VF * UF).
2980     CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
2981   }
2982 
2983   // Create new preheader for vector loop.
2984   LoopVectorPreHeader =
2985       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2986                  "vector.ph");
2987 
2988   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
2989                                DT->getNode(Bypass)->getIDom()) &&
2990          "TC check is expected to dominate Bypass");
2991 
2992   // Update dominator for Bypass & LoopExit (if needed).
2993   DT->changeImmediateDominator(Bypass, TCCheckBlock);
2994   if (!Cost->requiresScalarEpilogue(VF))
2995     // If there is an epilogue which must run, there's no edge from the
2996     // middle block to exit blocks  and thus no need to update the immediate
2997     // dominator of the exit blocks.
2998     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
2999 
3000   ReplaceInstWithInst(
3001       TCCheckBlock->getTerminator(),
3002       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3003   LoopBypassBlocks.push_back(TCCheckBlock);
3004 }
3005 
3006 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(BasicBlock *Bypass) {
3007   BasicBlock *const SCEVCheckBlock =
3008       RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3009   if (!SCEVCheckBlock)
3010     return nullptr;
3011 
3012   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3013            (OptForSizeBasedOnProfile &&
3014             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3015          "Cannot SCEV check stride or overflow when optimizing for size");
3016 
3017 
3018   // Update dominator only if this is first RT check.
3019   if (LoopBypassBlocks.empty()) {
3020     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3021     if (!Cost->requiresScalarEpilogue(VF))
3022       // If there is an epilogue which must run, there's no edge from the
3023       // middle block to exit blocks  and thus no need to update the immediate
3024       // dominator of the exit blocks.
3025       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3026   }
3027 
3028   LoopBypassBlocks.push_back(SCEVCheckBlock);
3029   AddedSafetyChecks = true;
3030   return SCEVCheckBlock;
3031 }
3032 
3033 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(BasicBlock *Bypass) {
3034   // VPlan-native path does not do any analysis for runtime checks currently.
3035   if (EnableVPlanNativePath)
3036     return nullptr;
3037 
3038   BasicBlock *const MemCheckBlock =
3039       RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3040 
3041   // Check if we generated code that checks in runtime if arrays overlap. We put
3042   // the checks into a separate block to make the more common case of few
3043   // elements faster.
3044   if (!MemCheckBlock)
3045     return nullptr;
3046 
3047   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3048     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3049            "Cannot emit memory checks when optimizing for size, unless forced "
3050            "to vectorize.");
3051     ORE->emit([&]() {
3052       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3053                                         OrigLoop->getStartLoc(),
3054                                         OrigLoop->getHeader())
3055              << "Code-size may be reduced by not forcing "
3056                 "vectorization, or by source-code modifications "
3057                 "eliminating the need for runtime checks "
3058                 "(e.g., adding 'restrict').";
3059     });
3060   }
3061 
3062   LoopBypassBlocks.push_back(MemCheckBlock);
3063 
3064   AddedSafetyChecks = true;
3065 
3066   return MemCheckBlock;
3067 }
3068 
3069 void InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3070   LoopScalarBody = OrigLoop->getHeader();
3071   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3072   assert(LoopVectorPreHeader && "Invalid loop structure");
3073   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3074   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3075          "multiple exit loop without required epilogue?");
3076 
3077   LoopMiddleBlock =
3078       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3079                  LI, nullptr, Twine(Prefix) + "middle.block");
3080   LoopScalarPreHeader =
3081       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3082                  nullptr, Twine(Prefix) + "scalar.ph");
3083 
3084   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3085 
3086   // Set up the middle block terminator.  Two cases:
3087   // 1) If we know that we must execute the scalar epilogue, emit an
3088   //    unconditional branch.
3089   // 2) Otherwise, we must have a single unique exit block (due to how we
3090   //    implement the multiple exit case).  In this case, set up a conditonal
3091   //    branch from the middle block to the loop scalar preheader, and the
3092   //    exit block.  completeLoopSkeleton will update the condition to use an
3093   //    iteration check, if required to decide whether to execute the remainder.
3094   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3095     BranchInst::Create(LoopScalarPreHeader) :
3096     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3097                        Builder.getTrue());
3098   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3099   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3100 
3101   // Update dominator for loop exit. During skeleton creation, only the vector
3102   // pre-header and the middle block are created. The vector loop is entirely
3103   // created during VPlan exection.
3104   if (!Cost->requiresScalarEpilogue(VF))
3105     // If there is an epilogue which must run, there's no edge from the
3106     // middle block to exit blocks  and thus no need to update the immediate
3107     // dominator of the exit blocks.
3108     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3109 }
3110 
3111 void InnerLoopVectorizer::createInductionResumeValues(
3112     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3113   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3114           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3115          "Inconsistent information about additional bypass.");
3116 
3117   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3118   assert(VectorTripCount && "Expected valid arguments");
3119   // We are going to resume the execution of the scalar loop.
3120   // Go over all of the induction variables that we found and fix the
3121   // PHIs that are left in the scalar version of the loop.
3122   // The starting values of PHI nodes depend on the counter of the last
3123   // iteration in the vectorized loop.
3124   // If we come from a bypass edge then we need to start from the original
3125   // start value.
3126   Instruction *OldInduction = Legal->getPrimaryInduction();
3127   for (auto &InductionEntry : Legal->getInductionVars()) {
3128     PHINode *OrigPhi = InductionEntry.first;
3129     InductionDescriptor II = InductionEntry.second;
3130 
3131     Value *&EndValue = IVEndValues[OrigPhi];
3132     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3133     if (OrigPhi == OldInduction) {
3134       // We know what the end value is.
3135       EndValue = VectorTripCount;
3136     } else {
3137       IRBuilder<> B(LoopVectorPreHeader->getTerminator());
3138 
3139       // Fast-math-flags propagate from the original induction instruction.
3140       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3141         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3142 
3143       Type *StepType = II.getStep()->getType();
3144       Instruction::CastOps CastOp =
3145           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3146       Value *VTC = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.vtc");
3147       Value *Step =
3148           CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3149       EndValue = emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3150       EndValue->setName("ind.end");
3151 
3152       // Compute the end value for the additional bypass (if applicable).
3153       if (AdditionalBypass.first) {
3154         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3155         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3156                                          StepType, true);
3157         Value *Step =
3158             CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3159         VTC =
3160             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.vtc");
3161         EndValueFromAdditionalBypass =
3162             emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3163         EndValueFromAdditionalBypass->setName("ind.end");
3164       }
3165     }
3166 
3167     // Create phi nodes to merge from the  backedge-taken check block.
3168     PHINode *BCResumeVal =
3169         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3170                         LoopScalarPreHeader->getTerminator());
3171     // Copy original phi DL over to the new one.
3172     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3173 
3174     // The new PHI merges the original incoming value, in case of a bypass,
3175     // or the value at the end of the vectorized loop.
3176     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3177 
3178     // Fix the scalar body counter (PHI node).
3179     // The old induction's phi node in the scalar body needs the truncated
3180     // value.
3181     for (BasicBlock *BB : LoopBypassBlocks)
3182       BCResumeVal->addIncoming(II.getStartValue(), BB);
3183 
3184     if (AdditionalBypass.first)
3185       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3186                                             EndValueFromAdditionalBypass);
3187 
3188     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3189   }
3190 }
3191 
3192 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(MDNode *OrigLoopID) {
3193   // The trip counts should be cached by now.
3194   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
3195   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3196 
3197   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3198 
3199   // Add a check in the middle block to see if we have completed
3200   // all of the iterations in the first vector loop.  Three cases:
3201   // 1) If we require a scalar epilogue, there is no conditional branch as
3202   //    we unconditionally branch to the scalar preheader.  Do nothing.
3203   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3204   //    Thus if tail is to be folded, we know we don't need to run the
3205   //    remainder and we can use the previous value for the condition (true).
3206   // 3) Otherwise, construct a runtime check.
3207   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3208     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3209                                         Count, VectorTripCount, "cmp.n",
3210                                         LoopMiddleBlock->getTerminator());
3211 
3212     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3213     // of the corresponding compare because they may have ended up with
3214     // different line numbers and we want to avoid awkward line stepping while
3215     // debugging. Eg. if the compare has got a line number inside the loop.
3216     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3217     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3218   }
3219 
3220 #ifdef EXPENSIVE_CHECKS
3221   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3222 #endif
3223 
3224   return LoopVectorPreHeader;
3225 }
3226 
3227 std::pair<BasicBlock *, Value *>
3228 InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3229   /*
3230    In this function we generate a new loop. The new loop will contain
3231    the vectorized instructions while the old loop will continue to run the
3232    scalar remainder.
3233 
3234        [ ] <-- loop iteration number check.
3235     /   |
3236    /    v
3237   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3238   |  /  |
3239   | /   v
3240   ||   [ ]     <-- vector pre header.
3241   |/    |
3242   |     v
3243   |    [  ] \
3244   |    [  ]_|   <-- vector loop (created during VPlan execution).
3245   |     |
3246   |     v
3247   \   -[ ]   <--- middle-block.
3248    \/   |
3249    /\   v
3250    | ->[ ]     <--- new preheader.
3251    |    |
3252  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3253    |   [ ] \
3254    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3255     \   |
3256      \  v
3257       >[ ]     <-- exit block(s).
3258    ...
3259    */
3260 
3261   // Get the metadata of the original loop before it gets modified.
3262   MDNode *OrigLoopID = OrigLoop->getLoopID();
3263 
3264   // Workaround!  Compute the trip count of the original loop and cache it
3265   // before we start modifying the CFG.  This code has a systemic problem
3266   // wherein it tries to run analysis over partially constructed IR; this is
3267   // wrong, and not simply for SCEV.  The trip count of the original loop
3268   // simply happens to be prone to hitting this in practice.  In theory, we
3269   // can hit the same issue for any SCEV, or ValueTracking query done during
3270   // mutation.  See PR49900.
3271   getOrCreateTripCount(OrigLoop->getLoopPreheader());
3272 
3273   // Create an empty vector loop, and prepare basic blocks for the runtime
3274   // checks.
3275   createVectorLoopSkeleton("");
3276 
3277   // Now, compare the new count to zero. If it is zero skip the vector loop and
3278   // jump to the scalar loop. This check also covers the case where the
3279   // backedge-taken count is uint##_max: adding one to it will overflow leading
3280   // to an incorrect trip count of zero. In this (rare) case we will also jump
3281   // to the scalar loop.
3282   emitIterationCountCheck(LoopScalarPreHeader);
3283 
3284   // Generate the code to check any assumptions that we've made for SCEV
3285   // expressions.
3286   emitSCEVChecks(LoopScalarPreHeader);
3287 
3288   // Generate the code that checks in runtime if arrays overlap. We put the
3289   // checks into a separate block to make the more common case of few elements
3290   // faster.
3291   emitMemRuntimeChecks(LoopScalarPreHeader);
3292 
3293   // Emit phis for the new starting index of the scalar loop.
3294   createInductionResumeValues();
3295 
3296   return {completeLoopSkeleton(OrigLoopID), nullptr};
3297 }
3298 
3299 // Fix up external users of the induction variable. At this point, we are
3300 // in LCSSA form, with all external PHIs that use the IV having one input value,
3301 // coming from the remainder loop. We need those PHIs to also have a correct
3302 // value for the IV when arriving directly from the middle block.
3303 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3304                                        const InductionDescriptor &II,
3305                                        Value *VectorTripCount, Value *EndValue,
3306                                        BasicBlock *MiddleBlock,
3307                                        BasicBlock *VectorHeader, VPlan &Plan) {
3308   // There are two kinds of external IV usages - those that use the value
3309   // computed in the last iteration (the PHI) and those that use the penultimate
3310   // value (the value that feeds into the phi from the loop latch).
3311   // We allow both, but they, obviously, have different values.
3312 
3313   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3314 
3315   DenseMap<Value *, Value *> MissingVals;
3316 
3317   // An external user of the last iteration's value should see the value that
3318   // the remainder loop uses to initialize its own IV.
3319   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3320   for (User *U : PostInc->users()) {
3321     Instruction *UI = cast<Instruction>(U);
3322     if (!OrigLoop->contains(UI)) {
3323       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3324       MissingVals[UI] = EndValue;
3325     }
3326   }
3327 
3328   // An external user of the penultimate value need to see EndValue - Step.
3329   // The simplest way to get this is to recompute it from the constituent SCEVs,
3330   // that is Start + (Step * (CRD - 1)).
3331   for (User *U : OrigPhi->users()) {
3332     auto *UI = cast<Instruction>(U);
3333     if (!OrigLoop->contains(UI)) {
3334       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3335 
3336       IRBuilder<> B(MiddleBlock->getTerminator());
3337 
3338       // Fast-math-flags propagate from the original induction instruction.
3339       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3340         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3341 
3342       Value *CountMinusOne = B.CreateSub(
3343           VectorTripCount, ConstantInt::get(VectorTripCount->getType(), 1));
3344       Value *CMO =
3345           !II.getStep()->getType()->isIntegerTy()
3346               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3347                              II.getStep()->getType())
3348               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3349       CMO->setName("cast.cmo");
3350 
3351       Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3352                                     VectorHeader->getTerminator());
3353       Value *Escape =
3354           emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3355       Escape->setName("ind.escape");
3356       MissingVals[UI] = Escape;
3357     }
3358   }
3359 
3360   for (auto &I : MissingVals) {
3361     PHINode *PHI = cast<PHINode>(I.first);
3362     // One corner case we have to handle is two IVs "chasing" each-other,
3363     // that is %IV2 = phi [...], [ %IV1, %latch ]
3364     // In this case, if IV1 has an external use, we need to avoid adding both
3365     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3366     // don't already have an incoming value for the middle block.
3367     if (PHI->getBasicBlockIndex(MiddleBlock) == -1) {
3368       PHI->addIncoming(I.second, MiddleBlock);
3369       Plan.removeLiveOut(PHI);
3370     }
3371   }
3372 }
3373 
3374 namespace {
3375 
3376 struct CSEDenseMapInfo {
3377   static bool canHandle(const Instruction *I) {
3378     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3379            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3380   }
3381 
3382   static inline Instruction *getEmptyKey() {
3383     return DenseMapInfo<Instruction *>::getEmptyKey();
3384   }
3385 
3386   static inline Instruction *getTombstoneKey() {
3387     return DenseMapInfo<Instruction *>::getTombstoneKey();
3388   }
3389 
3390   static unsigned getHashValue(const Instruction *I) {
3391     assert(canHandle(I) && "Unknown instruction!");
3392     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3393                                                            I->value_op_end()));
3394   }
3395 
3396   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3397     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3398         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3399       return LHS == RHS;
3400     return LHS->isIdenticalTo(RHS);
3401   }
3402 };
3403 
3404 } // end anonymous namespace
3405 
3406 ///Perform cse of induction variable instructions.
3407 static void cse(BasicBlock *BB) {
3408   // Perform simple cse.
3409   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3410   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3411     if (!CSEDenseMapInfo::canHandle(&In))
3412       continue;
3413 
3414     // Check if we can replace this instruction with any of the
3415     // visited instructions.
3416     if (Instruction *V = CSEMap.lookup(&In)) {
3417       In.replaceAllUsesWith(V);
3418       In.eraseFromParent();
3419       continue;
3420     }
3421 
3422     CSEMap[&In] = &In;
3423   }
3424 }
3425 
3426 InstructionCost
3427 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3428                                               bool &NeedToScalarize) const {
3429   Function *F = CI->getCalledFunction();
3430   Type *ScalarRetTy = CI->getType();
3431   SmallVector<Type *, 4> Tys, ScalarTys;
3432   for (auto &ArgOp : CI->args())
3433     ScalarTys.push_back(ArgOp->getType());
3434 
3435   // Estimate cost of scalarized vector call. The source operands are assumed
3436   // to be vectors, so we need to extract individual elements from there,
3437   // execute VF scalar calls, and then gather the result into the vector return
3438   // value.
3439   InstructionCost ScalarCallCost =
3440       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3441   if (VF.isScalar())
3442     return ScalarCallCost;
3443 
3444   // Compute corresponding vector type for return value and arguments.
3445   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3446   for (Type *ScalarTy : ScalarTys)
3447     Tys.push_back(ToVectorTy(ScalarTy, VF));
3448 
3449   // Compute costs of unpacking argument values for the scalar calls and
3450   // packing the return values to a vector.
3451   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3452 
3453   InstructionCost Cost =
3454       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3455 
3456   // If we can't emit a vector call for this function, then the currently found
3457   // cost is the cost we need to return.
3458   NeedToScalarize = true;
3459   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3460   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3461 
3462   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3463     return Cost;
3464 
3465   // If the corresponding vector cost is cheaper, return its cost.
3466   InstructionCost VectorCallCost =
3467       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3468   if (VectorCallCost < Cost) {
3469     NeedToScalarize = false;
3470     Cost = VectorCallCost;
3471   }
3472   return Cost;
3473 }
3474 
3475 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3476   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3477     return Elt;
3478   return VectorType::get(Elt, VF);
3479 }
3480 
3481 InstructionCost
3482 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3483                                                    ElementCount VF) const {
3484   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3485   assert(ID && "Expected intrinsic call!");
3486   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3487   FastMathFlags FMF;
3488   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3489     FMF = FPMO->getFastMathFlags();
3490 
3491   SmallVector<const Value *> Arguments(CI->args());
3492   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3493   SmallVector<Type *> ParamTys;
3494   std::transform(FTy->param_begin(), FTy->param_end(),
3495                  std::back_inserter(ParamTys),
3496                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3497 
3498   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3499                                     dyn_cast<IntrinsicInst>(CI));
3500   return TTI.getIntrinsicInstrCost(CostAttrs,
3501                                    TargetTransformInfo::TCK_RecipThroughput);
3502 }
3503 
3504 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3505   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3506   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3507   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3508 }
3509 
3510 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3511   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3512   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3513   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3514 }
3515 
3516 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3517   // For every instruction `I` in MinBWs, truncate the operands, create a
3518   // truncated version of `I` and reextend its result. InstCombine runs
3519   // later and will remove any ext/trunc pairs.
3520   SmallPtrSet<Value *, 4> Erased;
3521   for (const auto &KV : Cost->getMinimalBitwidths()) {
3522     // If the value wasn't vectorized, we must maintain the original scalar
3523     // type. The absence of the value from State indicates that it
3524     // wasn't vectorized.
3525     // FIXME: Should not rely on getVPValue at this point.
3526     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3527     if (!State.hasAnyVectorValue(Def))
3528       continue;
3529     for (unsigned Part = 0; Part < UF; ++Part) {
3530       Value *I = State.get(Def, Part);
3531       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3532         continue;
3533       Type *OriginalTy = I->getType();
3534       Type *ScalarTruncatedTy =
3535           IntegerType::get(OriginalTy->getContext(), KV.second);
3536       auto *TruncatedTy = VectorType::get(
3537           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3538       if (TruncatedTy == OriginalTy)
3539         continue;
3540 
3541       IRBuilder<> B(cast<Instruction>(I));
3542       auto ShrinkOperand = [&](Value *V) -> Value * {
3543         if (auto *ZI = dyn_cast<ZExtInst>(V))
3544           if (ZI->getSrcTy() == TruncatedTy)
3545             return ZI->getOperand(0);
3546         return B.CreateZExtOrTrunc(V, TruncatedTy);
3547       };
3548 
3549       // The actual instruction modification depends on the instruction type,
3550       // unfortunately.
3551       Value *NewI = nullptr;
3552       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3553         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3554                              ShrinkOperand(BO->getOperand(1)));
3555 
3556         // Any wrapping introduced by shrinking this operation shouldn't be
3557         // considered undefined behavior. So, we can't unconditionally copy
3558         // arithmetic wrapping flags to NewI.
3559         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3560       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3561         NewI =
3562             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3563                          ShrinkOperand(CI->getOperand(1)));
3564       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3565         NewI = B.CreateSelect(SI->getCondition(),
3566                               ShrinkOperand(SI->getTrueValue()),
3567                               ShrinkOperand(SI->getFalseValue()));
3568       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3569         switch (CI->getOpcode()) {
3570         default:
3571           llvm_unreachable("Unhandled cast!");
3572         case Instruction::Trunc:
3573           NewI = ShrinkOperand(CI->getOperand(0));
3574           break;
3575         case Instruction::SExt:
3576           NewI = B.CreateSExtOrTrunc(
3577               CI->getOperand(0),
3578               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3579           break;
3580         case Instruction::ZExt:
3581           NewI = B.CreateZExtOrTrunc(
3582               CI->getOperand(0),
3583               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3584           break;
3585         }
3586       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3587         auto Elements0 =
3588             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3589         auto *O0 = B.CreateZExtOrTrunc(
3590             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3591         auto Elements1 =
3592             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3593         auto *O1 = B.CreateZExtOrTrunc(
3594             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3595 
3596         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3597       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3598         // Don't do anything with the operands, just extend the result.
3599         continue;
3600       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3601         auto Elements =
3602             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3603         auto *O0 = B.CreateZExtOrTrunc(
3604             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3605         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3606         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3607       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3608         auto Elements =
3609             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3610         auto *O0 = B.CreateZExtOrTrunc(
3611             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3612         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3613       } else {
3614         // If we don't know what to do, be conservative and don't do anything.
3615         continue;
3616       }
3617 
3618       // Lastly, extend the result.
3619       NewI->takeName(cast<Instruction>(I));
3620       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3621       I->replaceAllUsesWith(Res);
3622       cast<Instruction>(I)->eraseFromParent();
3623       Erased.insert(I);
3624       State.reset(Def, Res, Part);
3625     }
3626   }
3627 
3628   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3629   for (const auto &KV : Cost->getMinimalBitwidths()) {
3630     // If the value wasn't vectorized, we must maintain the original scalar
3631     // type. The absence of the value from State indicates that it
3632     // wasn't vectorized.
3633     // FIXME: Should not rely on getVPValue at this point.
3634     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3635     if (!State.hasAnyVectorValue(Def))
3636       continue;
3637     for (unsigned Part = 0; Part < UF; ++Part) {
3638       Value *I = State.get(Def, Part);
3639       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3640       if (Inst && Inst->use_empty()) {
3641         Value *NewI = Inst->getOperand(0);
3642         Inst->eraseFromParent();
3643         State.reset(Def, NewI, Part);
3644       }
3645     }
3646   }
3647 }
3648 
3649 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State,
3650                                             VPlan &Plan) {
3651   // Insert truncates and extends for any truncated instructions as hints to
3652   // InstCombine.
3653   if (VF.isVector())
3654     truncateToMinimalBitwidths(State);
3655 
3656   // Fix widened non-induction PHIs by setting up the PHI operands.
3657   if (EnableVPlanNativePath)
3658     fixNonInductionPHIs(Plan, State);
3659 
3660   // At this point every instruction in the original loop is widened to a
3661   // vector form. Now we need to fix the recurrences in the loop. These PHI
3662   // nodes are currently empty because we did not want to introduce cycles.
3663   // This is the second stage of vectorizing recurrences.
3664   fixCrossIterationPHIs(State);
3665 
3666   // Forget the original basic block.
3667   PSE.getSE()->forgetLoop(OrigLoop);
3668 
3669   VPBasicBlock *LatchVPBB = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3670   Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3671   if (Cost->requiresScalarEpilogue(VF)) {
3672     // No edge from the middle block to the unique exit block has been inserted
3673     // and there is nothing to fix from vector loop; phis should have incoming
3674     // from scalar loop only.
3675     Plan.clearLiveOuts();
3676   } else {
3677     // If we inserted an edge from the middle block to the unique exit block,
3678     // update uses outside the loop (phis) to account for the newly inserted
3679     // edge.
3680 
3681     // Fix-up external users of the induction variables.
3682     for (auto &Entry : Legal->getInductionVars())
3683       fixupIVUsers(Entry.first, Entry.second,
3684                    getOrCreateVectorTripCount(VectorLoop->getLoopPreheader()),
3685                    IVEndValues[Entry.first], LoopMiddleBlock,
3686                    VectorLoop->getHeader(), Plan);
3687   }
3688 
3689   // Fix LCSSA phis not already fixed earlier. Extracts may need to be generated
3690   // in the exit block, so update the builder.
3691   State.Builder.SetInsertPoint(State.CFG.ExitBB->getFirstNonPHI());
3692   for (auto &KV : Plan.getLiveOuts())
3693     KV.second->fixPhi(Plan, State);
3694 
3695   for (Instruction *PI : PredicatedInstructions)
3696     sinkScalarOperands(&*PI);
3697 
3698   // Remove redundant induction instructions.
3699   cse(VectorLoop->getHeader());
3700 
3701   // Set/update profile weights for the vector and remainder loops as original
3702   // loop iterations are now distributed among them. Note that original loop
3703   // represented by LoopScalarBody becomes remainder loop after vectorization.
3704   //
3705   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3706   // end up getting slightly roughened result but that should be OK since
3707   // profile is not inherently precise anyway. Note also possible bypass of
3708   // vector code caused by legality checks is ignored, assigning all the weight
3709   // to the vector loop, optimistically.
3710   //
3711   // For scalable vectorization we can't know at compile time how many iterations
3712   // of the loop are handled in one vector iteration, so instead assume a pessimistic
3713   // vscale of '1'.
3714   setProfileInfoAfterUnrolling(LI->getLoopFor(LoopScalarBody), VectorLoop,
3715                                LI->getLoopFor(LoopScalarBody),
3716                                VF.getKnownMinValue() * UF);
3717 }
3718 
3719 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
3720   // In order to support recurrences we need to be able to vectorize Phi nodes.
3721   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3722   // stage #2: We now need to fix the recurrences by adding incoming edges to
3723   // the currently empty PHI nodes. At this point every instruction in the
3724   // original loop is widened to a vector form so we can use them to construct
3725   // the incoming edges.
3726   VPBasicBlock *Header =
3727       State.Plan->getVectorLoopRegion()->getEntryBasicBlock();
3728   for (VPRecipeBase &R : Header->phis()) {
3729     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3730       fixReduction(ReductionPhi, State);
3731     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3732       fixFirstOrderRecurrence(FOR, State);
3733   }
3734 }
3735 
3736 void InnerLoopVectorizer::fixFirstOrderRecurrence(
3737     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
3738   // This is the second phase of vectorizing first-order recurrences. An
3739   // overview of the transformation is described below. Suppose we have the
3740   // following loop.
3741   //
3742   //   for (int i = 0; i < n; ++i)
3743   //     b[i] = a[i] - a[i - 1];
3744   //
3745   // There is a first-order recurrence on "a". For this loop, the shorthand
3746   // scalar IR looks like:
3747   //
3748   //   scalar.ph:
3749   //     s_init = a[-1]
3750   //     br scalar.body
3751   //
3752   //   scalar.body:
3753   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3754   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3755   //     s2 = a[i]
3756   //     b[i] = s2 - s1
3757   //     br cond, scalar.body, ...
3758   //
3759   // In this example, s1 is a recurrence because it's value depends on the
3760   // previous iteration. In the first phase of vectorization, we created a
3761   // vector phi v1 for s1. We now complete the vectorization and produce the
3762   // shorthand vector IR shown below (for VF = 4, UF = 1).
3763   //
3764   //   vector.ph:
3765   //     v_init = vector(..., ..., ..., a[-1])
3766   //     br vector.body
3767   //
3768   //   vector.body
3769   //     i = phi [0, vector.ph], [i+4, vector.body]
3770   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3771   //     v2 = a[i, i+1, i+2, i+3];
3772   //     v3 = vector(v1(3), v2(0, 1, 2))
3773   //     b[i, i+1, i+2, i+3] = v2 - v3
3774   //     br cond, vector.body, middle.block
3775   //
3776   //   middle.block:
3777   //     x = v2(3)
3778   //     br scalar.ph
3779   //
3780   //   scalar.ph:
3781   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3782   //     br scalar.body
3783   //
3784   // After execution completes the vector loop, we extract the next value of
3785   // the recurrence (x) to use as the initial value in the scalar loop.
3786 
3787   // Extract the last vector element in the middle block. This will be the
3788   // initial value for the recurrence when jumping to the scalar loop.
3789   VPValue *PreviousDef = PhiR->getBackedgeValue();
3790   Value *Incoming = State.get(PreviousDef, UF - 1);
3791   auto *ExtractForScalar = Incoming;
3792   auto *IdxTy = Builder.getInt32Ty();
3793   if (VF.isVector()) {
3794     auto *One = ConstantInt::get(IdxTy, 1);
3795     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3796     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3797     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3798     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3799                                                     "vector.recur.extract");
3800   }
3801   // Extract the second last element in the middle block if the
3802   // Phi is used outside the loop. We need to extract the phi itself
3803   // and not the last element (the phi update in the current iteration). This
3804   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3805   // when the scalar loop is not run at all.
3806   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3807   if (VF.isVector()) {
3808     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3809     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3810     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3811         Incoming, Idx, "vector.recur.extract.for.phi");
3812   } else if (UF > 1)
3813     // When loop is unrolled without vectorizing, initialize
3814     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3815     // of `Incoming`. This is analogous to the vectorized case above: extracting
3816     // the second last element when VF > 1.
3817     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3818 
3819   // Fix the initial value of the original recurrence in the scalar loop.
3820   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3821   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3822   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3823   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3824   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3825     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3826     Start->addIncoming(Incoming, BB);
3827   }
3828 
3829   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3830   Phi->setName("scalar.recur");
3831 
3832   // Finally, fix users of the recurrence outside the loop. The users will need
3833   // either the last value of the scalar recurrence or the last value of the
3834   // vector recurrence we extracted in the middle block. Since the loop is in
3835   // LCSSA form, we just need to find all the phi nodes for the original scalar
3836   // recurrence in the exit block, and then add an edge for the middle block.
3837   // Note that LCSSA does not imply single entry when the original scalar loop
3838   // had multiple exiting edges (as we always run the last iteration in the
3839   // scalar epilogue); in that case, there is no edge from middle to exit and
3840   // and thus no phis which needed updated.
3841   if (!Cost->requiresScalarEpilogue(VF))
3842     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3843       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi)) {
3844         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3845         State.Plan->removeLiveOut(&LCSSAPhi);
3846       }
3847 }
3848 
3849 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
3850                                        VPTransformState &State) {
3851   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3852   // Get it's reduction variable descriptor.
3853   assert(Legal->isReductionVariable(OrigPhi) &&
3854          "Unable to find the reduction variable");
3855   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3856 
3857   RecurKind RK = RdxDesc.getRecurrenceKind();
3858   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3859   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3860   State.setDebugLocFromInst(ReductionStartValue);
3861 
3862   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3863   // This is the vector-clone of the value that leaves the loop.
3864   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3865 
3866   // Wrap flags are in general invalid after vectorization, clear them.
3867   clearReductionWrapFlags(PhiR, State);
3868 
3869   // Before each round, move the insertion point right between
3870   // the PHIs and the values we are going to write.
3871   // This allows us to write both PHINodes and the extractelement
3872   // instructions.
3873   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3874 
3875   State.setDebugLocFromInst(LoopExitInst);
3876 
3877   Type *PhiTy = OrigPhi->getType();
3878 
3879   VPBasicBlock *LatchVPBB =
3880       PhiR->getParent()->getEnclosingLoopRegion()->getExitingBasicBlock();
3881   BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3882   // If tail is folded by masking, the vector value to leave the loop should be
3883   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3884   // instead of the former. For an inloop reduction the reduction will already
3885   // be predicated, and does not need to be handled here.
3886   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3887     for (unsigned Part = 0; Part < UF; ++Part) {
3888       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3889       SelectInst *Sel = nullptr;
3890       for (User *U : VecLoopExitInst->users()) {
3891         if (isa<SelectInst>(U)) {
3892           assert(!Sel && "Reduction exit feeding two selects");
3893           Sel = cast<SelectInst>(U);
3894         } else
3895           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3896       }
3897       assert(Sel && "Reduction exit feeds no select");
3898       State.reset(LoopExitInstDef, Sel, Part);
3899 
3900       if (isa<FPMathOperator>(Sel))
3901         Sel->setFastMathFlags(RdxDesc.getFastMathFlags());
3902 
3903       // If the target can create a predicated operator for the reduction at no
3904       // extra cost in the loop (for example a predicated vadd), it can be
3905       // cheaper for the select to remain in the loop than be sunk out of it,
3906       // and so use the select value for the phi instead of the old
3907       // LoopExitValue.
3908       if (PreferPredicatedReductionSelect ||
3909           TTI->preferPredicatedReductionSelect(
3910               RdxDesc.getOpcode(), PhiTy,
3911               TargetTransformInfo::ReductionFlags())) {
3912         auto *VecRdxPhi =
3913             cast<PHINode>(State.get(PhiR, Part));
3914         VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3915       }
3916     }
3917   }
3918 
3919   // If the vector reduction can be performed in a smaller type, we truncate
3920   // then extend the loop exit value to enable InstCombine to evaluate the
3921   // entire expression in the smaller type.
3922   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3923     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3924     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3925     Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3926     VectorParts RdxParts(UF);
3927     for (unsigned Part = 0; Part < UF; ++Part) {
3928       RdxParts[Part] = State.get(LoopExitInstDef, Part);
3929       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3930       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3931                                         : Builder.CreateZExt(Trunc, VecTy);
3932       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3933         if (U != Trunc) {
3934           U->replaceUsesOfWith(RdxParts[Part], Extnd);
3935           RdxParts[Part] = Extnd;
3936         }
3937     }
3938     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3939     for (unsigned Part = 0; Part < UF; ++Part) {
3940       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3941       State.reset(LoopExitInstDef, RdxParts[Part], Part);
3942     }
3943   }
3944 
3945   // Reduce all of the unrolled parts into a single vector.
3946   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3947   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3948 
3949   // The middle block terminator has already been assigned a DebugLoc here (the
3950   // OrigLoop's single latch terminator). We want the whole middle block to
3951   // appear to execute on this line because: (a) it is all compiler generated,
3952   // (b) these instructions are always executed after evaluating the latch
3953   // conditional branch, and (c) other passes may add new predecessors which
3954   // terminate on this line. This is the easiest way to ensure we don't
3955   // accidentally cause an extra step back into the loop while debugging.
3956   State.setDebugLocFromInst(LoopMiddleBlock->getTerminator());
3957   if (PhiR->isOrdered())
3958     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3959   else {
3960     // Floating-point operations should have some FMF to enable the reduction.
3961     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
3962     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
3963     for (unsigned Part = 1; Part < UF; ++Part) {
3964       Value *RdxPart = State.get(LoopExitInstDef, Part);
3965       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3966         ReducedPartRdx = Builder.CreateBinOp(
3967             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3968       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
3969         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3970                                            ReducedPartRdx, RdxPart);
3971       else
3972         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3973     }
3974   }
3975 
3976   // Create the reduction after the loop. Note that inloop reductions create the
3977   // target reduction in the loop using a Reduction recipe.
3978   if (VF.isVector() && !PhiR->isInLoop()) {
3979     ReducedPartRdx =
3980         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3981     // If the reduction can be performed in a smaller type, we need to extend
3982     // the reduction to the wider type before we branch to the original loop.
3983     if (PhiTy != RdxDesc.getRecurrenceType())
3984       ReducedPartRdx = RdxDesc.isSigned()
3985                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
3986                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
3987   }
3988 
3989   PHINode *ResumePhi =
3990       dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
3991 
3992   // Create a phi node that merges control-flow from the backedge-taken check
3993   // block and the middle block.
3994   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
3995                                         LoopScalarPreHeader->getTerminator());
3996 
3997   // If we are fixing reductions in the epilogue loop then we should already
3998   // have created a bc.merge.rdx Phi after the main vector body. Ensure that
3999   // we carry over the incoming values correctly.
4000   for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
4001     if (Incoming == LoopMiddleBlock)
4002       BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4003     else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4004       BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4005                               Incoming);
4006     else
4007       BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4008   }
4009 
4010   // Set the resume value for this reduction
4011   ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4012 
4013   // If there were stores of the reduction value to a uniform memory address
4014   // inside the loop, create the final store here.
4015   if (StoreInst *SI = RdxDesc.IntermediateStore) {
4016     StoreInst *NewSI =
4017         Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4018     propagateMetadata(NewSI, SI);
4019 
4020     // If the reduction value is used in other places,
4021     // then let the code below create PHI's for that.
4022   }
4023 
4024   // Now, we need to fix the users of the reduction variable
4025   // inside and outside of the scalar remainder loop.
4026 
4027   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4028   // in the exit blocks.  See comment on analogous loop in
4029   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4030   if (!Cost->requiresScalarEpilogue(VF))
4031     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4032       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst)) {
4033         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4034         State.Plan->removeLiveOut(&LCSSAPhi);
4035       }
4036 
4037   // Fix the scalar loop reduction variable with the incoming reduction sum
4038   // from the vector body and from the backedge value.
4039   int IncomingEdgeBlockIdx =
4040       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4041   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4042   // Pick the other block.
4043   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4044   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4045   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4046 }
4047 
4048 void InnerLoopVectorizer::clearReductionWrapFlags(VPReductionPHIRecipe *PhiR,
4049                                                   VPTransformState &State) {
4050   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4051   RecurKind RK = RdxDesc.getRecurrenceKind();
4052   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4053     return;
4054 
4055   SmallVector<VPValue *, 8> Worklist;
4056   SmallPtrSet<VPValue *, 8> Visited;
4057   Worklist.push_back(PhiR);
4058   Visited.insert(PhiR);
4059 
4060   while (!Worklist.empty()) {
4061     VPValue *Cur = Worklist.pop_back_val();
4062     for (unsigned Part = 0; Part < UF; ++Part) {
4063       Value *V = State.get(Cur, Part);
4064       if (!isa<OverflowingBinaryOperator>(V))
4065         break;
4066       cast<Instruction>(V)->dropPoisonGeneratingFlags();
4067       }
4068 
4069       for (VPUser *U : Cur->users()) {
4070         auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
4071         if (!UserRecipe)
4072           continue;
4073         for (VPValue *V : UserRecipe->definedValues())
4074           if (Visited.insert(V).second)
4075             Worklist.push_back(V);
4076       }
4077   }
4078 }
4079 
4080 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4081   // The basic block and loop containing the predicated instruction.
4082   auto *PredBB = PredInst->getParent();
4083   auto *VectorLoop = LI->getLoopFor(PredBB);
4084 
4085   // Initialize a worklist with the operands of the predicated instruction.
4086   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4087 
4088   // Holds instructions that we need to analyze again. An instruction may be
4089   // reanalyzed if we don't yet know if we can sink it or not.
4090   SmallVector<Instruction *, 8> InstsToReanalyze;
4091 
4092   // Returns true if a given use occurs in the predicated block. Phi nodes use
4093   // their operands in their corresponding predecessor blocks.
4094   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4095     auto *I = cast<Instruction>(U.getUser());
4096     BasicBlock *BB = I->getParent();
4097     if (auto *Phi = dyn_cast<PHINode>(I))
4098       BB = Phi->getIncomingBlock(
4099           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4100     return BB == PredBB;
4101   };
4102 
4103   // Iteratively sink the scalarized operands of the predicated instruction
4104   // into the block we created for it. When an instruction is sunk, it's
4105   // operands are then added to the worklist. The algorithm ends after one pass
4106   // through the worklist doesn't sink a single instruction.
4107   bool Changed;
4108   do {
4109     // Add the instructions that need to be reanalyzed to the worklist, and
4110     // reset the changed indicator.
4111     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4112     InstsToReanalyze.clear();
4113     Changed = false;
4114 
4115     while (!Worklist.empty()) {
4116       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4117 
4118       // We can't sink an instruction if it is a phi node, is not in the loop,
4119       // or may have side effects.
4120       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4121           I->mayHaveSideEffects())
4122         continue;
4123 
4124       // If the instruction is already in PredBB, check if we can sink its
4125       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4126       // sinking the scalar instruction I, hence it appears in PredBB; but it
4127       // may have failed to sink I's operands (recursively), which we try
4128       // (again) here.
4129       if (I->getParent() == PredBB) {
4130         Worklist.insert(I->op_begin(), I->op_end());
4131         continue;
4132       }
4133 
4134       // It's legal to sink the instruction if all its uses occur in the
4135       // predicated block. Otherwise, there's nothing to do yet, and we may
4136       // need to reanalyze the instruction.
4137       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4138         InstsToReanalyze.push_back(I);
4139         continue;
4140       }
4141 
4142       // Move the instruction to the beginning of the predicated block, and add
4143       // it's operands to the worklist.
4144       I->moveBefore(&*PredBB->getFirstInsertionPt());
4145       Worklist.insert(I->op_begin(), I->op_end());
4146 
4147       // The sinking may have enabled other instructions to be sunk, so we will
4148       // need to iterate.
4149       Changed = true;
4150     }
4151   } while (Changed);
4152 }
4153 
4154 void InnerLoopVectorizer::fixNonInductionPHIs(VPlan &Plan,
4155                                               VPTransformState &State) {
4156   auto Iter = depth_first(
4157       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()));
4158   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
4159     for (VPRecipeBase &P : VPBB->phis()) {
4160       VPWidenPHIRecipe *VPPhi = dyn_cast<VPWidenPHIRecipe>(&P);
4161       if (!VPPhi)
4162         continue;
4163       PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4164       // Make sure the builder has a valid insert point.
4165       Builder.SetInsertPoint(NewPhi);
4166       for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4167         VPValue *Inc = VPPhi->getIncomingValue(i);
4168         VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4169         NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4170       }
4171     }
4172   }
4173 }
4174 
4175 bool InnerLoopVectorizer::useOrderedReductions(
4176     const RecurrenceDescriptor &RdxDesc) {
4177   return Cost->useOrderedReductions(RdxDesc);
4178 }
4179 
4180 void InnerLoopVectorizer::widenCallInstruction(CallInst &CI, VPValue *Def,
4181                                                VPUser &ArgOperands,
4182                                                VPTransformState &State) {
4183   assert(!isa<DbgInfoIntrinsic>(CI) &&
4184          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4185   State.setDebugLocFromInst(&CI);
4186 
4187   SmallVector<Type *, 4> Tys;
4188   for (Value *ArgOperand : CI.args())
4189     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4190 
4191   Intrinsic::ID ID = getVectorIntrinsicIDForCall(&CI, TLI);
4192 
4193   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4194   // version of the instruction.
4195   // Is it beneficial to perform intrinsic call compared to lib call?
4196   bool NeedToScalarize = false;
4197   InstructionCost CallCost = Cost->getVectorCallCost(&CI, VF, NeedToScalarize);
4198   InstructionCost IntrinsicCost =
4199       ID ? Cost->getVectorIntrinsicCost(&CI, VF) : 0;
4200   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4201   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4202          "Instruction should be scalarized elsewhere.");
4203   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4204          "Either the intrinsic cost or vector call cost must be valid");
4205 
4206   for (unsigned Part = 0; Part < UF; ++Part) {
4207     SmallVector<Type *, 2> TysForDecl = {CI.getType()};
4208     SmallVector<Value *, 4> Args;
4209     for (auto &I : enumerate(ArgOperands.operands())) {
4210       // Some intrinsics have a scalar argument - don't replace it with a
4211       // vector.
4212       Value *Arg;
4213       if (!UseVectorIntrinsic ||
4214           !isVectorIntrinsicWithScalarOpAtArg(ID, I.index()))
4215         Arg = State.get(I.value(), Part);
4216       else
4217         Arg = State.get(I.value(), VPIteration(0, 0));
4218       if (isVectorIntrinsicWithOverloadTypeAtArg(ID, I.index()))
4219         TysForDecl.push_back(Arg->getType());
4220       Args.push_back(Arg);
4221     }
4222 
4223     Function *VectorF;
4224     if (UseVectorIntrinsic) {
4225       // Use vector version of the intrinsic.
4226       if (VF.isVector())
4227         TysForDecl[0] = VectorType::get(CI.getType()->getScalarType(), VF);
4228       Module *M = State.Builder.GetInsertBlock()->getModule();
4229       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4230       assert(VectorF && "Can't retrieve vector intrinsic.");
4231     } else {
4232       // Use vector version of the function call.
4233       const VFShape Shape = VFShape::get(CI, VF, false /*HasGlobalPred*/);
4234 #ifndef NDEBUG
4235       assert(VFDatabase(CI).getVectorizedFunction(Shape) != nullptr &&
4236              "Can't create vector function.");
4237 #endif
4238       VectorF = VFDatabase(CI).getVectorizedFunction(Shape);
4239     }
4240       SmallVector<OperandBundleDef, 1> OpBundles;
4241       CI.getOperandBundlesAsDefs(OpBundles);
4242       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4243 
4244       if (isa<FPMathOperator>(V))
4245         V->copyFastMathFlags(&CI);
4246 
4247       State.set(Def, V, Part);
4248       State.addMetadata(V, &CI);
4249   }
4250 }
4251 
4252 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4253   // We should not collect Scalars more than once per VF. Right now, this
4254   // function is called from collectUniformsAndScalars(), which already does
4255   // this check. Collecting Scalars for VF=1 does not make any sense.
4256   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4257          "This function should not be visited twice for the same VF");
4258 
4259   // This avoids any chances of creating a REPLICATE recipe during planning
4260   // since that would result in generation of scalarized code during execution,
4261   // which is not supported for scalable vectors.
4262   if (VF.isScalable()) {
4263     Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4264     return;
4265   }
4266 
4267   SmallSetVector<Instruction *, 8> Worklist;
4268 
4269   // These sets are used to seed the analysis with pointers used by memory
4270   // accesses that will remain scalar.
4271   SmallSetVector<Instruction *, 8> ScalarPtrs;
4272   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4273   auto *Latch = TheLoop->getLoopLatch();
4274 
4275   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4276   // The pointer operands of loads and stores will be scalar as long as the
4277   // memory access is not a gather or scatter operation. The value operand of a
4278   // store will remain scalar if the store is scalarized.
4279   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4280     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4281     assert(WideningDecision != CM_Unknown &&
4282            "Widening decision should be ready at this moment");
4283     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4284       if (Ptr == Store->getValueOperand())
4285         return WideningDecision == CM_Scalarize;
4286     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4287            "Ptr is neither a value or pointer operand");
4288     return WideningDecision != CM_GatherScatter;
4289   };
4290 
4291   // A helper that returns true if the given value is a bitcast or
4292   // getelementptr instruction contained in the loop.
4293   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4294     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4295             isa<GetElementPtrInst>(V)) &&
4296            !TheLoop->isLoopInvariant(V);
4297   };
4298 
4299   // A helper that evaluates a memory access's use of a pointer. If the use will
4300   // be a scalar use and the pointer is only used by memory accesses, we place
4301   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4302   // PossibleNonScalarPtrs.
4303   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4304     // We only care about bitcast and getelementptr instructions contained in
4305     // the loop.
4306     if (!isLoopVaryingBitCastOrGEP(Ptr))
4307       return;
4308 
4309     // If the pointer has already been identified as scalar (e.g., if it was
4310     // also identified as uniform), there's nothing to do.
4311     auto *I = cast<Instruction>(Ptr);
4312     if (Worklist.count(I))
4313       return;
4314 
4315     // If the use of the pointer will be a scalar use, and all users of the
4316     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4317     // place the pointer in PossibleNonScalarPtrs.
4318     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4319           return isa<LoadInst>(U) || isa<StoreInst>(U);
4320         }))
4321       ScalarPtrs.insert(I);
4322     else
4323       PossibleNonScalarPtrs.insert(I);
4324   };
4325 
4326   // We seed the scalars analysis with three classes of instructions: (1)
4327   // instructions marked uniform-after-vectorization and (2) bitcast,
4328   // getelementptr and (pointer) phi instructions used by memory accesses
4329   // requiring a scalar use.
4330   //
4331   // (1) Add to the worklist all instructions that have been identified as
4332   // uniform-after-vectorization.
4333   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4334 
4335   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4336   // memory accesses requiring a scalar use. The pointer operands of loads and
4337   // stores will be scalar as long as the memory accesses is not a gather or
4338   // scatter operation. The value operand of a store will remain scalar if the
4339   // store is scalarized.
4340   for (auto *BB : TheLoop->blocks())
4341     for (auto &I : *BB) {
4342       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4343         evaluatePtrUse(Load, Load->getPointerOperand());
4344       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4345         evaluatePtrUse(Store, Store->getPointerOperand());
4346         evaluatePtrUse(Store, Store->getValueOperand());
4347       }
4348     }
4349   for (auto *I : ScalarPtrs)
4350     if (!PossibleNonScalarPtrs.count(I)) {
4351       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4352       Worklist.insert(I);
4353     }
4354 
4355   // Insert the forced scalars.
4356   // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
4357   // induction variable when the PHI user is scalarized.
4358   auto ForcedScalar = ForcedScalars.find(VF);
4359   if (ForcedScalar != ForcedScalars.end())
4360     for (auto *I : ForcedScalar->second)
4361       Worklist.insert(I);
4362 
4363   // Expand the worklist by looking through any bitcasts and getelementptr
4364   // instructions we've already identified as scalar. This is similar to the
4365   // expansion step in collectLoopUniforms(); however, here we're only
4366   // expanding to include additional bitcasts and getelementptr instructions.
4367   unsigned Idx = 0;
4368   while (Idx != Worklist.size()) {
4369     Instruction *Dst = Worklist[Idx++];
4370     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4371       continue;
4372     auto *Src = cast<Instruction>(Dst->getOperand(0));
4373     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4374           auto *J = cast<Instruction>(U);
4375           return !TheLoop->contains(J) || Worklist.count(J) ||
4376                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4377                   isScalarUse(J, Src));
4378         })) {
4379       Worklist.insert(Src);
4380       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4381     }
4382   }
4383 
4384   // An induction variable will remain scalar if all users of the induction
4385   // variable and induction variable update remain scalar.
4386   for (auto &Induction : Legal->getInductionVars()) {
4387     auto *Ind = Induction.first;
4388     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4389 
4390     // If tail-folding is applied, the primary induction variable will be used
4391     // to feed a vector compare.
4392     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4393       continue;
4394 
4395     // Returns true if \p Indvar is a pointer induction that is used directly by
4396     // load/store instruction \p I.
4397     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4398                                               Instruction *I) {
4399       return Induction.second.getKind() ==
4400                  InductionDescriptor::IK_PtrInduction &&
4401              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4402              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4403     };
4404 
4405     // Determine if all users of the induction variable are scalar after
4406     // vectorization.
4407     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4408       auto *I = cast<Instruction>(U);
4409       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4410              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4411     });
4412     if (!ScalarInd)
4413       continue;
4414 
4415     // Determine if all users of the induction variable update instruction are
4416     // scalar after vectorization.
4417     auto ScalarIndUpdate =
4418         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4419           auto *I = cast<Instruction>(U);
4420           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4421                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4422         });
4423     if (!ScalarIndUpdate)
4424       continue;
4425 
4426     // The induction variable and its update instruction will remain scalar.
4427     Worklist.insert(Ind);
4428     Worklist.insert(IndUpdate);
4429     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4430     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4431                       << "\n");
4432   }
4433 
4434   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4435 }
4436 
4437 bool LoopVectorizationCostModel::isScalarWithPredication(
4438     Instruction *I, ElementCount VF) const {
4439   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4440     return false;
4441   switch(I->getOpcode()) {
4442   default:
4443     break;
4444   case Instruction::Load:
4445   case Instruction::Store: {
4446     if (!Legal->isMaskRequired(I))
4447       return false;
4448     auto *Ptr = getLoadStorePointerOperand(I);
4449     auto *Ty = getLoadStoreType(I);
4450     Type *VTy = Ty;
4451     if (VF.isVector())
4452       VTy = VectorType::get(Ty, VF);
4453     const Align Alignment = getLoadStoreAlignment(I);
4454     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4455                                 TTI.isLegalMaskedGather(VTy, Alignment))
4456                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4457                                 TTI.isLegalMaskedScatter(VTy, Alignment));
4458   }
4459   case Instruction::UDiv:
4460   case Instruction::SDiv:
4461   case Instruction::SRem:
4462   case Instruction::URem:
4463     // TODO: We can use the loop-preheader as context point here and get
4464     // context sensitive reasoning
4465     return !isSafeToSpeculativelyExecute(I);
4466   }
4467   return false;
4468 }
4469 
4470 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4471     Instruction *I, ElementCount VF) {
4472   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4473   assert(getWideningDecision(I, VF) == CM_Unknown &&
4474          "Decision should not be set yet.");
4475   auto *Group = getInterleavedAccessGroup(I);
4476   assert(Group && "Must have a group.");
4477 
4478   // If the instruction's allocated size doesn't equal it's type size, it
4479   // requires padding and will be scalarized.
4480   auto &DL = I->getModule()->getDataLayout();
4481   auto *ScalarTy = getLoadStoreType(I);
4482   if (hasIrregularType(ScalarTy, DL))
4483     return false;
4484 
4485   // If the group involves a non-integral pointer, we may not be able to
4486   // losslessly cast all values to a common type.
4487   unsigned InterleaveFactor = Group->getFactor();
4488   bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
4489   for (unsigned i = 0; i < InterleaveFactor; i++) {
4490     Instruction *Member = Group->getMember(i);
4491     if (!Member)
4492       continue;
4493     auto *MemberTy = getLoadStoreType(Member);
4494     bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
4495     // Don't coerce non-integral pointers to integers or vice versa.
4496     if (MemberNI != ScalarNI) {
4497       // TODO: Consider adding special nullptr value case here
4498       return false;
4499     } else if (MemberNI && ScalarNI &&
4500                ScalarTy->getPointerAddressSpace() !=
4501                MemberTy->getPointerAddressSpace()) {
4502       return false;
4503     }
4504   }
4505 
4506   // Check if masking is required.
4507   // A Group may need masking for one of two reasons: it resides in a block that
4508   // needs predication, or it was decided to use masking to deal with gaps
4509   // (either a gap at the end of a load-access that may result in a speculative
4510   // load, or any gaps in a store-access).
4511   bool PredicatedAccessRequiresMasking =
4512       blockNeedsPredicationForAnyReason(I->getParent()) &&
4513       Legal->isMaskRequired(I);
4514   bool LoadAccessWithGapsRequiresEpilogMasking =
4515       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4516       !isScalarEpilogueAllowed();
4517   bool StoreAccessWithGapsRequiresMasking =
4518       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4519   if (!PredicatedAccessRequiresMasking &&
4520       !LoadAccessWithGapsRequiresEpilogMasking &&
4521       !StoreAccessWithGapsRequiresMasking)
4522     return true;
4523 
4524   // If masked interleaving is required, we expect that the user/target had
4525   // enabled it, because otherwise it either wouldn't have been created or
4526   // it should have been invalidated by the CostModel.
4527   assert(useMaskedInterleavedAccesses(TTI) &&
4528          "Masked interleave-groups for predicated accesses are not enabled.");
4529 
4530   if (Group->isReverse())
4531     return false;
4532 
4533   auto *Ty = getLoadStoreType(I);
4534   const Align Alignment = getLoadStoreAlignment(I);
4535   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4536                           : TTI.isLegalMaskedStore(Ty, Alignment);
4537 }
4538 
4539 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4540     Instruction *I, ElementCount VF) {
4541   // Get and ensure we have a valid memory instruction.
4542   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4543 
4544   auto *Ptr = getLoadStorePointerOperand(I);
4545   auto *ScalarTy = getLoadStoreType(I);
4546 
4547   // In order to be widened, the pointer should be consecutive, first of all.
4548   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4549     return false;
4550 
4551   // If the instruction is a store located in a predicated block, it will be
4552   // scalarized.
4553   if (isScalarWithPredication(I, VF))
4554     return false;
4555 
4556   // If the instruction's allocated size doesn't equal it's type size, it
4557   // requires padding and will be scalarized.
4558   auto &DL = I->getModule()->getDataLayout();
4559   if (hasIrregularType(ScalarTy, DL))
4560     return false;
4561 
4562   return true;
4563 }
4564 
4565 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4566   // We should not collect Uniforms more than once per VF. Right now,
4567   // this function is called from collectUniformsAndScalars(), which
4568   // already does this check. Collecting Uniforms for VF=1 does not make any
4569   // sense.
4570 
4571   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4572          "This function should not be visited twice for the same VF");
4573 
4574   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4575   // not analyze again.  Uniforms.count(VF) will return 1.
4576   Uniforms[VF].clear();
4577 
4578   // We now know that the loop is vectorizable!
4579   // Collect instructions inside the loop that will remain uniform after
4580   // vectorization.
4581 
4582   // Global values, params and instructions outside of current loop are out of
4583   // scope.
4584   auto isOutOfScope = [&](Value *V) -> bool {
4585     Instruction *I = dyn_cast<Instruction>(V);
4586     return (!I || !TheLoop->contains(I));
4587   };
4588 
4589   // Worklist containing uniform instructions demanding lane 0.
4590   SetVector<Instruction *> Worklist;
4591   BasicBlock *Latch = TheLoop->getLoopLatch();
4592 
4593   // Add uniform instructions demanding lane 0 to the worklist. Instructions
4594   // that are scalar with predication must not be considered uniform after
4595   // vectorization, because that would create an erroneous replicating region
4596   // where only a single instance out of VF should be formed.
4597   // TODO: optimize such seldom cases if found important, see PR40816.
4598   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4599     if (isOutOfScope(I)) {
4600       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4601                         << *I << "\n");
4602       return;
4603     }
4604     if (isScalarWithPredication(I, VF)) {
4605       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4606                         << *I << "\n");
4607       return;
4608     }
4609     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4610     Worklist.insert(I);
4611   };
4612 
4613   // Start with the conditional branch. If the branch condition is an
4614   // instruction contained in the loop that is only used by the branch, it is
4615   // uniform.
4616   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4617   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4618     addToWorklistIfAllowed(Cmp);
4619 
4620   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
4621     InstWidening WideningDecision = getWideningDecision(I, VF);
4622     assert(WideningDecision != CM_Unknown &&
4623            "Widening decision should be ready at this moment");
4624 
4625     // A uniform memory op is itself uniform.  We exclude uniform stores
4626     // here as they demand the last lane, not the first one.
4627     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
4628       assert(WideningDecision == CM_Scalarize);
4629       return true;
4630     }
4631 
4632     return (WideningDecision == CM_Widen ||
4633             WideningDecision == CM_Widen_Reverse ||
4634             WideningDecision == CM_Interleave);
4635   };
4636 
4637 
4638   // Returns true if Ptr is the pointer operand of a memory access instruction
4639   // I, and I is known to not require scalarization.
4640   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4641     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4642   };
4643 
4644   // Holds a list of values which are known to have at least one uniform use.
4645   // Note that there may be other uses which aren't uniform.  A "uniform use"
4646   // here is something which only demands lane 0 of the unrolled iterations;
4647   // it does not imply that all lanes produce the same value (e.g. this is not
4648   // the usual meaning of uniform)
4649   SetVector<Value *> HasUniformUse;
4650 
4651   // Scan the loop for instructions which are either a) known to have only
4652   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
4653   for (auto *BB : TheLoop->blocks())
4654     for (auto &I : *BB) {
4655       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
4656         switch (II->getIntrinsicID()) {
4657         case Intrinsic::sideeffect:
4658         case Intrinsic::experimental_noalias_scope_decl:
4659         case Intrinsic::assume:
4660         case Intrinsic::lifetime_start:
4661         case Intrinsic::lifetime_end:
4662           if (TheLoop->hasLoopInvariantOperands(&I))
4663             addToWorklistIfAllowed(&I);
4664           break;
4665         default:
4666           break;
4667         }
4668       }
4669 
4670       // ExtractValue instructions must be uniform, because the operands are
4671       // known to be loop-invariant.
4672       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
4673         assert(isOutOfScope(EVI->getAggregateOperand()) &&
4674                "Expected aggregate value to be loop invariant");
4675         addToWorklistIfAllowed(EVI);
4676         continue;
4677       }
4678 
4679       // If there's no pointer operand, there's nothing to do.
4680       auto *Ptr = getLoadStorePointerOperand(&I);
4681       if (!Ptr)
4682         continue;
4683 
4684       // A uniform memory op is itself uniform.  We exclude uniform stores
4685       // here as they demand the last lane, not the first one.
4686       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
4687         addToWorklistIfAllowed(&I);
4688 
4689       if (isUniformDecision(&I, VF)) {
4690         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
4691         HasUniformUse.insert(Ptr);
4692       }
4693     }
4694 
4695   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
4696   // demanding) users.  Since loops are assumed to be in LCSSA form, this
4697   // disallows uses outside the loop as well.
4698   for (auto *V : HasUniformUse) {
4699     if (isOutOfScope(V))
4700       continue;
4701     auto *I = cast<Instruction>(V);
4702     auto UsersAreMemAccesses =
4703       llvm::all_of(I->users(), [&](User *U) -> bool {
4704         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4705       });
4706     if (UsersAreMemAccesses)
4707       addToWorklistIfAllowed(I);
4708   }
4709 
4710   // Expand Worklist in topological order: whenever a new instruction
4711   // is added , its users should be already inside Worklist.  It ensures
4712   // a uniform instruction will only be used by uniform instructions.
4713   unsigned idx = 0;
4714   while (idx != Worklist.size()) {
4715     Instruction *I = Worklist[idx++];
4716 
4717     for (auto OV : I->operand_values()) {
4718       // isOutOfScope operands cannot be uniform instructions.
4719       if (isOutOfScope(OV))
4720         continue;
4721       // First order recurrence Phi's should typically be considered
4722       // non-uniform.
4723       auto *OP = dyn_cast<PHINode>(OV);
4724       if (OP && Legal->isFirstOrderRecurrence(OP))
4725         continue;
4726       // If all the users of the operand are uniform, then add the
4727       // operand into the uniform worklist.
4728       auto *OI = cast<Instruction>(OV);
4729       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4730             auto *J = cast<Instruction>(U);
4731             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4732           }))
4733         addToWorklistIfAllowed(OI);
4734     }
4735   }
4736 
4737   // For an instruction to be added into Worklist above, all its users inside
4738   // the loop should also be in Worklist. However, this condition cannot be
4739   // true for phi nodes that form a cyclic dependence. We must process phi
4740   // nodes separately. An induction variable will remain uniform if all users
4741   // of the induction variable and induction variable update remain uniform.
4742   // The code below handles both pointer and non-pointer induction variables.
4743   for (auto &Induction : Legal->getInductionVars()) {
4744     auto *Ind = Induction.first;
4745     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4746 
4747     // Determine if all users of the induction variable are uniform after
4748     // vectorization.
4749     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4750       auto *I = cast<Instruction>(U);
4751       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4752              isVectorizedMemAccessUse(I, Ind);
4753     });
4754     if (!UniformInd)
4755       continue;
4756 
4757     // Determine if all users of the induction variable update instruction are
4758     // uniform after vectorization.
4759     auto UniformIndUpdate =
4760         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4761           auto *I = cast<Instruction>(U);
4762           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4763                  isVectorizedMemAccessUse(I, IndUpdate);
4764         });
4765     if (!UniformIndUpdate)
4766       continue;
4767 
4768     // The induction variable and its update instruction will remain uniform.
4769     addToWorklistIfAllowed(Ind);
4770     addToWorklistIfAllowed(IndUpdate);
4771   }
4772 
4773   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4774 }
4775 
4776 bool LoopVectorizationCostModel::runtimeChecksRequired() {
4777   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
4778 
4779   if (Legal->getRuntimePointerChecking()->Need) {
4780     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
4781         "runtime pointer checks needed. Enable vectorization of this "
4782         "loop with '#pragma clang loop vectorize(enable)' when "
4783         "compiling with -Os/-Oz",
4784         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4785     return true;
4786   }
4787 
4788   if (!PSE.getPredicate().isAlwaysTrue()) {
4789     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
4790         "runtime SCEV checks needed. Enable vectorization of this "
4791         "loop with '#pragma clang loop vectorize(enable)' when "
4792         "compiling with -Os/-Oz",
4793         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4794     return true;
4795   }
4796 
4797   // FIXME: Avoid specializing for stride==1 instead of bailing out.
4798   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
4799     reportVectorizationFailure("Runtime stride check for small trip count",
4800         "runtime stride == 1 checks needed. Enable vectorization of "
4801         "this loop without such check by compiling with -Os/-Oz",
4802         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4803     return true;
4804   }
4805 
4806   return false;
4807 }
4808 
4809 ElementCount
4810 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
4811   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
4812     return ElementCount::getScalable(0);
4813 
4814   if (Hints->isScalableVectorizationDisabled()) {
4815     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
4816                             "ScalableVectorizationDisabled", ORE, TheLoop);
4817     return ElementCount::getScalable(0);
4818   }
4819 
4820   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
4821 
4822   auto MaxScalableVF = ElementCount::getScalable(
4823       std::numeric_limits<ElementCount::ScalarTy>::max());
4824 
4825   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
4826   // FIXME: While for scalable vectors this is currently sufficient, this should
4827   // be replaced by a more detailed mechanism that filters out specific VFs,
4828   // instead of invalidating vectorization for a whole set of VFs based on the
4829   // MaxVF.
4830 
4831   // Disable scalable vectorization if the loop contains unsupported reductions.
4832   if (!canVectorizeReductions(MaxScalableVF)) {
4833     reportVectorizationInfo(
4834         "Scalable vectorization not supported for the reduction "
4835         "operations found in this loop.",
4836         "ScalableVFUnfeasible", ORE, TheLoop);
4837     return ElementCount::getScalable(0);
4838   }
4839 
4840   // Disable scalable vectorization if the loop contains any instructions
4841   // with element types not supported for scalable vectors.
4842   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
4843         return !Ty->isVoidTy() &&
4844                !this->TTI.isElementTypeLegalForScalableVector(Ty);
4845       })) {
4846     reportVectorizationInfo("Scalable vectorization is not supported "
4847                             "for all element types found in this loop.",
4848                             "ScalableVFUnfeasible", ORE, TheLoop);
4849     return ElementCount::getScalable(0);
4850   }
4851 
4852   if (Legal->isSafeForAnyVectorWidth())
4853     return MaxScalableVF;
4854 
4855   // Limit MaxScalableVF by the maximum safe dependence distance.
4856   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
4857   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
4858     MaxVScale =
4859         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
4860   MaxScalableVF = ElementCount::getScalable(
4861       MaxVScale ? (MaxSafeElements / MaxVScale.value()) : 0);
4862   if (!MaxScalableVF)
4863     reportVectorizationInfo(
4864         "Max legal vector width too small, scalable vectorization "
4865         "unfeasible.",
4866         "ScalableVFUnfeasible", ORE, TheLoop);
4867 
4868   return MaxScalableVF;
4869 }
4870 
4871 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
4872     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
4873   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4874   unsigned SmallestType, WidestType;
4875   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4876 
4877   // Get the maximum safe dependence distance in bits computed by LAA.
4878   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4879   // the memory accesses that is most restrictive (involved in the smallest
4880   // dependence distance).
4881   unsigned MaxSafeElements =
4882       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
4883 
4884   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
4885   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4886 
4887   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
4888                     << ".\n");
4889   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
4890                     << ".\n");
4891 
4892   // First analyze the UserVF, fall back if the UserVF should be ignored.
4893   if (UserVF) {
4894     auto MaxSafeUserVF =
4895         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4896 
4897     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
4898       // If `VF=vscale x N` is safe, then so is `VF=N`
4899       if (UserVF.isScalable())
4900         return FixedScalableVFPair(
4901             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
4902       else
4903         return UserVF;
4904     }
4905 
4906     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
4907 
4908     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
4909     // is better to ignore the hint and let the compiler choose a suitable VF.
4910     if (!UserVF.isScalable()) {
4911       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4912                         << " is unsafe, clamping to max safe VF="
4913                         << MaxSafeFixedVF << ".\n");
4914       ORE->emit([&]() {
4915         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4916                                           TheLoop->getStartLoc(),
4917                                           TheLoop->getHeader())
4918                << "User-specified vectorization factor "
4919                << ore::NV("UserVectorizationFactor", UserVF)
4920                << " is unsafe, clamping to maximum safe vectorization factor "
4921                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
4922       });
4923       return MaxSafeFixedVF;
4924     }
4925 
4926     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
4927       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4928                         << " is ignored because scalable vectors are not "
4929                            "available.\n");
4930       ORE->emit([&]() {
4931         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4932                                           TheLoop->getStartLoc(),
4933                                           TheLoop->getHeader())
4934                << "User-specified vectorization factor "
4935                << ore::NV("UserVectorizationFactor", UserVF)
4936                << " is ignored because the target does not support scalable "
4937                   "vectors. The compiler will pick a more suitable value.";
4938       });
4939     } else {
4940       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4941                         << " is unsafe. Ignoring scalable UserVF.\n");
4942       ORE->emit([&]() {
4943         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4944                                           TheLoop->getStartLoc(),
4945                                           TheLoop->getHeader())
4946                << "User-specified vectorization factor "
4947                << ore::NV("UserVectorizationFactor", UserVF)
4948                << " is unsafe. Ignoring the hint to let the compiler pick a "
4949                   "more suitable value.";
4950       });
4951     }
4952   }
4953 
4954   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
4955                     << " / " << WidestType << " bits.\n");
4956 
4957   FixedScalableVFPair Result(ElementCount::getFixed(1),
4958                              ElementCount::getScalable(0));
4959   if (auto MaxVF =
4960           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
4961                                   MaxSafeFixedVF, FoldTailByMasking))
4962     Result.FixedVF = MaxVF;
4963 
4964   if (auto MaxVF =
4965           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
4966                                   MaxSafeScalableVF, FoldTailByMasking))
4967     if (MaxVF.isScalable()) {
4968       Result.ScalableVF = MaxVF;
4969       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
4970                         << "\n");
4971     }
4972 
4973   return Result;
4974 }
4975 
4976 FixedScalableVFPair
4977 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
4978   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
4979     // TODO: It may by useful to do since it's still likely to be dynamically
4980     // uniform if the target can skip.
4981     reportVectorizationFailure(
4982         "Not inserting runtime ptr check for divergent target",
4983         "runtime pointer checks needed. Not enabled for divergent target",
4984         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
4985     return FixedScalableVFPair::getNone();
4986   }
4987 
4988   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
4989   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4990   if (TC == 1) {
4991     reportVectorizationFailure("Single iteration (non) loop",
4992         "loop trip count is one, irrelevant for vectorization",
4993         "SingleIterationLoop", ORE, TheLoop);
4994     return FixedScalableVFPair::getNone();
4995   }
4996 
4997   switch (ScalarEpilogueStatus) {
4998   case CM_ScalarEpilogueAllowed:
4999     return computeFeasibleMaxVF(TC, UserVF, false);
5000   case CM_ScalarEpilogueNotAllowedUsePredicate:
5001     LLVM_FALLTHROUGH;
5002   case CM_ScalarEpilogueNotNeededUsePredicate:
5003     LLVM_DEBUG(
5004         dbgs() << "LV: vector predicate hint/switch found.\n"
5005                << "LV: Not allowing scalar epilogue, creating predicated "
5006                << "vector loop.\n");
5007     break;
5008   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5009     // fallthrough as a special case of OptForSize
5010   case CM_ScalarEpilogueNotAllowedOptSize:
5011     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5012       LLVM_DEBUG(
5013           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5014     else
5015       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5016                         << "count.\n");
5017 
5018     // Bail if runtime checks are required, which are not good when optimising
5019     // for size.
5020     if (runtimeChecksRequired())
5021       return FixedScalableVFPair::getNone();
5022 
5023     break;
5024   }
5025 
5026   // The only loops we can vectorize without a scalar epilogue, are loops with
5027   // a bottom-test and a single exiting block. We'd have to handle the fact
5028   // that not every instruction executes on the last iteration.  This will
5029   // require a lane mask which varies through the vector loop body.  (TODO)
5030   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5031     // If there was a tail-folding hint/switch, but we can't fold the tail by
5032     // masking, fallback to a vectorization with a scalar epilogue.
5033     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5034       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5035                            "scalar epilogue instead.\n");
5036       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5037       return computeFeasibleMaxVF(TC, UserVF, false);
5038     }
5039     return FixedScalableVFPair::getNone();
5040   }
5041 
5042   // Now try the tail folding
5043 
5044   // Invalidate interleave groups that require an epilogue if we can't mask
5045   // the interleave-group.
5046   if (!useMaskedInterleavedAccesses(TTI)) {
5047     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5048            "No decisions should have been taken at this point");
5049     // Note: There is no need to invalidate any cost modeling decisions here, as
5050     // non where taken so far.
5051     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5052   }
5053 
5054   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5055   // Avoid tail folding if the trip count is known to be a multiple of any VF
5056   // we chose.
5057   // FIXME: The condition below pessimises the case for fixed-width vectors,
5058   // when scalable VFs are also candidates for vectorization.
5059   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5060     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5061     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5062            "MaxFixedVF must be a power of 2");
5063     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5064                                    : MaxFixedVF.getFixedValue();
5065     ScalarEvolution *SE = PSE.getSE();
5066     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5067     const SCEV *ExitCount = SE->getAddExpr(
5068         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5069     const SCEV *Rem = SE->getURemExpr(
5070         SE->applyLoopGuards(ExitCount, TheLoop),
5071         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5072     if (Rem->isZero()) {
5073       // Accept MaxFixedVF if we do not have a tail.
5074       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5075       return MaxFactors;
5076     }
5077   }
5078 
5079   // If we don't know the precise trip count, or if the trip count that we
5080   // found modulo the vectorization factor is not zero, try to fold the tail
5081   // by masking.
5082   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5083   if (Legal->prepareToFoldTailByMasking()) {
5084     FoldTailByMasking = true;
5085     return MaxFactors;
5086   }
5087 
5088   // If there was a tail-folding hint/switch, but we can't fold the tail by
5089   // masking, fallback to a vectorization with a scalar epilogue.
5090   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5091     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5092                          "scalar epilogue instead.\n");
5093     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5094     return MaxFactors;
5095   }
5096 
5097   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5098     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5099     return FixedScalableVFPair::getNone();
5100   }
5101 
5102   if (TC == 0) {
5103     reportVectorizationFailure(
5104         "Unable to calculate the loop count due to complex control flow",
5105         "unable to calculate the loop count due to complex control flow",
5106         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5107     return FixedScalableVFPair::getNone();
5108   }
5109 
5110   reportVectorizationFailure(
5111       "Cannot optimize for size and vectorize at the same time.",
5112       "cannot optimize for size and vectorize at the same time. "
5113       "Enable vectorization of this loop with '#pragma clang loop "
5114       "vectorize(enable)' when compiling with -Os/-Oz",
5115       "NoTailLoopWithOptForSize", ORE, TheLoop);
5116   return FixedScalableVFPair::getNone();
5117 }
5118 
5119 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5120     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5121     ElementCount MaxSafeVF, bool FoldTailByMasking) {
5122   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5123   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5124       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5125                            : TargetTransformInfo::RGK_FixedWidthVector);
5126 
5127   // Convenience function to return the minimum of two ElementCounts.
5128   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5129     assert((LHS.isScalable() == RHS.isScalable()) &&
5130            "Scalable flags must match");
5131     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5132   };
5133 
5134   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5135   // Note that both WidestRegister and WidestType may not be a powers of 2.
5136   auto MaxVectorElementCount = ElementCount::get(
5137       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5138       ComputeScalableMaxVF);
5139   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5140   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5141                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5142 
5143   if (!MaxVectorElementCount) {
5144     LLVM_DEBUG(dbgs() << "LV: The target has no "
5145                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5146                       << " vector registers.\n");
5147     return ElementCount::getFixed(1);
5148   }
5149 
5150   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5151   if (ConstTripCount &&
5152       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5153       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5154     // If loop trip count (TC) is known at compile time there is no point in
5155     // choosing VF greater than TC (as done in the loop below). Select maximum
5156     // power of two which doesn't exceed TC.
5157     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5158     // when the TC is less than or equal to the known number of lanes.
5159     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5160     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5161                          "exceeding the constant trip count: "
5162                       << ClampedConstTripCount << "\n");
5163     return ElementCount::getFixed(ClampedConstTripCount);
5164   }
5165 
5166   TargetTransformInfo::RegisterKind RegKind =
5167       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5168                            : TargetTransformInfo::RGK_FixedWidthVector;
5169   ElementCount MaxVF = MaxVectorElementCount;
5170   if (MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
5171                             TTI.shouldMaximizeVectorBandwidth(RegKind))) {
5172     auto MaxVectorElementCountMaxBW = ElementCount::get(
5173         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5174         ComputeScalableMaxVF);
5175     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5176 
5177     // Collect all viable vectorization factors larger than the default MaxVF
5178     // (i.e. MaxVectorElementCount).
5179     SmallVector<ElementCount, 8> VFs;
5180     for (ElementCount VS = MaxVectorElementCount * 2;
5181          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5182       VFs.push_back(VS);
5183 
5184     // For each VF calculate its register usage.
5185     auto RUs = calculateRegisterUsage(VFs);
5186 
5187     // Select the largest VF which doesn't require more registers than existing
5188     // ones.
5189     for (int i = RUs.size() - 1; i >= 0; --i) {
5190       bool Selected = true;
5191       for (auto &pair : RUs[i].MaxLocalUsers) {
5192         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5193         if (pair.second > TargetNumRegisters)
5194           Selected = false;
5195       }
5196       if (Selected) {
5197         MaxVF = VFs[i];
5198         break;
5199       }
5200     }
5201     if (ElementCount MinVF =
5202             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5203       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5204         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5205                           << ") with target's minimum: " << MinVF << '\n');
5206         MaxVF = MinVF;
5207       }
5208     }
5209 
5210     // Invalidate any widening decisions we might have made, in case the loop
5211     // requires prediction (decided later), but we have already made some
5212     // load/store widening decisions.
5213     invalidateCostModelingDecisions();
5214   }
5215   return MaxVF;
5216 }
5217 
5218 Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
5219   if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5220     auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
5221     auto Min = Attr.getVScaleRangeMin();
5222     auto Max = Attr.getVScaleRangeMax();
5223     if (Max && Min == Max)
5224       return Max;
5225   }
5226 
5227   return TTI.getVScaleForTuning();
5228 }
5229 
5230 bool LoopVectorizationCostModel::isMoreProfitable(
5231     const VectorizationFactor &A, const VectorizationFactor &B) const {
5232   InstructionCost CostA = A.Cost;
5233   InstructionCost CostB = B.Cost;
5234 
5235   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5236 
5237   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5238       MaxTripCount) {
5239     // If we are folding the tail and the trip count is a known (possibly small)
5240     // constant, the trip count will be rounded up to an integer number of
5241     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5242     // which we compare directly. When not folding the tail, the total cost will
5243     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5244     // approximated with the per-lane cost below instead of using the tripcount
5245     // as here.
5246     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5247     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5248     return RTCostA < RTCostB;
5249   }
5250 
5251   // Improve estimate for the vector width if it is scalable.
5252   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5253   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5254   if (Optional<unsigned> VScale = getVScaleForTuning()) {
5255     if (A.Width.isScalable())
5256       EstimatedWidthA *= VScale.value();
5257     if (B.Width.isScalable())
5258       EstimatedWidthB *= VScale.value();
5259   }
5260 
5261   // Assume vscale may be larger than 1 (or the value being tuned for),
5262   // so that scalable vectorization is slightly favorable over fixed-width
5263   // vectorization.
5264   if (A.Width.isScalable() && !B.Width.isScalable())
5265     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5266 
5267   // To avoid the need for FP division:
5268   //      (CostA / A.Width) < (CostB / B.Width)
5269   // <=>  (CostA * B.Width) < (CostB * A.Width)
5270   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5271 }
5272 
5273 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5274     const ElementCountSet &VFCandidates) {
5275   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5276   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5277   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5278   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5279          "Expected Scalar VF to be a candidate");
5280 
5281   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
5282                                        ExpectedCost);
5283   VectorizationFactor ChosenFactor = ScalarCost;
5284 
5285   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5286   if (ForceVectorization && VFCandidates.size() > 1) {
5287     // Ignore scalar width, because the user explicitly wants vectorization.
5288     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5289     // evaluation.
5290     ChosenFactor.Cost = InstructionCost::getMax();
5291   }
5292 
5293   SmallVector<InstructionVFPair> InvalidCosts;
5294   for (const auto &i : VFCandidates) {
5295     // The cost for scalar VF=1 is already calculated, so ignore it.
5296     if (i.isScalar())
5297       continue;
5298 
5299     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5300     VectorizationFactor Candidate(i, C.first, ScalarCost.ScalarCost);
5301 
5302 #ifndef NDEBUG
5303     unsigned AssumedMinimumVscale = 1;
5304     if (Optional<unsigned> VScale = getVScaleForTuning())
5305       AssumedMinimumVscale = *VScale;
5306     unsigned Width =
5307         Candidate.Width.isScalable()
5308             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5309             : Candidate.Width.getFixedValue();
5310     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5311                       << " costs: " << (Candidate.Cost / Width));
5312     if (i.isScalable())
5313       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5314                         << AssumedMinimumVscale << ")");
5315     LLVM_DEBUG(dbgs() << ".\n");
5316 #endif
5317 
5318     if (!C.second && !ForceVectorization) {
5319       LLVM_DEBUG(
5320           dbgs() << "LV: Not considering vector loop of width " << i
5321                  << " because it will not generate any vector instructions.\n");
5322       continue;
5323     }
5324 
5325     // If profitable add it to ProfitableVF list.
5326     if (isMoreProfitable(Candidate, ScalarCost))
5327       ProfitableVFs.push_back(Candidate);
5328 
5329     if (isMoreProfitable(Candidate, ChosenFactor))
5330       ChosenFactor = Candidate;
5331   }
5332 
5333   // Emit a report of VFs with invalid costs in the loop.
5334   if (!InvalidCosts.empty()) {
5335     // Group the remarks per instruction, keeping the instruction order from
5336     // InvalidCosts.
5337     std::map<Instruction *, unsigned> Numbering;
5338     unsigned I = 0;
5339     for (auto &Pair : InvalidCosts)
5340       if (!Numbering.count(Pair.first))
5341         Numbering[Pair.first] = I++;
5342 
5343     // Sort the list, first on instruction(number) then on VF.
5344     llvm::sort(InvalidCosts,
5345                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5346                  if (Numbering[A.first] != Numbering[B.first])
5347                    return Numbering[A.first] < Numbering[B.first];
5348                  ElementCountComparator ECC;
5349                  return ECC(A.second, B.second);
5350                });
5351 
5352     // For a list of ordered instruction-vf pairs:
5353     //   [(load, vf1), (load, vf2), (store, vf1)]
5354     // Group the instructions together to emit separate remarks for:
5355     //   load  (vf1, vf2)
5356     //   store (vf1)
5357     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5358     auto Subset = ArrayRef<InstructionVFPair>();
5359     do {
5360       if (Subset.empty())
5361         Subset = Tail.take_front(1);
5362 
5363       Instruction *I = Subset.front().first;
5364 
5365       // If the next instruction is different, or if there are no other pairs,
5366       // emit a remark for the collated subset. e.g.
5367       //   [(load, vf1), (load, vf2))]
5368       // to emit:
5369       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5370       if (Subset == Tail || Tail[Subset.size()].first != I) {
5371         std::string OutString;
5372         raw_string_ostream OS(OutString);
5373         assert(!Subset.empty() && "Unexpected empty range");
5374         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5375         for (auto &Pair : Subset)
5376           OS << (Pair.second == Subset.front().second ? "" : ", ")
5377              << Pair.second;
5378         OS << "):";
5379         if (auto *CI = dyn_cast<CallInst>(I))
5380           OS << " call to " << CI->getCalledFunction()->getName();
5381         else
5382           OS << " " << I->getOpcodeName();
5383         OS.flush();
5384         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5385         Tail = Tail.drop_front(Subset.size());
5386         Subset = {};
5387       } else
5388         // Grow the subset by one element
5389         Subset = Tail.take_front(Subset.size() + 1);
5390     } while (!Tail.empty());
5391   }
5392 
5393   if (!EnableCondStoresVectorization && NumPredStores) {
5394     reportVectorizationFailure("There are conditional stores.",
5395         "store that is conditionally executed prevents vectorization",
5396         "ConditionalStore", ORE, TheLoop);
5397     ChosenFactor = ScalarCost;
5398   }
5399 
5400   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5401                  !isMoreProfitable(ChosenFactor, ScalarCost)) dbgs()
5402              << "LV: Vectorization seems to be not beneficial, "
5403              << "but was forced by a user.\n");
5404   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5405   return ChosenFactor;
5406 }
5407 
5408 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5409     const Loop &L, ElementCount VF) const {
5410   // Cross iteration phis such as reductions need special handling and are
5411   // currently unsupported.
5412   if (any_of(L.getHeader()->phis(),
5413              [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
5414     return false;
5415 
5416   // Phis with uses outside of the loop require special handling and are
5417   // currently unsupported.
5418   for (auto &Entry : Legal->getInductionVars()) {
5419     // Look for uses of the value of the induction at the last iteration.
5420     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5421     for (User *U : PostInc->users())
5422       if (!L.contains(cast<Instruction>(U)))
5423         return false;
5424     // Look for uses of penultimate value of the induction.
5425     for (User *U : Entry.first->users())
5426       if (!L.contains(cast<Instruction>(U)))
5427         return false;
5428   }
5429 
5430   // Induction variables that are widened require special handling that is
5431   // currently not supported.
5432   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5433         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5434                  this->isProfitableToScalarize(Entry.first, VF));
5435       }))
5436     return false;
5437 
5438   // Epilogue vectorization code has not been auditted to ensure it handles
5439   // non-latch exits properly.  It may be fine, but it needs auditted and
5440   // tested.
5441   if (L.getExitingBlock() != L.getLoopLatch())
5442     return false;
5443 
5444   return true;
5445 }
5446 
5447 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5448     const ElementCount VF) const {
5449   // FIXME: We need a much better cost-model to take different parameters such
5450   // as register pressure, code size increase and cost of extra branches into
5451   // account. For now we apply a very crude heuristic and only consider loops
5452   // with vectorization factors larger than a certain value.
5453   // We also consider epilogue vectorization unprofitable for targets that don't
5454   // consider interleaving beneficial (eg. MVE).
5455   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5456     return false;
5457   // FIXME: We should consider changing the threshold for scalable
5458   // vectors to take VScaleForTuning into account.
5459   if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
5460     return true;
5461   return false;
5462 }
5463 
5464 VectorizationFactor
5465 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5466     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5467   VectorizationFactor Result = VectorizationFactor::Disabled();
5468   if (!EnableEpilogueVectorization) {
5469     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5470     return Result;
5471   }
5472 
5473   if (!isScalarEpilogueAllowed()) {
5474     LLVM_DEBUG(
5475         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5476                   "allowed.\n";);
5477     return Result;
5478   }
5479 
5480   // Not really a cost consideration, but check for unsupported cases here to
5481   // simplify the logic.
5482   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5483     LLVM_DEBUG(
5484         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5485                   "not a supported candidate.\n";);
5486     return Result;
5487   }
5488 
5489   if (EpilogueVectorizationForceVF > 1) {
5490     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5491     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5492     if (LVP.hasPlanWithVF(ForcedEC))
5493       return {ForcedEC, 0, 0};
5494     else {
5495       LLVM_DEBUG(
5496           dbgs()
5497               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5498       return Result;
5499     }
5500   }
5501 
5502   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5503       TheLoop->getHeader()->getParent()->hasMinSize()) {
5504     LLVM_DEBUG(
5505         dbgs()
5506             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5507     return Result;
5508   }
5509 
5510   if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
5511     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5512                          "this loop\n");
5513     return Result;
5514   }
5515 
5516   // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
5517   // the main loop handles 8 lanes per iteration. We could still benefit from
5518   // vectorizing the epilogue loop with VF=4.
5519   ElementCount EstimatedRuntimeVF = MainLoopVF;
5520   if (MainLoopVF.isScalable()) {
5521     EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5522     if (Optional<unsigned> VScale = getVScaleForTuning())
5523       EstimatedRuntimeVF *= *VScale;
5524   }
5525 
5526   for (auto &NextVF : ProfitableVFs)
5527     if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
5528           ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
5529          ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
5530         (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
5531         LVP.hasPlanWithVF(NextVF.Width))
5532       Result = NextVF;
5533 
5534   if (Result != VectorizationFactor::Disabled())
5535     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5536                       << Result.Width << "\n";);
5537   return Result;
5538 }
5539 
5540 std::pair<unsigned, unsigned>
5541 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5542   unsigned MinWidth = -1U;
5543   unsigned MaxWidth = 8;
5544   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5545   // For in-loop reductions, no element types are added to ElementTypesInLoop
5546   // if there are no loads/stores in the loop. In this case, check through the
5547   // reduction variables to determine the maximum width.
5548   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5549     // Reset MaxWidth so that we can find the smallest type used by recurrences
5550     // in the loop.
5551     MaxWidth = -1U;
5552     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5553       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5554       // When finding the min width used by the recurrence we need to account
5555       // for casts on the input operands of the recurrence.
5556       MaxWidth = std::min<unsigned>(
5557           MaxWidth, std::min<unsigned>(
5558                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5559                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5560     }
5561   } else {
5562     for (Type *T : ElementTypesInLoop) {
5563       MinWidth = std::min<unsigned>(
5564           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5565       MaxWidth = std::max<unsigned>(
5566           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5567     }
5568   }
5569   return {MinWidth, MaxWidth};
5570 }
5571 
5572 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5573   ElementTypesInLoop.clear();
5574   // For each block.
5575   for (BasicBlock *BB : TheLoop->blocks()) {
5576     // For each instruction in the loop.
5577     for (Instruction &I : BB->instructionsWithoutDebug()) {
5578       Type *T = I.getType();
5579 
5580       // Skip ignored values.
5581       if (ValuesToIgnore.count(&I))
5582         continue;
5583 
5584       // Only examine Loads, Stores and PHINodes.
5585       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5586         continue;
5587 
5588       // Examine PHI nodes that are reduction variables. Update the type to
5589       // account for the recurrence type.
5590       if (auto *PN = dyn_cast<PHINode>(&I)) {
5591         if (!Legal->isReductionVariable(PN))
5592           continue;
5593         const RecurrenceDescriptor &RdxDesc =
5594             Legal->getReductionVars().find(PN)->second;
5595         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
5596             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
5597                                       RdxDesc.getRecurrenceType(),
5598                                       TargetTransformInfo::ReductionFlags()))
5599           continue;
5600         T = RdxDesc.getRecurrenceType();
5601       }
5602 
5603       // Examine the stored values.
5604       if (auto *ST = dyn_cast<StoreInst>(&I))
5605         T = ST->getValueOperand()->getType();
5606 
5607       assert(T->isSized() &&
5608              "Expected the load/store/recurrence type to be sized");
5609 
5610       ElementTypesInLoop.insert(T);
5611     }
5612   }
5613 }
5614 
5615 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5616                                                            unsigned LoopCost) {
5617   // -- The interleave heuristics --
5618   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5619   // There are many micro-architectural considerations that we can't predict
5620   // at this level. For example, frontend pressure (on decode or fetch) due to
5621   // code size, or the number and capabilities of the execution ports.
5622   //
5623   // We use the following heuristics to select the interleave count:
5624   // 1. If the code has reductions, then we interleave to break the cross
5625   // iteration dependency.
5626   // 2. If the loop is really small, then we interleave to reduce the loop
5627   // overhead.
5628   // 3. We don't interleave if we think that we will spill registers to memory
5629   // due to the increased register pressure.
5630 
5631   if (!isScalarEpilogueAllowed())
5632     return 1;
5633 
5634   // We used the distance for the interleave count.
5635   if (Legal->getMaxSafeDepDistBytes() != -1U)
5636     return 1;
5637 
5638   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5639   const bool HasReductions = !Legal->getReductionVars().empty();
5640   // Do not interleave loops with a relatively small known or estimated trip
5641   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5642   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5643   // because with the above conditions interleaving can expose ILP and break
5644   // cross iteration dependences for reductions.
5645   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5646       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5647     return 1;
5648 
5649   // If we did not calculate the cost for VF (because the user selected the VF)
5650   // then we calculate the cost of VF here.
5651   if (LoopCost == 0) {
5652     InstructionCost C = expectedCost(VF).first;
5653     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
5654     LoopCost = *C.getValue();
5655 
5656     // Loop body is free and there is no need for interleaving.
5657     if (LoopCost == 0)
5658       return 1;
5659   }
5660 
5661   RegisterUsage R = calculateRegisterUsage({VF})[0];
5662   // We divide by these constants so assume that we have at least one
5663   // instruction that uses at least one register.
5664   for (auto& pair : R.MaxLocalUsers) {
5665     pair.second = std::max(pair.second, 1U);
5666   }
5667 
5668   // We calculate the interleave count using the following formula.
5669   // Subtract the number of loop invariants from the number of available
5670   // registers. These registers are used by all of the interleaved instances.
5671   // Next, divide the remaining registers by the number of registers that is
5672   // required by the loop, in order to estimate how many parallel instances
5673   // fit without causing spills. All of this is rounded down if necessary to be
5674   // a power of two. We want power of two interleave count to simplify any
5675   // addressing operations or alignment considerations.
5676   // We also want power of two interleave counts to ensure that the induction
5677   // variable of the vector loop wraps to zero, when tail is folded by masking;
5678   // this currently happens when OptForSize, in which case IC is set to 1 above.
5679   unsigned IC = UINT_MAX;
5680 
5681   for (auto& pair : R.MaxLocalUsers) {
5682     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5683     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5684                       << " registers of "
5685                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5686     if (VF.isScalar()) {
5687       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5688         TargetNumRegisters = ForceTargetNumScalarRegs;
5689     } else {
5690       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5691         TargetNumRegisters = ForceTargetNumVectorRegs;
5692     }
5693     unsigned MaxLocalUsers = pair.second;
5694     unsigned LoopInvariantRegs = 0;
5695     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5696       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5697 
5698     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5699     // Don't count the induction variable as interleaved.
5700     if (EnableIndVarRegisterHeur) {
5701       TmpIC =
5702           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5703                         std::max(1U, (MaxLocalUsers - 1)));
5704     }
5705 
5706     IC = std::min(IC, TmpIC);
5707   }
5708 
5709   // Clamp the interleave ranges to reasonable counts.
5710   unsigned MaxInterleaveCount =
5711       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5712 
5713   // Check if the user has overridden the max.
5714   if (VF.isScalar()) {
5715     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5716       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5717   } else {
5718     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5719       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5720   }
5721 
5722   // If trip count is known or estimated compile time constant, limit the
5723   // interleave count to be less than the trip count divided by VF, provided it
5724   // is at least 1.
5725   //
5726   // For scalable vectors we can't know if interleaving is beneficial. It may
5727   // not be beneficial for small loops if none of the lanes in the second vector
5728   // iterations is enabled. However, for larger loops, there is likely to be a
5729   // similar benefit as for fixed-width vectors. For now, we choose to leave
5730   // the InterleaveCount as if vscale is '1', although if some information about
5731   // the vector is known (e.g. min vector size), we can make a better decision.
5732   if (BestKnownTC) {
5733     MaxInterleaveCount =
5734         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5735     // Make sure MaxInterleaveCount is greater than 0.
5736     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5737   }
5738 
5739   assert(MaxInterleaveCount > 0 &&
5740          "Maximum interleave count must be greater than 0");
5741 
5742   // Clamp the calculated IC to be between the 1 and the max interleave count
5743   // that the target and trip count allows.
5744   if (IC > MaxInterleaveCount)
5745     IC = MaxInterleaveCount;
5746   else
5747     // Make sure IC is greater than 0.
5748     IC = std::max(1u, IC);
5749 
5750   assert(IC > 0 && "Interleave count must be greater than 0.");
5751 
5752   // Interleave if we vectorized this loop and there is a reduction that could
5753   // benefit from interleaving.
5754   if (VF.isVector() && HasReductions) {
5755     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5756     return IC;
5757   }
5758 
5759   // For any scalar loop that either requires runtime checks or predication we
5760   // are better off leaving this to the unroller. Note that if we've already
5761   // vectorized the loop we will have done the runtime check and so interleaving
5762   // won't require further checks.
5763   bool ScalarInterleavingRequiresPredication =
5764       (VF.isScalar() && any_of(TheLoop->blocks(), [this](BasicBlock *BB) {
5765          return Legal->blockNeedsPredication(BB);
5766        }));
5767   bool ScalarInterleavingRequiresRuntimePointerCheck =
5768       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5769 
5770   // We want to interleave small loops in order to reduce the loop overhead and
5771   // potentially expose ILP opportunities.
5772   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5773                     << "LV: IC is " << IC << '\n'
5774                     << "LV: VF is " << VF << '\n');
5775   const bool AggressivelyInterleaveReductions =
5776       TTI.enableAggressiveInterleaving(HasReductions);
5777   if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5778       !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
5779     // We assume that the cost overhead is 1 and we use the cost model
5780     // to estimate the cost of the loop and interleave until the cost of the
5781     // loop overhead is about 5% of the cost of the loop.
5782     unsigned SmallIC =
5783         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5784 
5785     // Interleave until store/load ports (estimated by max interleave count) are
5786     // saturated.
5787     unsigned NumStores = Legal->getNumStores();
5788     unsigned NumLoads = Legal->getNumLoads();
5789     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5790     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5791 
5792     // There is little point in interleaving for reductions containing selects
5793     // and compares when VF=1 since it may just create more overhead than it's
5794     // worth for loops with small trip counts. This is because we still have to
5795     // do the final reduction after the loop.
5796     bool HasSelectCmpReductions =
5797         HasReductions &&
5798         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5799           const RecurrenceDescriptor &RdxDesc = Reduction.second;
5800           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
5801               RdxDesc.getRecurrenceKind());
5802         });
5803     if (HasSelectCmpReductions) {
5804       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
5805       return 1;
5806     }
5807 
5808     // If we have a scalar reduction (vector reductions are already dealt with
5809     // by this point), we can increase the critical path length if the loop
5810     // we're interleaving is inside another loop. For tree-wise reductions
5811     // set the limit to 2, and for ordered reductions it's best to disable
5812     // interleaving entirely.
5813     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5814       bool HasOrderedReductions =
5815           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5816             const RecurrenceDescriptor &RdxDesc = Reduction.second;
5817             return RdxDesc.isOrdered();
5818           });
5819       if (HasOrderedReductions) {
5820         LLVM_DEBUG(
5821             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
5822         return 1;
5823       }
5824 
5825       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5826       SmallIC = std::min(SmallIC, F);
5827       StoresIC = std::min(StoresIC, F);
5828       LoadsIC = std::min(LoadsIC, F);
5829     }
5830 
5831     if (EnableLoadStoreRuntimeInterleave &&
5832         std::max(StoresIC, LoadsIC) > SmallIC) {
5833       LLVM_DEBUG(
5834           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5835       return std::max(StoresIC, LoadsIC);
5836     }
5837 
5838     // If there are scalar reductions and TTI has enabled aggressive
5839     // interleaving for reductions, we will interleave to expose ILP.
5840     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5841         AggressivelyInterleaveReductions) {
5842       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5843       // Interleave no less than SmallIC but not as aggressive as the normal IC
5844       // to satisfy the rare situation when resources are too limited.
5845       return std::max(IC / 2, SmallIC);
5846     } else {
5847       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5848       return SmallIC;
5849     }
5850   }
5851 
5852   // Interleave if this is a large loop (small loops are already dealt with by
5853   // this point) that could benefit from interleaving.
5854   if (AggressivelyInterleaveReductions) {
5855     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5856     return IC;
5857   }
5858 
5859   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5860   return 1;
5861 }
5862 
5863 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5864 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5865   // This function calculates the register usage by measuring the highest number
5866   // of values that are alive at a single location. Obviously, this is a very
5867   // rough estimation. We scan the loop in a topological order in order and
5868   // assign a number to each instruction. We use RPO to ensure that defs are
5869   // met before their users. We assume that each instruction that has in-loop
5870   // users starts an interval. We record every time that an in-loop value is
5871   // used, so we have a list of the first and last occurrences of each
5872   // instruction. Next, we transpose this data structure into a multi map that
5873   // holds the list of intervals that *end* at a specific location. This multi
5874   // map allows us to perform a linear search. We scan the instructions linearly
5875   // and record each time that a new interval starts, by placing it in a set.
5876   // If we find this value in the multi-map then we remove it from the set.
5877   // The max register usage is the maximum size of the set.
5878   // We also search for instructions that are defined outside the loop, but are
5879   // used inside the loop. We need this number separately from the max-interval
5880   // usage number because when we unroll, loop-invariant values do not take
5881   // more register.
5882   LoopBlocksDFS DFS(TheLoop);
5883   DFS.perform(LI);
5884 
5885   RegisterUsage RU;
5886 
5887   // Each 'key' in the map opens a new interval. The values
5888   // of the map are the index of the 'last seen' usage of the
5889   // instruction that is the key.
5890   using IntervalMap = DenseMap<Instruction *, unsigned>;
5891 
5892   // Maps instruction to its index.
5893   SmallVector<Instruction *, 64> IdxToInstr;
5894   // Marks the end of each interval.
5895   IntervalMap EndPoint;
5896   // Saves the list of instruction indices that are used in the loop.
5897   SmallPtrSet<Instruction *, 8> Ends;
5898   // Saves the list of values that are used in the loop but are
5899   // defined outside the loop, such as arguments and constants.
5900   SmallPtrSet<Value *, 8> LoopInvariants;
5901 
5902   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5903     for (Instruction &I : BB->instructionsWithoutDebug()) {
5904       IdxToInstr.push_back(&I);
5905 
5906       // Save the end location of each USE.
5907       for (Value *U : I.operands()) {
5908         auto *Instr = dyn_cast<Instruction>(U);
5909 
5910         // Ignore non-instruction values such as arguments, constants, etc.
5911         if (!Instr)
5912           continue;
5913 
5914         // If this instruction is outside the loop then record it and continue.
5915         if (!TheLoop->contains(Instr)) {
5916           LoopInvariants.insert(Instr);
5917           continue;
5918         }
5919 
5920         // Overwrite previous end points.
5921         EndPoint[Instr] = IdxToInstr.size();
5922         Ends.insert(Instr);
5923       }
5924     }
5925   }
5926 
5927   // Saves the list of intervals that end with the index in 'key'.
5928   using InstrList = SmallVector<Instruction *, 2>;
5929   DenseMap<unsigned, InstrList> TransposeEnds;
5930 
5931   // Transpose the EndPoints to a list of values that end at each index.
5932   for (auto &Interval : EndPoint)
5933     TransposeEnds[Interval.second].push_back(Interval.first);
5934 
5935   SmallPtrSet<Instruction *, 8> OpenIntervals;
5936   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5937   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5938 
5939   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5940 
5941   const auto &TTICapture = TTI;
5942   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
5943     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
5944       return 0;
5945     return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
5946   };
5947 
5948   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
5949     Instruction *I = IdxToInstr[i];
5950 
5951     // Remove all of the instructions that end at this location.
5952     InstrList &List = TransposeEnds[i];
5953     for (Instruction *ToRemove : List)
5954       OpenIntervals.erase(ToRemove);
5955 
5956     // Ignore instructions that are never used within the loop.
5957     if (!Ends.count(I))
5958       continue;
5959 
5960     // Skip ignored values.
5961     if (ValuesToIgnore.count(I))
5962       continue;
5963 
5964     // For each VF find the maximum usage of registers.
5965     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5966       // Count the number of live intervals.
5967       SmallMapVector<unsigned, unsigned, 4> RegUsage;
5968 
5969       if (VFs[j].isScalar()) {
5970         for (auto Inst : OpenIntervals) {
5971           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5972           if (RegUsage.find(ClassID) == RegUsage.end())
5973             RegUsage[ClassID] = 1;
5974           else
5975             RegUsage[ClassID] += 1;
5976         }
5977       } else {
5978         collectUniformsAndScalars(VFs[j]);
5979         for (auto Inst : OpenIntervals) {
5980           // Skip ignored values for VF > 1.
5981           if (VecValuesToIgnore.count(Inst))
5982             continue;
5983           if (isScalarAfterVectorization(Inst, VFs[j])) {
5984             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5985             if (RegUsage.find(ClassID) == RegUsage.end())
5986               RegUsage[ClassID] = 1;
5987             else
5988               RegUsage[ClassID] += 1;
5989           } else {
5990             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
5991             if (RegUsage.find(ClassID) == RegUsage.end())
5992               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
5993             else
5994               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
5995           }
5996         }
5997       }
5998 
5999       for (auto& pair : RegUsage) {
6000         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6001           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6002         else
6003           MaxUsages[j][pair.first] = pair.second;
6004       }
6005     }
6006 
6007     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6008                       << OpenIntervals.size() << '\n');
6009 
6010     // Add the current instruction to the list of open intervals.
6011     OpenIntervals.insert(I);
6012   }
6013 
6014   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6015     SmallMapVector<unsigned, unsigned, 4> Invariant;
6016 
6017     for (auto Inst : LoopInvariants) {
6018       unsigned Usage =
6019           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6020       unsigned ClassID =
6021           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6022       if (Invariant.find(ClassID) == Invariant.end())
6023         Invariant[ClassID] = Usage;
6024       else
6025         Invariant[ClassID] += Usage;
6026     }
6027 
6028     LLVM_DEBUG({
6029       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6030       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6031              << " item\n";
6032       for (const auto &pair : MaxUsages[i]) {
6033         dbgs() << "LV(REG): RegisterClass: "
6034                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6035                << " registers\n";
6036       }
6037       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6038              << " item\n";
6039       for (const auto &pair : Invariant) {
6040         dbgs() << "LV(REG): RegisterClass: "
6041                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6042                << " registers\n";
6043       }
6044     });
6045 
6046     RU.LoopInvariantRegs = Invariant;
6047     RU.MaxLocalUsers = MaxUsages[i];
6048     RUs[i] = RU;
6049   }
6050 
6051   return RUs;
6052 }
6053 
6054 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
6055                                                            ElementCount VF) {
6056   // TODO: Cost model for emulated masked load/store is completely
6057   // broken. This hack guides the cost model to use an artificially
6058   // high enough value to practically disable vectorization with such
6059   // operations, except where previously deployed legality hack allowed
6060   // using very low cost values. This is to avoid regressions coming simply
6061   // from moving "masked load/store" check from legality to cost model.
6062   // Masked Load/Gather emulation was previously never allowed.
6063   // Limited number of Masked Store/Scatter emulation was allowed.
6064   assert((isPredicatedInst(I, VF) || Legal->isUniformMemOp(*I)) &&
6065          "Expecting a scalar emulated instruction");
6066   return isa<LoadInst>(I) ||
6067          (isa<StoreInst>(I) &&
6068           NumPredStores > NumberOfStoresToPredicate);
6069 }
6070 
6071 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6072   // If we aren't vectorizing the loop, or if we've already collected the
6073   // instructions to scalarize, there's nothing to do. Collection may already
6074   // have occurred if we have a user-selected VF and are now computing the
6075   // expected cost for interleaving.
6076   if (VF.isScalar() || VF.isZero() ||
6077       InstsToScalarize.find(VF) != InstsToScalarize.end())
6078     return;
6079 
6080   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6081   // not profitable to scalarize any instructions, the presence of VF in the
6082   // map will indicate that we've analyzed it already.
6083   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6084 
6085   PredicatedBBsAfterVectorization[VF].clear();
6086 
6087   // Find all the instructions that are scalar with predication in the loop and
6088   // determine if it would be better to not if-convert the blocks they are in.
6089   // If so, we also record the instructions to scalarize.
6090   for (BasicBlock *BB : TheLoop->blocks()) {
6091     if (!blockNeedsPredicationForAnyReason(BB))
6092       continue;
6093     for (Instruction &I : *BB)
6094       if (isScalarWithPredication(&I, VF)) {
6095         ScalarCostsTy ScalarCosts;
6096         // Do not apply discount if scalable, because that would lead to
6097         // invalid scalarization costs.
6098         // Do not apply discount logic if hacked cost is needed
6099         // for emulated masked memrefs.
6100         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
6101             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6102           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6103         // Remember that BB will remain after vectorization.
6104         PredicatedBBsAfterVectorization[VF].insert(BB);
6105       }
6106   }
6107 }
6108 
6109 int LoopVectorizationCostModel::computePredInstDiscount(
6110     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6111   assert(!isUniformAfterVectorization(PredInst, VF) &&
6112          "Instruction marked uniform-after-vectorization will be predicated");
6113 
6114   // Initialize the discount to zero, meaning that the scalar version and the
6115   // vector version cost the same.
6116   InstructionCost Discount = 0;
6117 
6118   // Holds instructions to analyze. The instructions we visit are mapped in
6119   // ScalarCosts. Those instructions are the ones that would be scalarized if
6120   // we find that the scalar version costs less.
6121   SmallVector<Instruction *, 8> Worklist;
6122 
6123   // Returns true if the given instruction can be scalarized.
6124   auto canBeScalarized = [&](Instruction *I) -> bool {
6125     // We only attempt to scalarize instructions forming a single-use chain
6126     // from the original predicated block that would otherwise be vectorized.
6127     // Although not strictly necessary, we give up on instructions we know will
6128     // already be scalar to avoid traversing chains that are unlikely to be
6129     // beneficial.
6130     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6131         isScalarAfterVectorization(I, VF))
6132       return false;
6133 
6134     // If the instruction is scalar with predication, it will be analyzed
6135     // separately. We ignore it within the context of PredInst.
6136     if (isScalarWithPredication(I, VF))
6137       return false;
6138 
6139     // If any of the instruction's operands are uniform after vectorization,
6140     // the instruction cannot be scalarized. This prevents, for example, a
6141     // masked load from being scalarized.
6142     //
6143     // We assume we will only emit a value for lane zero of an instruction
6144     // marked uniform after vectorization, rather than VF identical values.
6145     // Thus, if we scalarize an instruction that uses a uniform, we would
6146     // create uses of values corresponding to the lanes we aren't emitting code
6147     // for. This behavior can be changed by allowing getScalarValue to clone
6148     // the lane zero values for uniforms rather than asserting.
6149     for (Use &U : I->operands())
6150       if (auto *J = dyn_cast<Instruction>(U.get()))
6151         if (isUniformAfterVectorization(J, VF))
6152           return false;
6153 
6154     // Otherwise, we can scalarize the instruction.
6155     return true;
6156   };
6157 
6158   // Compute the expected cost discount from scalarizing the entire expression
6159   // feeding the predicated instruction. We currently only consider expressions
6160   // that are single-use instruction chains.
6161   Worklist.push_back(PredInst);
6162   while (!Worklist.empty()) {
6163     Instruction *I = Worklist.pop_back_val();
6164 
6165     // If we've already analyzed the instruction, there's nothing to do.
6166     if (ScalarCosts.find(I) != ScalarCosts.end())
6167       continue;
6168 
6169     // Compute the cost of the vector instruction. Note that this cost already
6170     // includes the scalarization overhead of the predicated instruction.
6171     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6172 
6173     // Compute the cost of the scalarized instruction. This cost is the cost of
6174     // the instruction as if it wasn't if-converted and instead remained in the
6175     // predicated block. We will scale this cost by block probability after
6176     // computing the scalarization overhead.
6177     InstructionCost ScalarCost =
6178         VF.getFixedValue() *
6179         getInstructionCost(I, ElementCount::getFixed(1)).first;
6180 
6181     // Compute the scalarization overhead of needed insertelement instructions
6182     // and phi nodes.
6183     if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
6184       ScalarCost += TTI.getScalarizationOverhead(
6185           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6186           APInt::getAllOnes(VF.getFixedValue()), true, false);
6187       ScalarCost +=
6188           VF.getFixedValue() *
6189           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6190     }
6191 
6192     // Compute the scalarization overhead of needed extractelement
6193     // instructions. For each of the instruction's operands, if the operand can
6194     // be scalarized, add it to the worklist; otherwise, account for the
6195     // overhead.
6196     for (Use &U : I->operands())
6197       if (auto *J = dyn_cast<Instruction>(U.get())) {
6198         assert(VectorType::isValidElementType(J->getType()) &&
6199                "Instruction has non-scalar type");
6200         if (canBeScalarized(J))
6201           Worklist.push_back(J);
6202         else if (needsExtract(J, VF)) {
6203           ScalarCost += TTI.getScalarizationOverhead(
6204               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6205               APInt::getAllOnes(VF.getFixedValue()), false, true);
6206         }
6207       }
6208 
6209     // Scale the total scalar cost by block probability.
6210     ScalarCost /= getReciprocalPredBlockProb();
6211 
6212     // Compute the discount. A non-negative discount means the vector version
6213     // of the instruction costs more, and scalarizing would be beneficial.
6214     Discount += VectorCost - ScalarCost;
6215     ScalarCosts[I] = ScalarCost;
6216   }
6217 
6218   return *Discount.getValue();
6219 }
6220 
6221 LoopVectorizationCostModel::VectorizationCostTy
6222 LoopVectorizationCostModel::expectedCost(
6223     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6224   VectorizationCostTy Cost;
6225 
6226   // For each block.
6227   for (BasicBlock *BB : TheLoop->blocks()) {
6228     VectorizationCostTy BlockCost;
6229 
6230     // For each instruction in the old loop.
6231     for (Instruction &I : BB->instructionsWithoutDebug()) {
6232       // Skip ignored values.
6233       if (ValuesToIgnore.count(&I) ||
6234           (VF.isVector() && VecValuesToIgnore.count(&I)))
6235         continue;
6236 
6237       VectorizationCostTy C = getInstructionCost(&I, VF);
6238 
6239       // Check if we should override the cost.
6240       if (C.first.isValid() &&
6241           ForceTargetInstructionCost.getNumOccurrences() > 0)
6242         C.first = InstructionCost(ForceTargetInstructionCost);
6243 
6244       // Keep a list of instructions with invalid costs.
6245       if (Invalid && !C.first.isValid())
6246         Invalid->emplace_back(&I, VF);
6247 
6248       BlockCost.first += C.first;
6249       BlockCost.second |= C.second;
6250       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6251                         << " for VF " << VF << " For instruction: " << I
6252                         << '\n');
6253     }
6254 
6255     // If we are vectorizing a predicated block, it will have been
6256     // if-converted. This means that the block's instructions (aside from
6257     // stores and instructions that may divide by zero) will now be
6258     // unconditionally executed. For the scalar case, we may not always execute
6259     // the predicated block, if it is an if-else block. Thus, scale the block's
6260     // cost by the probability of executing it. blockNeedsPredication from
6261     // Legal is used so as to not include all blocks in tail folded loops.
6262     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6263       BlockCost.first /= getReciprocalPredBlockProb();
6264 
6265     Cost.first += BlockCost.first;
6266     Cost.second |= BlockCost.second;
6267   }
6268 
6269   return Cost;
6270 }
6271 
6272 /// Gets Address Access SCEV after verifying that the access pattern
6273 /// is loop invariant except the induction variable dependence.
6274 ///
6275 /// This SCEV can be sent to the Target in order to estimate the address
6276 /// calculation cost.
6277 static const SCEV *getAddressAccessSCEV(
6278               Value *Ptr,
6279               LoopVectorizationLegality *Legal,
6280               PredicatedScalarEvolution &PSE,
6281               const Loop *TheLoop) {
6282 
6283   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6284   if (!Gep)
6285     return nullptr;
6286 
6287   // We are looking for a gep with all loop invariant indices except for one
6288   // which should be an induction variable.
6289   auto SE = PSE.getSE();
6290   unsigned NumOperands = Gep->getNumOperands();
6291   for (unsigned i = 1; i < NumOperands; ++i) {
6292     Value *Opd = Gep->getOperand(i);
6293     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6294         !Legal->isInductionVariable(Opd))
6295       return nullptr;
6296   }
6297 
6298   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6299   return PSE.getSCEV(Ptr);
6300 }
6301 
6302 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6303   return Legal->hasStride(I->getOperand(0)) ||
6304          Legal->hasStride(I->getOperand(1));
6305 }
6306 
6307 InstructionCost
6308 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6309                                                         ElementCount VF) {
6310   assert(VF.isVector() &&
6311          "Scalarization cost of instruction implies vectorization.");
6312   if (VF.isScalable())
6313     return InstructionCost::getInvalid();
6314 
6315   Type *ValTy = getLoadStoreType(I);
6316   auto SE = PSE.getSE();
6317 
6318   unsigned AS = getLoadStoreAddressSpace(I);
6319   Value *Ptr = getLoadStorePointerOperand(I);
6320   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6321   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6322   //       that it is being called from this specific place.
6323 
6324   // Figure out whether the access is strided and get the stride value
6325   // if it's known in compile time
6326   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6327 
6328   // Get the cost of the scalar memory instruction and address computation.
6329   InstructionCost Cost =
6330       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6331 
6332   // Don't pass *I here, since it is scalar but will actually be part of a
6333   // vectorized loop where the user of it is a vectorized instruction.
6334   const Align Alignment = getLoadStoreAlignment(I);
6335   Cost += VF.getKnownMinValue() *
6336           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6337                               AS, TTI::TCK_RecipThroughput);
6338 
6339   // Get the overhead of the extractelement and insertelement instructions
6340   // we might create due to scalarization.
6341   Cost += getScalarizationOverhead(I, VF);
6342 
6343   // If we have a predicated load/store, it will need extra i1 extracts and
6344   // conditional branches, but may not be executed for each vector lane. Scale
6345   // the cost by the probability of executing the predicated block.
6346   if (isPredicatedInst(I, VF)) {
6347     Cost /= getReciprocalPredBlockProb();
6348 
6349     // Add the cost of an i1 extract and a branch
6350     auto *Vec_i1Ty =
6351         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6352     Cost += TTI.getScalarizationOverhead(
6353         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6354         /*Insert=*/false, /*Extract=*/true);
6355     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6356 
6357     if (useEmulatedMaskMemRefHack(I, VF))
6358       // Artificially setting to a high enough value to practically disable
6359       // vectorization with such operations.
6360       Cost = 3000000;
6361   }
6362 
6363   return Cost;
6364 }
6365 
6366 InstructionCost
6367 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6368                                                     ElementCount VF) {
6369   Type *ValTy = getLoadStoreType(I);
6370   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6371   Value *Ptr = getLoadStorePointerOperand(I);
6372   unsigned AS = getLoadStoreAddressSpace(I);
6373   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6374   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6375 
6376   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6377          "Stride should be 1 or -1 for consecutive memory access");
6378   const Align Alignment = getLoadStoreAlignment(I);
6379   InstructionCost Cost = 0;
6380   if (Legal->isMaskRequired(I))
6381     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6382                                       CostKind);
6383   else
6384     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6385                                 CostKind, I);
6386 
6387   bool Reverse = ConsecutiveStride < 0;
6388   if (Reverse)
6389     Cost +=
6390         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6391   return Cost;
6392 }
6393 
6394 InstructionCost
6395 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6396                                                 ElementCount VF) {
6397   assert(Legal->isUniformMemOp(*I));
6398 
6399   Type *ValTy = getLoadStoreType(I);
6400   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6401   const Align Alignment = getLoadStoreAlignment(I);
6402   unsigned AS = getLoadStoreAddressSpace(I);
6403   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6404   if (isa<LoadInst>(I)) {
6405     return TTI.getAddressComputationCost(ValTy) +
6406            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6407                                CostKind) +
6408            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6409   }
6410   StoreInst *SI = cast<StoreInst>(I);
6411 
6412   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6413   return TTI.getAddressComputationCost(ValTy) +
6414          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6415                              CostKind) +
6416          (isLoopInvariantStoreValue
6417               ? 0
6418               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6419                                        VF.getKnownMinValue() - 1));
6420 }
6421 
6422 InstructionCost
6423 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6424                                                  ElementCount VF) {
6425   Type *ValTy = getLoadStoreType(I);
6426   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6427   const Align Alignment = getLoadStoreAlignment(I);
6428   const Value *Ptr = getLoadStorePointerOperand(I);
6429 
6430   return TTI.getAddressComputationCost(VectorTy) +
6431          TTI.getGatherScatterOpCost(
6432              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6433              TargetTransformInfo::TCK_RecipThroughput, I);
6434 }
6435 
6436 InstructionCost
6437 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6438                                                    ElementCount VF) {
6439   // TODO: Once we have support for interleaving with scalable vectors
6440   // we can calculate the cost properly here.
6441   if (VF.isScalable())
6442     return InstructionCost::getInvalid();
6443 
6444   Type *ValTy = getLoadStoreType(I);
6445   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6446   unsigned AS = getLoadStoreAddressSpace(I);
6447 
6448   auto Group = getInterleavedAccessGroup(I);
6449   assert(Group && "Fail to get an interleaved access group.");
6450 
6451   unsigned InterleaveFactor = Group->getFactor();
6452   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6453 
6454   // Holds the indices of existing members in the interleaved group.
6455   SmallVector<unsigned, 4> Indices;
6456   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6457     if (Group->getMember(IF))
6458       Indices.push_back(IF);
6459 
6460   // Calculate the cost of the whole interleaved group.
6461   bool UseMaskForGaps =
6462       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6463       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6464   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6465       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6466       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6467 
6468   if (Group->isReverse()) {
6469     // TODO: Add support for reversed masked interleaved access.
6470     assert(!Legal->isMaskRequired(I) &&
6471            "Reverse masked interleaved access not supported.");
6472     Cost +=
6473         Group->getNumMembers() *
6474         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6475   }
6476   return Cost;
6477 }
6478 
6479 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6480     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6481   using namespace llvm::PatternMatch;
6482   // Early exit for no inloop reductions
6483   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6484     return None;
6485   auto *VectorTy = cast<VectorType>(Ty);
6486 
6487   // We are looking for a pattern of, and finding the minimal acceptable cost:
6488   //  reduce(mul(ext(A), ext(B))) or
6489   //  reduce(mul(A, B)) or
6490   //  reduce(ext(A)) or
6491   //  reduce(A).
6492   // The basic idea is that we walk down the tree to do that, finding the root
6493   // reduction instruction in InLoopReductionImmediateChains. From there we find
6494   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6495   // of the components. If the reduction cost is lower then we return it for the
6496   // reduction instruction and 0 for the other instructions in the pattern. If
6497   // it is not we return an invalid cost specifying the orignal cost method
6498   // should be used.
6499   Instruction *RetI = I;
6500   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6501     if (!RetI->hasOneUser())
6502       return None;
6503     RetI = RetI->user_back();
6504   }
6505   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6506       RetI->user_back()->getOpcode() == Instruction::Add) {
6507     if (!RetI->hasOneUser())
6508       return None;
6509     RetI = RetI->user_back();
6510   }
6511 
6512   // Test if the found instruction is a reduction, and if not return an invalid
6513   // cost specifying the parent to use the original cost modelling.
6514   if (!InLoopReductionImmediateChains.count(RetI))
6515     return None;
6516 
6517   // Find the reduction this chain is a part of and calculate the basic cost of
6518   // the reduction on its own.
6519   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6520   Instruction *ReductionPhi = LastChain;
6521   while (!isa<PHINode>(ReductionPhi))
6522     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6523 
6524   const RecurrenceDescriptor &RdxDesc =
6525       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6526 
6527   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6528       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6529 
6530   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6531   // normal fmul instruction to the cost of the fadd reduction.
6532   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6533     BaseCost +=
6534         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6535 
6536   // If we're using ordered reductions then we can just return the base cost
6537   // here, since getArithmeticReductionCost calculates the full ordered
6538   // reduction cost when FP reassociation is not allowed.
6539   if (useOrderedReductions(RdxDesc))
6540     return BaseCost;
6541 
6542   // Get the operand that was not the reduction chain and match it to one of the
6543   // patterns, returning the better cost if it is found.
6544   Instruction *RedOp = RetI->getOperand(1) == LastChain
6545                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6546                            : dyn_cast<Instruction>(RetI->getOperand(1));
6547 
6548   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6549 
6550   Instruction *Op0, *Op1;
6551   if (RedOp &&
6552       match(RedOp,
6553             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6554       match(Op0, m_ZExtOrSExt(m_Value())) &&
6555       Op0->getOpcode() == Op1->getOpcode() &&
6556       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6557       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6558       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6559 
6560     // Matched reduce(ext(mul(ext(A), ext(B)))
6561     // Note that the extend opcodes need to all match, or if A==B they will have
6562     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6563     // which is equally fine.
6564     bool IsUnsigned = isa<ZExtInst>(Op0);
6565     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6566     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6567 
6568     InstructionCost ExtCost =
6569         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6570                              TTI::CastContextHint::None, CostKind, Op0);
6571     InstructionCost MulCost =
6572         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6573     InstructionCost Ext2Cost =
6574         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6575                              TTI::CastContextHint::None, CostKind, RedOp);
6576 
6577     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6578         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6579         CostKind);
6580 
6581     if (RedCost.isValid() &&
6582         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6583       return I == RetI ? RedCost : 0;
6584   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
6585              !TheLoop->isLoopInvariant(RedOp)) {
6586     // Matched reduce(ext(A))
6587     bool IsUnsigned = isa<ZExtInst>(RedOp);
6588     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6589     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6590         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6591         CostKind);
6592 
6593     InstructionCost ExtCost =
6594         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6595                              TTI::CastContextHint::None, CostKind, RedOp);
6596     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6597       return I == RetI ? RedCost : 0;
6598   } else if (RedOp &&
6599              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
6600     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
6601         Op0->getOpcode() == Op1->getOpcode() &&
6602         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6603       bool IsUnsigned = isa<ZExtInst>(Op0);
6604       Type *Op0Ty = Op0->getOperand(0)->getType();
6605       Type *Op1Ty = Op1->getOperand(0)->getType();
6606       Type *LargestOpTy =
6607           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
6608                                                                     : Op0Ty;
6609       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
6610 
6611       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
6612       // different sizes. We take the largest type as the ext to reduce, and add
6613       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
6614       InstructionCost ExtCost0 = TTI.getCastInstrCost(
6615           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
6616           TTI::CastContextHint::None, CostKind, Op0);
6617       InstructionCost ExtCost1 = TTI.getCastInstrCost(
6618           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
6619           TTI::CastContextHint::None, CostKind, Op1);
6620       InstructionCost MulCost =
6621           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6622 
6623       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6624           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6625           CostKind);
6626       InstructionCost ExtraExtCost = 0;
6627       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6628         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6629         ExtraExtCost = TTI.getCastInstrCost(
6630             ExtraExtOp->getOpcode(), ExtType,
6631             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
6632             TTI::CastContextHint::None, CostKind, ExtraExtOp);
6633       }
6634 
6635       if (RedCost.isValid() &&
6636           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6637         return I == RetI ? RedCost : 0;
6638     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
6639       // Matched reduce(mul())
6640       InstructionCost MulCost =
6641           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6642 
6643       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6644           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6645           CostKind);
6646 
6647       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6648         return I == RetI ? RedCost : 0;
6649     }
6650   }
6651 
6652   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
6653 }
6654 
6655 InstructionCost
6656 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6657                                                      ElementCount VF) {
6658   // Calculate scalar cost only. Vectorization cost should be ready at this
6659   // moment.
6660   if (VF.isScalar()) {
6661     Type *ValTy = getLoadStoreType(I);
6662     const Align Alignment = getLoadStoreAlignment(I);
6663     unsigned AS = getLoadStoreAddressSpace(I);
6664 
6665     return TTI.getAddressComputationCost(ValTy) +
6666            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6667                                TTI::TCK_RecipThroughput, I);
6668   }
6669   return getWideningCost(I, VF);
6670 }
6671 
6672 LoopVectorizationCostModel::VectorizationCostTy
6673 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6674                                                ElementCount VF) {
6675   // If we know that this instruction will remain uniform, check the cost of
6676   // the scalar version.
6677   if (isUniformAfterVectorization(I, VF))
6678     VF = ElementCount::getFixed(1);
6679 
6680   if (VF.isVector() && isProfitableToScalarize(I, VF))
6681     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6682 
6683   // Forced scalars do not have any scalarization overhead.
6684   auto ForcedScalar = ForcedScalars.find(VF);
6685   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6686     auto InstSet = ForcedScalar->second;
6687     if (InstSet.count(I))
6688       return VectorizationCostTy(
6689           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6690            VF.getKnownMinValue()),
6691           false);
6692   }
6693 
6694   Type *VectorTy;
6695   InstructionCost C = getInstructionCost(I, VF, VectorTy);
6696 
6697   bool TypeNotScalarized = false;
6698   if (VF.isVector() && VectorTy->isVectorTy()) {
6699     if (unsigned NumParts = TTI.getNumberOfParts(VectorTy)) {
6700       if (VF.isScalable())
6701         // <vscale x 1 x iN> is assumed to be profitable over iN because
6702         // scalable registers are a distinct register class from scalar ones.
6703         // If we ever find a target which wants to lower scalable vectors
6704         // back to scalars, we'll need to update this code to explicitly
6705         // ask TTI about the register class uses for each part.
6706         TypeNotScalarized = NumParts <= VF.getKnownMinValue();
6707       else
6708         TypeNotScalarized = NumParts < VF.getKnownMinValue();
6709     } else
6710       C = InstructionCost::getInvalid();
6711   }
6712   return VectorizationCostTy(C, TypeNotScalarized);
6713 }
6714 
6715 InstructionCost
6716 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6717                                                      ElementCount VF) const {
6718 
6719   // There is no mechanism yet to create a scalable scalarization loop,
6720   // so this is currently Invalid.
6721   if (VF.isScalable())
6722     return InstructionCost::getInvalid();
6723 
6724   if (VF.isScalar())
6725     return 0;
6726 
6727   InstructionCost Cost = 0;
6728   Type *RetTy = ToVectorTy(I->getType(), VF);
6729   if (!RetTy->isVoidTy() &&
6730       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6731     Cost += TTI.getScalarizationOverhead(
6732         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
6733         false);
6734 
6735   // Some targets keep addresses scalar.
6736   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6737     return Cost;
6738 
6739   // Some targets support efficient element stores.
6740   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6741     return Cost;
6742 
6743   // Collect operands to consider.
6744   CallInst *CI = dyn_cast<CallInst>(I);
6745   Instruction::op_range Ops = CI ? CI->args() : I->operands();
6746 
6747   // Skip operands that do not require extraction/scalarization and do not incur
6748   // any overhead.
6749   SmallVector<Type *> Tys;
6750   for (auto *V : filterExtractingOperands(Ops, VF))
6751     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
6752   return Cost + TTI.getOperandsScalarizationOverhead(
6753                     filterExtractingOperands(Ops, VF), Tys);
6754 }
6755 
6756 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6757   if (VF.isScalar())
6758     return;
6759   NumPredStores = 0;
6760   for (BasicBlock *BB : TheLoop->blocks()) {
6761     // For each instruction in the old loop.
6762     for (Instruction &I : *BB) {
6763       Value *Ptr =  getLoadStorePointerOperand(&I);
6764       if (!Ptr)
6765         continue;
6766 
6767       // TODO: We should generate better code and update the cost model for
6768       // predicated uniform stores. Today they are treated as any other
6769       // predicated store (see added test cases in
6770       // invariant-store-vectorization.ll).
6771       if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
6772         NumPredStores++;
6773 
6774       if (Legal->isUniformMemOp(I)) {
6775         // Lowering story for uniform memory ops is currently a bit complicated.
6776         // Scalarization works for everything which isn't a store with scalable
6777         // VF.  Fixed len VFs just scalarize and then DCE later; scalarization
6778         // knows how to handle uniform-per-part values (i.e. the first lane
6779         // in each unrolled VF) and can thus handle scalable loads too.  For
6780         // scalable stores, we use a scatter if legal.  If not, we have no way
6781         // to lower (currently) and thus have to abort vectorization.
6782         InstructionCost Cost;
6783         if (isa<StoreInst>(&I) && VF.isScalable()) {
6784           if (isLegalGatherOrScatter(&I, VF))
6785             setWideningDecision(&I, VF, CM_GatherScatter,
6786                                 getGatherScatterCost(&I, VF));
6787           else
6788             // Error case, abort vectorization
6789             setWideningDecision(&I, VF, CM_Scalarize,
6790                                 InstructionCost::getInvalid());
6791           continue;
6792         }
6793         // Load: Scalar load + broadcast
6794         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6795         // TODO: Avoid replicating loads and stores instead of relying on
6796         // instcombine to remove them.
6797         setWideningDecision(&I, VF, CM_Scalarize,
6798                             getUniformMemOpCost(&I, VF));
6799         continue;
6800       }
6801 
6802       // We assume that widening is the best solution when possible.
6803       if (memoryInstructionCanBeWidened(&I, VF)) {
6804         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
6805         int ConsecutiveStride = Legal->isConsecutivePtr(
6806             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
6807         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6808                "Expected consecutive stride.");
6809         InstWidening Decision =
6810             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6811         setWideningDecision(&I, VF, Decision, Cost);
6812         continue;
6813       }
6814 
6815       // Choose between Interleaving, Gather/Scatter or Scalarization.
6816       InstructionCost InterleaveCost = InstructionCost::getInvalid();
6817       unsigned NumAccesses = 1;
6818       if (isAccessInterleaved(&I)) {
6819         auto Group = getInterleavedAccessGroup(&I);
6820         assert(Group && "Fail to get an interleaved access group.");
6821 
6822         // Make one decision for the whole group.
6823         if (getWideningDecision(&I, VF) != CM_Unknown)
6824           continue;
6825 
6826         NumAccesses = Group->getNumMembers();
6827         if (interleavedAccessCanBeWidened(&I, VF))
6828           InterleaveCost = getInterleaveGroupCost(&I, VF);
6829       }
6830 
6831       InstructionCost GatherScatterCost =
6832           isLegalGatherOrScatter(&I, VF)
6833               ? getGatherScatterCost(&I, VF) * NumAccesses
6834               : InstructionCost::getInvalid();
6835 
6836       InstructionCost ScalarizationCost =
6837           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6838 
6839       // Choose better solution for the current VF,
6840       // write down this decision and use it during vectorization.
6841       InstructionCost Cost;
6842       InstWidening Decision;
6843       if (InterleaveCost <= GatherScatterCost &&
6844           InterleaveCost < ScalarizationCost) {
6845         Decision = CM_Interleave;
6846         Cost = InterleaveCost;
6847       } else if (GatherScatterCost < ScalarizationCost) {
6848         Decision = CM_GatherScatter;
6849         Cost = GatherScatterCost;
6850       } else {
6851         Decision = CM_Scalarize;
6852         Cost = ScalarizationCost;
6853       }
6854       // If the instructions belongs to an interleave group, the whole group
6855       // receives the same decision. The whole group receives the cost, but
6856       // the cost will actually be assigned to one instruction.
6857       if (auto Group = getInterleavedAccessGroup(&I))
6858         setWideningDecision(Group, VF, Decision, Cost);
6859       else
6860         setWideningDecision(&I, VF, Decision, Cost);
6861     }
6862   }
6863 
6864   // Make sure that any load of address and any other address computation
6865   // remains scalar unless there is gather/scatter support. This avoids
6866   // inevitable extracts into address registers, and also has the benefit of
6867   // activating LSR more, since that pass can't optimize vectorized
6868   // addresses.
6869   if (TTI.prefersVectorizedAddressing())
6870     return;
6871 
6872   // Start with all scalar pointer uses.
6873   SmallPtrSet<Instruction *, 8> AddrDefs;
6874   for (BasicBlock *BB : TheLoop->blocks())
6875     for (Instruction &I : *BB) {
6876       Instruction *PtrDef =
6877         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6878       if (PtrDef && TheLoop->contains(PtrDef) &&
6879           getWideningDecision(&I, VF) != CM_GatherScatter)
6880         AddrDefs.insert(PtrDef);
6881     }
6882 
6883   // Add all instructions used to generate the addresses.
6884   SmallVector<Instruction *, 4> Worklist;
6885   append_range(Worklist, AddrDefs);
6886   while (!Worklist.empty()) {
6887     Instruction *I = Worklist.pop_back_val();
6888     for (auto &Op : I->operands())
6889       if (auto *InstOp = dyn_cast<Instruction>(Op))
6890         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6891             AddrDefs.insert(InstOp).second)
6892           Worklist.push_back(InstOp);
6893   }
6894 
6895   for (auto *I : AddrDefs) {
6896     if (isa<LoadInst>(I)) {
6897       // Setting the desired widening decision should ideally be handled in
6898       // by cost functions, but since this involves the task of finding out
6899       // if the loaded register is involved in an address computation, it is
6900       // instead changed here when we know this is the case.
6901       InstWidening Decision = getWideningDecision(I, VF);
6902       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6903         // Scalarize a widened load of address.
6904         setWideningDecision(
6905             I, VF, CM_Scalarize,
6906             (VF.getKnownMinValue() *
6907              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6908       else if (auto Group = getInterleavedAccessGroup(I)) {
6909         // Scalarize an interleave group of address loads.
6910         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6911           if (Instruction *Member = Group->getMember(I))
6912             setWideningDecision(
6913                 Member, VF, CM_Scalarize,
6914                 (VF.getKnownMinValue() *
6915                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6916         }
6917       }
6918     } else
6919       // Make sure I gets scalarized and a cost estimate without
6920       // scalarization overhead.
6921       ForcedScalars[VF].insert(I);
6922   }
6923 }
6924 
6925 InstructionCost
6926 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
6927                                                Type *&VectorTy) {
6928   Type *RetTy = I->getType();
6929   if (canTruncateToMinimalBitwidth(I, VF))
6930     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6931   auto SE = PSE.getSE();
6932   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6933 
6934   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
6935                                                 ElementCount VF) -> bool {
6936     if (VF.isScalar())
6937       return true;
6938 
6939     auto Scalarized = InstsToScalarize.find(VF);
6940     assert(Scalarized != InstsToScalarize.end() &&
6941            "VF not yet analyzed for scalarization profitability");
6942     return !Scalarized->second.count(I) &&
6943            llvm::all_of(I->users(), [&](User *U) {
6944              auto *UI = cast<Instruction>(U);
6945              return !Scalarized->second.count(UI);
6946            });
6947   };
6948   (void) hasSingleCopyAfterVectorization;
6949 
6950   if (isScalarAfterVectorization(I, VF)) {
6951     // With the exception of GEPs and PHIs, after scalarization there should
6952     // only be one copy of the instruction generated in the loop. This is
6953     // because the VF is either 1, or any instructions that need scalarizing
6954     // have already been dealt with by the the time we get here. As a result,
6955     // it means we don't have to multiply the instruction cost by VF.
6956     assert(I->getOpcode() == Instruction::GetElementPtr ||
6957            I->getOpcode() == Instruction::PHI ||
6958            (I->getOpcode() == Instruction::BitCast &&
6959             I->getType()->isPointerTy()) ||
6960            hasSingleCopyAfterVectorization(I, VF));
6961     VectorTy = RetTy;
6962   } else
6963     VectorTy = ToVectorTy(RetTy, VF);
6964 
6965   // TODO: We need to estimate the cost of intrinsic calls.
6966   switch (I->getOpcode()) {
6967   case Instruction::GetElementPtr:
6968     // We mark this instruction as zero-cost because the cost of GEPs in
6969     // vectorized code depends on whether the corresponding memory instruction
6970     // is scalarized or not. Therefore, we handle GEPs with the memory
6971     // instruction cost.
6972     return 0;
6973   case Instruction::Br: {
6974     // In cases of scalarized and predicated instructions, there will be VF
6975     // predicated blocks in the vectorized loop. Each branch around these
6976     // blocks requires also an extract of its vector compare i1 element.
6977     bool ScalarPredicatedBB = false;
6978     BranchInst *BI = cast<BranchInst>(I);
6979     if (VF.isVector() && BI->isConditional() &&
6980         (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
6981          PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))))
6982       ScalarPredicatedBB = true;
6983 
6984     if (ScalarPredicatedBB) {
6985       // Not possible to scalarize scalable vector with predicated instructions.
6986       if (VF.isScalable())
6987         return InstructionCost::getInvalid();
6988       // Return cost for branches around scalarized and predicated blocks.
6989       auto *Vec_i1Ty =
6990           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
6991       return (
6992           TTI.getScalarizationOverhead(
6993               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
6994           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
6995     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6996       // The back-edge branch will remain, as will all scalar branches.
6997       return TTI.getCFInstrCost(Instruction::Br, CostKind);
6998     else
6999       // This branch will be eliminated by if-conversion.
7000       return 0;
7001     // Note: We currently assume zero cost for an unconditional branch inside
7002     // a predicated block since it will become a fall-through, although we
7003     // may decide in the future to call TTI for all branches.
7004   }
7005   case Instruction::PHI: {
7006     auto *Phi = cast<PHINode>(I);
7007 
7008     // First-order recurrences are replaced by vector shuffles inside the loop.
7009     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7010     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7011       return TTI.getShuffleCost(
7012           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7013           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7014 
7015     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7016     // converted into select instructions. We require N - 1 selects per phi
7017     // node, where N is the number of incoming values.
7018     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7019       return (Phi->getNumIncomingValues() - 1) *
7020              TTI.getCmpSelInstrCost(
7021                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7022                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7023                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7024 
7025     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7026   }
7027   case Instruction::UDiv:
7028   case Instruction::SDiv:
7029   case Instruction::URem:
7030   case Instruction::SRem:
7031     // If we have a predicated instruction, it may not be executed for each
7032     // vector lane. Get the scalarization cost and scale this amount by the
7033     // probability of executing the predicated block. If the instruction is not
7034     // predicated, we fall through to the next case.
7035     if (VF.isVector() && isScalarWithPredication(I, VF)) {
7036       InstructionCost Cost = 0;
7037 
7038       // These instructions have a non-void type, so account for the phi nodes
7039       // that we will create. This cost is likely to be zero. The phi node
7040       // cost, if any, should be scaled by the block probability because it
7041       // models a copy at the end of each predicated block.
7042       Cost += VF.getKnownMinValue() *
7043               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7044 
7045       // The cost of the non-predicated instruction.
7046       Cost += VF.getKnownMinValue() *
7047               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7048 
7049       // The cost of insertelement and extractelement instructions needed for
7050       // scalarization.
7051       Cost += getScalarizationOverhead(I, VF);
7052 
7053       // Scale the cost by the probability of executing the predicated blocks.
7054       // This assumes the predicated block for each vector lane is equally
7055       // likely.
7056       return Cost / getReciprocalPredBlockProb();
7057     }
7058     LLVM_FALLTHROUGH;
7059   case Instruction::Add:
7060   case Instruction::FAdd:
7061   case Instruction::Sub:
7062   case Instruction::FSub:
7063   case Instruction::Mul:
7064   case Instruction::FMul:
7065   case Instruction::FDiv:
7066   case Instruction::FRem:
7067   case Instruction::Shl:
7068   case Instruction::LShr:
7069   case Instruction::AShr:
7070   case Instruction::And:
7071   case Instruction::Or:
7072   case Instruction::Xor: {
7073     // Since we will replace the stride by 1 the multiplication should go away.
7074     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7075       return 0;
7076 
7077     // Detect reduction patterns
7078     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7079       return *RedCost;
7080 
7081     // Certain instructions can be cheaper to vectorize if they have a constant
7082     // second vector operand. One example of this are shifts on x86.
7083     Value *Op2 = I->getOperand(1);
7084     TargetTransformInfo::OperandValueProperties Op2VP;
7085     TargetTransformInfo::OperandValueKind Op2VK =
7086         TTI.getOperandInfo(Op2, Op2VP);
7087     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7088       Op2VK = TargetTransformInfo::OK_UniformValue;
7089 
7090     SmallVector<const Value *, 4> Operands(I->operand_values());
7091     return TTI.getArithmeticInstrCost(
7092         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7093         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7094   }
7095   case Instruction::FNeg: {
7096     return TTI.getArithmeticInstrCost(
7097         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7098         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7099         TargetTransformInfo::OP_None, I->getOperand(0), I);
7100   }
7101   case Instruction::Select: {
7102     SelectInst *SI = cast<SelectInst>(I);
7103     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7104     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7105 
7106     const Value *Op0, *Op1;
7107     using namespace llvm::PatternMatch;
7108     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7109                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7110       // select x, y, false --> x & y
7111       // select x, true, y --> x | y
7112       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7113       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7114       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7115       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7116       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7117               Op1->getType()->getScalarSizeInBits() == 1);
7118 
7119       SmallVector<const Value *, 2> Operands{Op0, Op1};
7120       return TTI.getArithmeticInstrCost(
7121           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7122           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7123     }
7124 
7125     Type *CondTy = SI->getCondition()->getType();
7126     if (!ScalarCond)
7127       CondTy = VectorType::get(CondTy, VF);
7128 
7129     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7130     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7131       Pred = Cmp->getPredicate();
7132     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7133                                   CostKind, I);
7134   }
7135   case Instruction::ICmp:
7136   case Instruction::FCmp: {
7137     Type *ValTy = I->getOperand(0)->getType();
7138     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7139     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7140       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7141     VectorTy = ToVectorTy(ValTy, VF);
7142     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7143                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7144                                   I);
7145   }
7146   case Instruction::Store:
7147   case Instruction::Load: {
7148     ElementCount Width = VF;
7149     if (Width.isVector()) {
7150       InstWidening Decision = getWideningDecision(I, Width);
7151       assert(Decision != CM_Unknown &&
7152              "CM decision should be taken at this point");
7153       if (getWideningCost(I, VF) == InstructionCost::getInvalid())
7154         return InstructionCost::getInvalid();
7155       if (Decision == CM_Scalarize)
7156         Width = ElementCount::getFixed(1);
7157     }
7158     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7159     return getMemoryInstructionCost(I, VF);
7160   }
7161   case Instruction::BitCast:
7162     if (I->getType()->isPointerTy())
7163       return 0;
7164     LLVM_FALLTHROUGH;
7165   case Instruction::ZExt:
7166   case Instruction::SExt:
7167   case Instruction::FPToUI:
7168   case Instruction::FPToSI:
7169   case Instruction::FPExt:
7170   case Instruction::PtrToInt:
7171   case Instruction::IntToPtr:
7172   case Instruction::SIToFP:
7173   case Instruction::UIToFP:
7174   case Instruction::Trunc:
7175   case Instruction::FPTrunc: {
7176     // Computes the CastContextHint from a Load/Store instruction.
7177     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7178       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7179              "Expected a load or a store!");
7180 
7181       if (VF.isScalar() || !TheLoop->contains(I))
7182         return TTI::CastContextHint::Normal;
7183 
7184       switch (getWideningDecision(I, VF)) {
7185       case LoopVectorizationCostModel::CM_GatherScatter:
7186         return TTI::CastContextHint::GatherScatter;
7187       case LoopVectorizationCostModel::CM_Interleave:
7188         return TTI::CastContextHint::Interleave;
7189       case LoopVectorizationCostModel::CM_Scalarize:
7190       case LoopVectorizationCostModel::CM_Widen:
7191         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7192                                         : TTI::CastContextHint::Normal;
7193       case LoopVectorizationCostModel::CM_Widen_Reverse:
7194         return TTI::CastContextHint::Reversed;
7195       case LoopVectorizationCostModel::CM_Unknown:
7196         llvm_unreachable("Instr did not go through cost modelling?");
7197       }
7198 
7199       llvm_unreachable("Unhandled case!");
7200     };
7201 
7202     unsigned Opcode = I->getOpcode();
7203     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7204     // For Trunc, the context is the only user, which must be a StoreInst.
7205     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7206       if (I->hasOneUse())
7207         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7208           CCH = ComputeCCH(Store);
7209     }
7210     // For Z/Sext, the context is the operand, which must be a LoadInst.
7211     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7212              Opcode == Instruction::FPExt) {
7213       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7214         CCH = ComputeCCH(Load);
7215     }
7216 
7217     // We optimize the truncation of induction variables having constant
7218     // integer steps. The cost of these truncations is the same as the scalar
7219     // operation.
7220     if (isOptimizableIVTruncate(I, VF)) {
7221       auto *Trunc = cast<TruncInst>(I);
7222       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7223                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7224     }
7225 
7226     // Detect reduction patterns
7227     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7228       return *RedCost;
7229 
7230     Type *SrcScalarTy = I->getOperand(0)->getType();
7231     Type *SrcVecTy =
7232         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7233     if (canTruncateToMinimalBitwidth(I, VF)) {
7234       // This cast is going to be shrunk. This may remove the cast or it might
7235       // turn it into slightly different cast. For example, if MinBW == 16,
7236       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7237       //
7238       // Calculate the modified src and dest types.
7239       Type *MinVecTy = VectorTy;
7240       if (Opcode == Instruction::Trunc) {
7241         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7242         VectorTy =
7243             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7244       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7245         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7246         VectorTy =
7247             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7248       }
7249     }
7250 
7251     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7252   }
7253   case Instruction::Call: {
7254     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7255       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7256         return *RedCost;
7257     bool NeedToScalarize;
7258     CallInst *CI = cast<CallInst>(I);
7259     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7260     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7261       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7262       return std::min(CallCost, IntrinsicCost);
7263     }
7264     return CallCost;
7265   }
7266   case Instruction::ExtractValue:
7267     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7268   case Instruction::Alloca:
7269     // We cannot easily widen alloca to a scalable alloca, as
7270     // the result would need to be a vector of pointers.
7271     if (VF.isScalable())
7272       return InstructionCost::getInvalid();
7273     LLVM_FALLTHROUGH;
7274   default:
7275     // This opcode is unknown. Assume that it is the same as 'mul'.
7276     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7277   } // end of switch.
7278 }
7279 
7280 char LoopVectorize::ID = 0;
7281 
7282 static const char lv_name[] = "Loop Vectorization";
7283 
7284 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7285 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7286 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7287 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7288 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7289 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7290 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7291 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7292 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7293 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7294 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7295 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7296 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7297 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7298 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7299 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7300 
7301 namespace llvm {
7302 
7303 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7304 
7305 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7306                               bool VectorizeOnlyWhenForced) {
7307   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7308 }
7309 
7310 } // end namespace llvm
7311 
7312 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7313   // Check if the pointer operand of a load or store instruction is
7314   // consecutive.
7315   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7316     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7317   return false;
7318 }
7319 
7320 void LoopVectorizationCostModel::collectValuesToIgnore() {
7321   // Ignore ephemeral values.
7322   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7323 
7324   // Find all stores to invariant variables. Since they are going to sink
7325   // outside the loop we do not need calculate cost for them.
7326   for (BasicBlock *BB : TheLoop->blocks())
7327     for (Instruction &I : *BB) {
7328       StoreInst *SI;
7329       if ((SI = dyn_cast<StoreInst>(&I)) &&
7330           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
7331         ValuesToIgnore.insert(&I);
7332     }
7333 
7334   // Ignore type-promoting instructions we identified during reduction
7335   // detection.
7336   for (auto &Reduction : Legal->getReductionVars()) {
7337     const RecurrenceDescriptor &RedDes = Reduction.second;
7338     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7339     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7340   }
7341   // Ignore type-casting instructions we identified during induction
7342   // detection.
7343   for (auto &Induction : Legal->getInductionVars()) {
7344     const InductionDescriptor &IndDes = Induction.second;
7345     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7346     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7347   }
7348 }
7349 
7350 void LoopVectorizationCostModel::collectInLoopReductions() {
7351   for (auto &Reduction : Legal->getReductionVars()) {
7352     PHINode *Phi = Reduction.first;
7353     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7354 
7355     // We don't collect reductions that are type promoted (yet).
7356     if (RdxDesc.getRecurrenceType() != Phi->getType())
7357       continue;
7358 
7359     // If the target would prefer this reduction to happen "in-loop", then we
7360     // want to record it as such.
7361     unsigned Opcode = RdxDesc.getOpcode();
7362     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7363         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7364                                    TargetTransformInfo::ReductionFlags()))
7365       continue;
7366 
7367     // Check that we can correctly put the reductions into the loop, by
7368     // finding the chain of operations that leads from the phi to the loop
7369     // exit value.
7370     SmallVector<Instruction *, 4> ReductionOperations =
7371         RdxDesc.getReductionOpChain(Phi, TheLoop);
7372     bool InLoop = !ReductionOperations.empty();
7373     if (InLoop) {
7374       InLoopReductionChains[Phi] = ReductionOperations;
7375       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7376       Instruction *LastChain = Phi;
7377       for (auto *I : ReductionOperations) {
7378         InLoopReductionImmediateChains[I] = LastChain;
7379         LastChain = I;
7380       }
7381     }
7382     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7383                       << " reduction for phi: " << *Phi << "\n");
7384   }
7385 }
7386 
7387 // TODO: we could return a pair of values that specify the max VF and
7388 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7389 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7390 // doesn't have a cost model that can choose which plan to execute if
7391 // more than one is generated.
7392 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7393                                  LoopVectorizationCostModel &CM) {
7394   unsigned WidestType;
7395   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7396   return WidestVectorRegBits / WidestType;
7397 }
7398 
7399 VectorizationFactor
7400 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7401   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7402   ElementCount VF = UserVF;
7403   // Outer loop handling: They may require CFG and instruction level
7404   // transformations before even evaluating whether vectorization is profitable.
7405   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7406   // the vectorization pipeline.
7407   if (!OrigLoop->isInnermost()) {
7408     // If the user doesn't provide a vectorization factor, determine a
7409     // reasonable one.
7410     if (UserVF.isZero()) {
7411       VF = ElementCount::getFixed(determineVPlanVF(
7412           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7413               .getFixedSize(),
7414           CM));
7415       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7416 
7417       // Make sure we have a VF > 1 for stress testing.
7418       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7419         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7420                           << "overriding computed VF.\n");
7421         VF = ElementCount::getFixed(4);
7422       }
7423     }
7424     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7425     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7426            "VF needs to be a power of two");
7427     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7428                       << "VF " << VF << " to build VPlans.\n");
7429     buildVPlans(VF, VF);
7430 
7431     // For VPlan build stress testing, we bail out after VPlan construction.
7432     if (VPlanBuildStressTest)
7433       return VectorizationFactor::Disabled();
7434 
7435     return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
7436   }
7437 
7438   LLVM_DEBUG(
7439       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7440                 "VPlan-native path.\n");
7441   return VectorizationFactor::Disabled();
7442 }
7443 
7444 Optional<VectorizationFactor>
7445 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7446   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7447   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7448   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7449     return None;
7450 
7451   // Invalidate interleave groups if all blocks of loop will be predicated.
7452   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7453       !useMaskedInterleavedAccesses(*TTI)) {
7454     LLVM_DEBUG(
7455         dbgs()
7456         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7457            "which requires masked-interleaved support.\n");
7458     if (CM.InterleaveInfo.invalidateGroups())
7459       // Invalidating interleave groups also requires invalidating all decisions
7460       // based on them, which includes widening decisions and uniform and scalar
7461       // values.
7462       CM.invalidateCostModelingDecisions();
7463   }
7464 
7465   ElementCount MaxUserVF =
7466       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7467   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7468   if (!UserVF.isZero() && UserVFIsLegal) {
7469     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7470            "VF needs to be a power of two");
7471     // Collect the instructions (and their associated costs) that will be more
7472     // profitable to scalarize.
7473     if (CM.selectUserVectorizationFactor(UserVF)) {
7474       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7475       CM.collectInLoopReductions();
7476       buildVPlansWithVPRecipes(UserVF, UserVF);
7477       LLVM_DEBUG(printPlans(dbgs()));
7478       return {{UserVF, 0, 0}};
7479     } else
7480       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7481                               "InvalidCost", ORE, OrigLoop);
7482   }
7483 
7484   // Populate the set of Vectorization Factor Candidates.
7485   ElementCountSet VFCandidates;
7486   for (auto VF = ElementCount::getFixed(1);
7487        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7488     VFCandidates.insert(VF);
7489   for (auto VF = ElementCount::getScalable(1);
7490        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7491     VFCandidates.insert(VF);
7492 
7493   for (const auto &VF : VFCandidates) {
7494     // Collect Uniform and Scalar instructions after vectorization with VF.
7495     CM.collectUniformsAndScalars(VF);
7496 
7497     // Collect the instructions (and their associated costs) that will be more
7498     // profitable to scalarize.
7499     if (VF.isVector())
7500       CM.collectInstsToScalarize(VF);
7501   }
7502 
7503   CM.collectInLoopReductions();
7504   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7505   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7506 
7507   LLVM_DEBUG(printPlans(dbgs()));
7508   if (!MaxFactors.hasVector())
7509     return VectorizationFactor::Disabled();
7510 
7511   // Select the optimal vectorization factor.
7512   VectorizationFactor VF = CM.selectVectorizationFactor(VFCandidates);
7513   assert((VF.Width.isScalar() || VF.ScalarCost > 0) && "when vectorizing, the scalar cost must be non-zero.");
7514   return VF;
7515 }
7516 
7517 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7518   assert(count_if(VPlans,
7519                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7520              1 &&
7521          "Best VF has not a single VPlan.");
7522 
7523   for (const VPlanPtr &Plan : VPlans) {
7524     if (Plan->hasVF(VF))
7525       return *Plan.get();
7526   }
7527   llvm_unreachable("No plan found!");
7528 }
7529 
7530 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7531   SmallVector<Metadata *, 4> MDs;
7532   // Reserve first location for self reference to the LoopID metadata node.
7533   MDs.push_back(nullptr);
7534   bool IsUnrollMetadata = false;
7535   MDNode *LoopID = L->getLoopID();
7536   if (LoopID) {
7537     // First find existing loop unrolling disable metadata.
7538     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7539       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7540       if (MD) {
7541         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7542         IsUnrollMetadata =
7543             S && S->getString().startswith("llvm.loop.unroll.disable");
7544       }
7545       MDs.push_back(LoopID->getOperand(i));
7546     }
7547   }
7548 
7549   if (!IsUnrollMetadata) {
7550     // Add runtime unroll disable metadata.
7551     LLVMContext &Context = L->getHeader()->getContext();
7552     SmallVector<Metadata *, 1> DisableOperands;
7553     DisableOperands.push_back(
7554         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7555     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7556     MDs.push_back(DisableNode);
7557     MDNode *NewLoopID = MDNode::get(Context, MDs);
7558     // Set operand 0 to refer to the loop id itself.
7559     NewLoopID->replaceOperandWith(0, NewLoopID);
7560     L->setLoopID(NewLoopID);
7561   }
7562 }
7563 
7564 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7565                                            VPlan &BestVPlan,
7566                                            InnerLoopVectorizer &ILV,
7567                                            DominatorTree *DT,
7568                                            bool IsEpilogueVectorization) {
7569   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7570                     << '\n');
7571 
7572   // Perform the actual loop transformation.
7573 
7574   // 1. Set up the skeleton for vectorization, including vector pre-header and
7575   // middle block. The vector loop is created during VPlan execution.
7576   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7577   Value *CanonicalIVStartValue;
7578   std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
7579       ILV.createVectorizedLoopSkeleton();
7580 
7581   // Only use noalias metadata when using memory checks guaranteeing no overlap
7582   // across all iterations.
7583   const LoopAccessInfo *LAI = ILV.Legal->getLAI();
7584   if (LAI && !LAI->getRuntimePointerChecking()->getChecks().empty() &&
7585       !LAI->getRuntimePointerChecking()->getDiffChecks()) {
7586 
7587     //  We currently don't use LoopVersioning for the actual loop cloning but we
7588     //  still use it to add the noalias metadata.
7589     //  TODO: Find a better way to re-use LoopVersioning functionality to add
7590     //        metadata.
7591     State.LVer = std::make_unique<LoopVersioning>(
7592         *LAI, LAI->getRuntimePointerChecking()->getChecks(), OrigLoop, LI, DT,
7593         PSE.getSE());
7594     State.LVer->prepareNoAliasMetadata();
7595   }
7596 
7597   ILV.collectPoisonGeneratingRecipes(State);
7598 
7599   ILV.printDebugTracesAtStart();
7600 
7601   //===------------------------------------------------===//
7602   //
7603   // Notice: any optimization or new instruction that go
7604   // into the code below should also be implemented in
7605   // the cost-model.
7606   //
7607   //===------------------------------------------------===//
7608 
7609   // 2. Copy and widen instructions from the old loop into the new loop.
7610   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
7611                              ILV.getOrCreateVectorTripCount(nullptr),
7612                              CanonicalIVStartValue, State,
7613                              IsEpilogueVectorization);
7614 
7615   BestVPlan.execute(&State);
7616 
7617   // Keep all loop hints from the original loop on the vector loop (we'll
7618   // replace the vectorizer-specific hints below).
7619   MDNode *OrigLoopID = OrigLoop->getLoopID();
7620 
7621   Optional<MDNode *> VectorizedLoopID =
7622       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7623                                       LLVMLoopVectorizeFollowupVectorized});
7624 
7625   VPBasicBlock *HeaderVPBB =
7626       BestVPlan.getVectorLoopRegion()->getEntryBasicBlock();
7627   Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
7628   if (VectorizedLoopID)
7629     L->setLoopID(VectorizedLoopID.value());
7630   else {
7631     // Keep all loop hints from the original loop on the vector loop (we'll
7632     // replace the vectorizer-specific hints below).
7633     if (MDNode *LID = OrigLoop->getLoopID())
7634       L->setLoopID(LID);
7635 
7636     LoopVectorizeHints Hints(L, true, *ORE);
7637     Hints.setAlreadyVectorized();
7638   }
7639   // Disable runtime unrolling when vectorizing the epilogue loop.
7640   if (CanonicalIVStartValue)
7641     AddRuntimeUnrollDisableMetaData(L);
7642 
7643   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7644   //    predication, updating analyses.
7645   ILV.fixVectorizedLoop(State, BestVPlan);
7646 
7647   ILV.printDebugTracesAtEnd();
7648 }
7649 
7650 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7651 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7652   for (const auto &Plan : VPlans)
7653     if (PrintVPlansInDotFormat)
7654       Plan->printDOT(O);
7655     else
7656       Plan->print(O);
7657 }
7658 #endif
7659 
7660 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7661 
7662 //===--------------------------------------------------------------------===//
7663 // EpilogueVectorizerMainLoop
7664 //===--------------------------------------------------------------------===//
7665 
7666 /// This function is partially responsible for generating the control flow
7667 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7668 std::pair<BasicBlock *, Value *>
7669 EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7670   MDNode *OrigLoopID = OrigLoop->getLoopID();
7671 
7672   // Workaround!  Compute the trip count of the original loop and cache it
7673   // before we start modifying the CFG.  This code has a systemic problem
7674   // wherein it tries to run analysis over partially constructed IR; this is
7675   // wrong, and not simply for SCEV.  The trip count of the original loop
7676   // simply happens to be prone to hitting this in practice.  In theory, we
7677   // can hit the same issue for any SCEV, or ValueTracking query done during
7678   // mutation.  See PR49900.
7679   getOrCreateTripCount(OrigLoop->getLoopPreheader());
7680   createVectorLoopSkeleton("");
7681 
7682   // Generate the code to check the minimum iteration count of the vector
7683   // epilogue (see below).
7684   EPI.EpilogueIterationCountCheck =
7685       emitIterationCountCheck(LoopScalarPreHeader, true);
7686   EPI.EpilogueIterationCountCheck->setName("iter.check");
7687 
7688   // Generate the code to check any assumptions that we've made for SCEV
7689   // expressions.
7690   EPI.SCEVSafetyCheck = emitSCEVChecks(LoopScalarPreHeader);
7691 
7692   // Generate the code that checks at runtime if arrays overlap. We put the
7693   // checks into a separate block to make the more common case of few elements
7694   // faster.
7695   EPI.MemSafetyCheck = emitMemRuntimeChecks(LoopScalarPreHeader);
7696 
7697   // Generate the iteration count check for the main loop, *after* the check
7698   // for the epilogue loop, so that the path-length is shorter for the case
7699   // that goes directly through the vector epilogue. The longer-path length for
7700   // the main loop is compensated for, by the gain from vectorizing the larger
7701   // trip count. Note: the branch will get updated later on when we vectorize
7702   // the epilogue.
7703   EPI.MainLoopIterationCountCheck =
7704       emitIterationCountCheck(LoopScalarPreHeader, false);
7705 
7706   // Generate the induction variable.
7707   EPI.VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
7708 
7709   // Skip induction resume value creation here because they will be created in
7710   // the second pass. If we created them here, they wouldn't be used anyway,
7711   // because the vplan in the second pass still contains the inductions from the
7712   // original loop.
7713 
7714   return {completeLoopSkeleton(OrigLoopID), nullptr};
7715 }
7716 
7717 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7718   LLVM_DEBUG({
7719     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7720            << "Main Loop VF:" << EPI.MainLoopVF
7721            << ", Main Loop UF:" << EPI.MainLoopUF
7722            << ", Epilogue Loop VF:" << EPI.EpilogueVF
7723            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7724   });
7725 }
7726 
7727 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7728   DEBUG_WITH_TYPE(VerboseDebug, {
7729     dbgs() << "intermediate fn:\n"
7730            << *OrigLoop->getHeader()->getParent() << "\n";
7731   });
7732 }
7733 
7734 BasicBlock *
7735 EpilogueVectorizerMainLoop::emitIterationCountCheck(BasicBlock *Bypass,
7736                                                     bool ForEpilogue) {
7737   assert(Bypass && "Expected valid bypass basic block.");
7738   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
7739   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
7740   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
7741   // Reuse existing vector loop preheader for TC checks.
7742   // Note that new preheader block is generated for vector loop.
7743   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7744   IRBuilder<> Builder(TCCheckBlock->getTerminator());
7745 
7746   // Generate code to check if the loop's trip count is less than VF * UF of the
7747   // main vector loop.
7748   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
7749       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7750 
7751   Value *CheckMinIters = Builder.CreateICmp(
7752       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
7753       "min.iters.check");
7754 
7755   if (!ForEpilogue)
7756     TCCheckBlock->setName("vector.main.loop.iter.check");
7757 
7758   // Create new preheader for vector loop.
7759   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7760                                    DT, LI, nullptr, "vector.ph");
7761 
7762   if (ForEpilogue) {
7763     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
7764                                  DT->getNode(Bypass)->getIDom()) &&
7765            "TC check is expected to dominate Bypass");
7766 
7767     // Update dominator for Bypass & LoopExit.
7768     DT->changeImmediateDominator(Bypass, TCCheckBlock);
7769     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7770       // For loops with multiple exits, there's no edge from the middle block
7771       // to exit blocks (as the epilogue must run) and thus no need to update
7772       // the immediate dominator of the exit blocks.
7773       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
7774 
7775     LoopBypassBlocks.push_back(TCCheckBlock);
7776 
7777     // Save the trip count so we don't have to regenerate it in the
7778     // vec.epilog.iter.check. This is safe to do because the trip count
7779     // generated here dominates the vector epilog iter check.
7780     EPI.TripCount = Count;
7781   }
7782 
7783   ReplaceInstWithInst(
7784       TCCheckBlock->getTerminator(),
7785       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7786 
7787   return TCCheckBlock;
7788 }
7789 
7790 //===--------------------------------------------------------------------===//
7791 // EpilogueVectorizerEpilogueLoop
7792 //===--------------------------------------------------------------------===//
7793 
7794 /// This function is partially responsible for generating the control flow
7795 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7796 std::pair<BasicBlock *, Value *>
7797 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
7798   MDNode *OrigLoopID = OrigLoop->getLoopID();
7799   createVectorLoopSkeleton("vec.epilog.");
7800 
7801   // Now, compare the remaining count and if there aren't enough iterations to
7802   // execute the vectorized epilogue skip to the scalar part.
7803   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
7804   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
7805   LoopVectorPreHeader =
7806       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
7807                  LI, nullptr, "vec.epilog.ph");
7808   emitMinimumVectorEpilogueIterCountCheck(LoopScalarPreHeader,
7809                                           VecEpilogueIterationCountCheck);
7810 
7811   // Adjust the control flow taking the state info from the main loop
7812   // vectorization into account.
7813   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
7814          "expected this to be saved from the previous pass.");
7815   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
7816       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7817 
7818   DT->changeImmediateDominator(LoopVectorPreHeader,
7819                                EPI.MainLoopIterationCountCheck);
7820 
7821   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
7822       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7823 
7824   if (EPI.SCEVSafetyCheck)
7825     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
7826         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7827   if (EPI.MemSafetyCheck)
7828     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
7829         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7830 
7831   DT->changeImmediateDominator(
7832       VecEpilogueIterationCountCheck,
7833       VecEpilogueIterationCountCheck->getSinglePredecessor());
7834 
7835   DT->changeImmediateDominator(LoopScalarPreHeader,
7836                                EPI.EpilogueIterationCountCheck);
7837   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7838     // If there is an epilogue which must run, there's no edge from the
7839     // middle block to exit blocks  and thus no need to update the immediate
7840     // dominator of the exit blocks.
7841     DT->changeImmediateDominator(LoopExitBlock,
7842                                  EPI.EpilogueIterationCountCheck);
7843 
7844   // Keep track of bypass blocks, as they feed start values to the induction
7845   // phis in the scalar loop preheader.
7846   if (EPI.SCEVSafetyCheck)
7847     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
7848   if (EPI.MemSafetyCheck)
7849     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
7850   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
7851 
7852   // The vec.epilog.iter.check block may contain Phi nodes from reductions which
7853   // merge control-flow from the latch block and the middle block. Update the
7854   // incoming values here and move the Phi into the preheader.
7855   SmallVector<PHINode *, 4> PhisInBlock;
7856   for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
7857     PhisInBlock.push_back(&Phi);
7858 
7859   for (PHINode *Phi : PhisInBlock) {
7860     Phi->replaceIncomingBlockWith(
7861         VecEpilogueIterationCountCheck->getSinglePredecessor(),
7862         VecEpilogueIterationCountCheck);
7863     Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7864     if (EPI.SCEVSafetyCheck)
7865       Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
7866     if (EPI.MemSafetyCheck)
7867       Phi->removeIncomingValue(EPI.MemSafetyCheck);
7868     Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
7869   }
7870 
7871   // Generate a resume induction for the vector epilogue and put it in the
7872   // vector epilogue preheader
7873   Type *IdxTy = Legal->getWidestInductionType();
7874   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
7875                                          LoopVectorPreHeader->getFirstNonPHI());
7876   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
7877   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
7878                            EPI.MainLoopIterationCountCheck);
7879 
7880   // Generate induction resume values. These variables save the new starting
7881   // indexes for the scalar loop. They are used to test if there are any tail
7882   // iterations left once the vector loop has completed.
7883   // Note that when the vectorized epilogue is skipped due to iteration count
7884   // check, then the resume value for the induction variable comes from
7885   // the trip count of the main vector loop, hence passing the AdditionalBypass
7886   // argument.
7887   createInductionResumeValues({VecEpilogueIterationCountCheck,
7888                                EPI.VectorTripCount} /* AdditionalBypass */);
7889 
7890   return {completeLoopSkeleton(OrigLoopID), EPResumeVal};
7891 }
7892 
7893 BasicBlock *
7894 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
7895     BasicBlock *Bypass, BasicBlock *Insert) {
7896 
7897   assert(EPI.TripCount &&
7898          "Expected trip count to have been safed in the first pass.");
7899   assert(
7900       (!isa<Instruction>(EPI.TripCount) ||
7901        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
7902       "saved trip count does not dominate insertion point.");
7903   Value *TC = EPI.TripCount;
7904   IRBuilder<> Builder(Insert->getTerminator());
7905   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7906 
7907   // Generate code to check if the loop's trip count is less than VF * UF of the
7908   // vector epilogue loop.
7909   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
7910       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7911 
7912   Value *CheckMinIters =
7913       Builder.CreateICmp(P, Count,
7914                          createStepForVF(Builder, Count->getType(),
7915                                          EPI.EpilogueVF, EPI.EpilogueUF),
7916                          "min.epilog.iters.check");
7917 
7918   ReplaceInstWithInst(
7919       Insert->getTerminator(),
7920       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7921 
7922   LoopBypassBlocks.push_back(Insert);
7923   return Insert;
7924 }
7925 
7926 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
7927   LLVM_DEBUG({
7928     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7929            << "Epilogue Loop VF:" << EPI.EpilogueVF
7930            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7931   });
7932 }
7933 
7934 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
7935   DEBUG_WITH_TYPE(VerboseDebug, {
7936     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7937   });
7938 }
7939 
7940 bool LoopVectorizationPlanner::getDecisionAndClampRange(
7941     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
7942   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
7943   bool PredicateAtRangeStart = Predicate(Range.Start);
7944 
7945   for (ElementCount TmpVF = Range.Start * 2;
7946        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
7947     if (Predicate(TmpVF) != PredicateAtRangeStart) {
7948       Range.End = TmpVF;
7949       break;
7950     }
7951 
7952   return PredicateAtRangeStart;
7953 }
7954 
7955 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
7956 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
7957 /// of VF's starting at a given VF and extending it as much as possible. Each
7958 /// vectorization decision can potentially shorten this sub-range during
7959 /// buildVPlan().
7960 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
7961                                            ElementCount MaxVF) {
7962   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
7963   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
7964     VFRange SubRange = {VF, MaxVFPlusOne};
7965     VPlans.push_back(buildVPlan(SubRange));
7966     VF = SubRange.End;
7967   }
7968 }
7969 
7970 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
7971                                          VPlanPtr &Plan) {
7972   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
7973 
7974   // Look for cached value.
7975   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7976   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
7977   if (ECEntryIt != EdgeMaskCache.end())
7978     return ECEntryIt->second;
7979 
7980   VPValue *SrcMask = createBlockInMask(Src, Plan);
7981 
7982   // The terminator has to be a branch inst!
7983   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
7984   assert(BI && "Unexpected terminator found");
7985 
7986   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
7987     return EdgeMaskCache[Edge] = SrcMask;
7988 
7989   // If source is an exiting block, we know the exit edge is dynamically dead
7990   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
7991   // adding uses of an otherwise potentially dead instruction.
7992   if (OrigLoop->isLoopExiting(Src))
7993     return EdgeMaskCache[Edge] = SrcMask;
7994 
7995   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
7996   assert(EdgeMask && "No Edge Mask found for condition");
7997 
7998   if (BI->getSuccessor(0) != Dst)
7999     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8000 
8001   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8002     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8003     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8004     // The select version does not introduce new UB if SrcMask is false and
8005     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8006     VPValue *False = Plan->getOrAddVPValue(
8007         ConstantInt::getFalse(BI->getCondition()->getType()));
8008     EdgeMask =
8009         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8010   }
8011 
8012   return EdgeMaskCache[Edge] = EdgeMask;
8013 }
8014 
8015 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8016   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8017 
8018   // Look for cached value.
8019   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8020   if (BCEntryIt != BlockMaskCache.end())
8021     return BCEntryIt->second;
8022 
8023   // All-one mask is modelled as no-mask following the convention for masked
8024   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8025   VPValue *BlockMask = nullptr;
8026 
8027   if (OrigLoop->getHeader() == BB) {
8028     if (!CM.blockNeedsPredicationForAnyReason(BB))
8029       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8030 
8031     assert(CM.foldTailByMasking() && "must fold the tail");
8032 
8033     // If we're using the active lane mask for control flow, then we get the
8034     // mask from the active lane mask PHI that is cached in the VPlan.
8035     PredicationStyle EmitGetActiveLaneMask = CM.TTI.emitGetActiveLaneMask();
8036     if (EmitGetActiveLaneMask == PredicationStyle::DataAndControlFlow)
8037       return BlockMaskCache[BB] = Plan->getActiveLaneMaskPhi();
8038 
8039     // Introduce the early-exit compare IV <= BTC to form header block mask.
8040     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8041     // constructing the desired canonical IV in the header block as its first
8042     // non-phi instructions.
8043 
8044     VPBasicBlock *HeaderVPBB =
8045         Plan->getVectorLoopRegion()->getEntryBasicBlock();
8046     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8047     auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
8048     HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
8049 
8050     VPBuilder::InsertPointGuard Guard(Builder);
8051     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8052     if (EmitGetActiveLaneMask != PredicationStyle::None) {
8053       VPValue *TC = Plan->getOrCreateTripCount();
8054       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC},
8055                                        nullptr, "active.lane.mask");
8056     } else {
8057       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8058       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8059     }
8060     return BlockMaskCache[BB] = BlockMask;
8061   }
8062 
8063   // This is the block mask. We OR all incoming edges.
8064   for (auto *Predecessor : predecessors(BB)) {
8065     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8066     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8067       return BlockMaskCache[BB] = EdgeMask;
8068 
8069     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8070       BlockMask = EdgeMask;
8071       continue;
8072     }
8073 
8074     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8075   }
8076 
8077   return BlockMaskCache[BB] = BlockMask;
8078 }
8079 
8080 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8081                                                 ArrayRef<VPValue *> Operands,
8082                                                 VFRange &Range,
8083                                                 VPlanPtr &Plan) {
8084   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8085          "Must be called with either a load or store");
8086 
8087   auto willWiden = [&](ElementCount VF) -> bool {
8088     LoopVectorizationCostModel::InstWidening Decision =
8089         CM.getWideningDecision(I, VF);
8090     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8091            "CM decision should be taken at this point.");
8092     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8093       return true;
8094     if (CM.isScalarAfterVectorization(I, VF) ||
8095         CM.isProfitableToScalarize(I, VF))
8096       return false;
8097     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8098   };
8099 
8100   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8101     return nullptr;
8102 
8103   VPValue *Mask = nullptr;
8104   if (Legal->isMaskRequired(I))
8105     Mask = createBlockInMask(I->getParent(), Plan);
8106 
8107   // Determine if the pointer operand of the access is either consecutive or
8108   // reverse consecutive.
8109   LoopVectorizationCostModel::InstWidening Decision =
8110       CM.getWideningDecision(I, Range.Start);
8111   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8112   bool Consecutive =
8113       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8114 
8115   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8116     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8117                                               Consecutive, Reverse);
8118 
8119   StoreInst *Store = cast<StoreInst>(I);
8120   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8121                                             Mask, Consecutive, Reverse);
8122 }
8123 
8124 /// Creates a VPWidenIntOrFpInductionRecpipe for \p Phi. If needed, it will also
8125 /// insert a recipe to expand the step for the induction recipe.
8126 static VPWidenIntOrFpInductionRecipe *createWidenInductionRecipes(
8127     PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start,
8128     const InductionDescriptor &IndDesc, LoopVectorizationCostModel &CM,
8129     VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop, VFRange &Range) {
8130   // Returns true if an instruction \p I should be scalarized instead of
8131   // vectorized for the chosen vectorization factor.
8132   auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
8133     return CM.isScalarAfterVectorization(I, VF) ||
8134            CM.isProfitableToScalarize(I, VF);
8135   };
8136 
8137   bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
8138       [&](ElementCount VF) {
8139         return ShouldScalarizeInstruction(PhiOrTrunc, VF);
8140       },
8141       Range);
8142   assert(IndDesc.getStartValue() ==
8143          Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
8144   assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
8145          "step must be loop invariant");
8146 
8147   VPValue *Step =
8148       vputils::getOrCreateVPValueForSCEVExpr(Plan, IndDesc.getStep(), SE);
8149   if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8150     return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc, TruncI,
8151                                              !NeedsScalarIVOnly);
8152   }
8153   assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
8154   return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc,
8155                                            !NeedsScalarIVOnly);
8156 }
8157 
8158 VPRecipeBase *VPRecipeBuilder::tryToOptimizeInductionPHI(
8159     PHINode *Phi, ArrayRef<VPValue *> Operands, VPlan &Plan, VFRange &Range) {
8160 
8161   // Check if this is an integer or fp induction. If so, build the recipe that
8162   // produces its scalar and vector values.
8163   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
8164     return createWidenInductionRecipes(Phi, Phi, Operands[0], *II, CM, Plan,
8165                                        *PSE.getSE(), *OrigLoop, Range);
8166 
8167   // Check if this is pointer induction. If so, build the recipe for it.
8168   if (auto *II = Legal->getPointerInductionDescriptor(Phi))
8169     return new VPWidenPointerInductionRecipe(Phi, Operands[0], *II,
8170                                              *PSE.getSE());
8171   return nullptr;
8172 }
8173 
8174 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8175     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range, VPlan &Plan) {
8176   // Optimize the special case where the source is a constant integer
8177   // induction variable. Notice that we can only optimize the 'trunc' case
8178   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8179   // (c) other casts depend on pointer size.
8180 
8181   // Determine whether \p K is a truncation based on an induction variable that
8182   // can be optimized.
8183   auto isOptimizableIVTruncate =
8184       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8185     return [=](ElementCount VF) -> bool {
8186       return CM.isOptimizableIVTruncate(K, VF);
8187     };
8188   };
8189 
8190   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8191           isOptimizableIVTruncate(I), Range)) {
8192 
8193     auto *Phi = cast<PHINode>(I->getOperand(0));
8194     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8195     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8196     return createWidenInductionRecipes(Phi, I, Start, II, CM, Plan,
8197                                        *PSE.getSE(), *OrigLoop, Range);
8198   }
8199   return nullptr;
8200 }
8201 
8202 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8203                                                 ArrayRef<VPValue *> Operands,
8204                                                 VPlanPtr &Plan) {
8205   // If all incoming values are equal, the incoming VPValue can be used directly
8206   // instead of creating a new VPBlendRecipe.
8207   VPValue *FirstIncoming = Operands[0];
8208   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8209         return FirstIncoming == Inc;
8210       })) {
8211     return Operands[0];
8212   }
8213 
8214   unsigned NumIncoming = Phi->getNumIncomingValues();
8215   // For in-loop reductions, we do not need to create an additional select.
8216   VPValue *InLoopVal = nullptr;
8217   for (unsigned In = 0; In < NumIncoming; In++) {
8218     PHINode *PhiOp =
8219         dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
8220     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
8221       assert(!InLoopVal && "Found more than one in-loop reduction!");
8222       InLoopVal = Operands[In];
8223     }
8224   }
8225 
8226   assert((!InLoopVal || NumIncoming == 2) &&
8227          "Found an in-loop reduction for PHI with unexpected number of "
8228          "incoming values");
8229   if (InLoopVal)
8230     return Operands[Operands[0] == InLoopVal ? 1 : 0];
8231 
8232   // We know that all PHIs in non-header blocks are converted into selects, so
8233   // we don't have to worry about the insertion order and we can just use the
8234   // builder. At this point we generate the predication tree. There may be
8235   // duplications since this is a simple recursive scan, but future
8236   // optimizations will clean it up.
8237   SmallVector<VPValue *, 2> OperandsWithMask;
8238 
8239   for (unsigned In = 0; In < NumIncoming; In++) {
8240     VPValue *EdgeMask =
8241       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8242     assert((EdgeMask || NumIncoming == 1) &&
8243            "Multiple predecessors with one having a full mask");
8244     OperandsWithMask.push_back(Operands[In]);
8245     if (EdgeMask)
8246       OperandsWithMask.push_back(EdgeMask);
8247   }
8248   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8249 }
8250 
8251 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8252                                                    ArrayRef<VPValue *> Operands,
8253                                                    VFRange &Range) const {
8254 
8255   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8256       [this, CI](ElementCount VF) {
8257         return CM.isScalarWithPredication(CI, VF);
8258       },
8259       Range);
8260 
8261   if (IsPredicated)
8262     return nullptr;
8263 
8264   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8265   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8266              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8267              ID == Intrinsic::pseudoprobe ||
8268              ID == Intrinsic::experimental_noalias_scope_decl))
8269     return nullptr;
8270 
8271   auto willWiden = [&](ElementCount VF) -> bool {
8272     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8273     // The following case may be scalarized depending on the VF.
8274     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8275     // version of the instruction.
8276     // Is it beneficial to perform intrinsic call compared to lib call?
8277     bool NeedToScalarize = false;
8278     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8279     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8280     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8281     return UseVectorIntrinsic || !NeedToScalarize;
8282   };
8283 
8284   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8285     return nullptr;
8286 
8287   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8288   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8289 }
8290 
8291 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8292   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8293          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8294   // Instruction should be widened, unless it is scalar after vectorization,
8295   // scalarization is profitable or it is predicated.
8296   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8297     return CM.isScalarAfterVectorization(I, VF) ||
8298            CM.isProfitableToScalarize(I, VF) ||
8299            CM.isScalarWithPredication(I, VF);
8300   };
8301   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8302                                                              Range);
8303 }
8304 
8305 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8306                                            ArrayRef<VPValue *> Operands) const {
8307   auto IsVectorizableOpcode = [](unsigned Opcode) {
8308     switch (Opcode) {
8309     case Instruction::Add:
8310     case Instruction::And:
8311     case Instruction::AShr:
8312     case Instruction::BitCast:
8313     case Instruction::FAdd:
8314     case Instruction::FCmp:
8315     case Instruction::FDiv:
8316     case Instruction::FMul:
8317     case Instruction::FNeg:
8318     case Instruction::FPExt:
8319     case Instruction::FPToSI:
8320     case Instruction::FPToUI:
8321     case Instruction::FPTrunc:
8322     case Instruction::FRem:
8323     case Instruction::FSub:
8324     case Instruction::ICmp:
8325     case Instruction::IntToPtr:
8326     case Instruction::LShr:
8327     case Instruction::Mul:
8328     case Instruction::Or:
8329     case Instruction::PtrToInt:
8330     case Instruction::SDiv:
8331     case Instruction::Select:
8332     case Instruction::SExt:
8333     case Instruction::Shl:
8334     case Instruction::SIToFP:
8335     case Instruction::SRem:
8336     case Instruction::Sub:
8337     case Instruction::Trunc:
8338     case Instruction::UDiv:
8339     case Instruction::UIToFP:
8340     case Instruction::URem:
8341     case Instruction::Xor:
8342     case Instruction::ZExt:
8343     case Instruction::Freeze:
8344       return true;
8345     }
8346     return false;
8347   };
8348 
8349   if (!IsVectorizableOpcode(I->getOpcode()))
8350     return nullptr;
8351 
8352   // Success: widen this instruction.
8353   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8354 }
8355 
8356 void VPRecipeBuilder::fixHeaderPhis() {
8357   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8358   for (VPHeaderPHIRecipe *R : PhisToFix) {
8359     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8360     VPRecipeBase *IncR =
8361         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8362     R->addOperand(IncR->getVPSingleValue());
8363   }
8364 }
8365 
8366 VPBasicBlock *VPRecipeBuilder::handleReplication(
8367     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8368     VPlanPtr &Plan) {
8369   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8370       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8371       Range);
8372 
8373   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8374       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF); },
8375       Range);
8376 
8377   // Even if the instruction is not marked as uniform, there are certain
8378   // intrinsic calls that can be effectively treated as such, so we check for
8379   // them here. Conservatively, we only do this for scalable vectors, since
8380   // for fixed-width VFs we can always fall back on full scalarization.
8381   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8382     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8383     case Intrinsic::assume:
8384     case Intrinsic::lifetime_start:
8385     case Intrinsic::lifetime_end:
8386       // For scalable vectors if one of the operands is variant then we still
8387       // want to mark as uniform, which will generate one instruction for just
8388       // the first lane of the vector. We can't scalarize the call in the same
8389       // way as for fixed-width vectors because we don't know how many lanes
8390       // there are.
8391       //
8392       // The reasons for doing it this way for scalable vectors are:
8393       //   1. For the assume intrinsic generating the instruction for the first
8394       //      lane is still be better than not generating any at all. For
8395       //      example, the input may be a splat across all lanes.
8396       //   2. For the lifetime start/end intrinsics the pointer operand only
8397       //      does anything useful when the input comes from a stack object,
8398       //      which suggests it should always be uniform. For non-stack objects
8399       //      the effect is to poison the object, which still allows us to
8400       //      remove the call.
8401       IsUniform = true;
8402       break;
8403     default:
8404       break;
8405     }
8406   }
8407 
8408   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8409                                        IsUniform, IsPredicated);
8410 
8411   // Find if I uses a predicated instruction. If so, it will use its scalar
8412   // value. Avoid hoisting the insert-element which packs the scalar value into
8413   // a vector value, as that happens iff all users use the vector value.
8414   for (VPValue *Op : Recipe->operands()) {
8415     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8416     if (!PredR)
8417       continue;
8418     auto *RepR =
8419         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8420     assert(RepR->isPredicated() &&
8421            "expected Replicate recipe to be predicated");
8422     RepR->setAlsoPack(false);
8423   }
8424 
8425   // Finalize the recipe for Instr, first if it is not predicated.
8426   if (!IsPredicated) {
8427     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8428     setRecipe(I, Recipe);
8429     Plan->addVPValue(I, Recipe);
8430     VPBB->appendRecipe(Recipe);
8431     return VPBB;
8432   }
8433   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8434 
8435   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8436   assert(SingleSucc && "VPBB must have a single successor when handling "
8437                        "predicated replication.");
8438   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8439   // Record predicated instructions for above packing optimizations.
8440   VPBlockBase *Region = createReplicateRegion(Recipe, Plan);
8441   VPBlockUtils::insertBlockAfter(Region, VPBB);
8442   auto *RegSucc = new VPBasicBlock();
8443   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8444   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8445   return RegSucc;
8446 }
8447 
8448 VPRegionBlock *
8449 VPRecipeBuilder::createReplicateRegion(VPReplicateRecipe *PredRecipe,
8450                                        VPlanPtr &Plan) {
8451   Instruction *Instr = PredRecipe->getUnderlyingInstr();
8452   // Instructions marked for predication are replicated and placed under an
8453   // if-then construct to prevent side-effects.
8454   // Generate recipes to compute the block mask for this region.
8455   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8456 
8457   // Build the triangular if-then region.
8458   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8459   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8460   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8461   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8462   auto *PHIRecipe = Instr->getType()->isVoidTy()
8463                         ? nullptr
8464                         : new VPPredInstPHIRecipe(PredRecipe);
8465   if (PHIRecipe) {
8466     setRecipe(Instr, PHIRecipe);
8467     Plan->addVPValue(Instr, PHIRecipe);
8468   } else {
8469     setRecipe(Instr, PredRecipe);
8470     Plan->addVPValue(Instr, PredRecipe);
8471   }
8472 
8473   auto *Exiting = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8474   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8475   VPRegionBlock *Region = new VPRegionBlock(Entry, Exiting, RegionName, true);
8476 
8477   // Note: first set Entry as region entry and then connect successors starting
8478   // from it in order, to propagate the "parent" of each VPBasicBlock.
8479   VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
8480   VPBlockUtils::connectBlocks(Pred, Exiting);
8481 
8482   return Region;
8483 }
8484 
8485 VPRecipeOrVPValueTy
8486 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8487                                         ArrayRef<VPValue *> Operands,
8488                                         VFRange &Range, VPlanPtr &Plan) {
8489   // First, check for specific widening recipes that deal with inductions, Phi
8490   // nodes, calls and memory operations.
8491   VPRecipeBase *Recipe;
8492   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8493     if (Phi->getParent() != OrigLoop->getHeader())
8494       return tryToBlend(Phi, Operands, Plan);
8495     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, *Plan, Range)))
8496       return toVPRecipeResult(Recipe);
8497 
8498     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8499     assert((Legal->isReductionVariable(Phi) ||
8500             Legal->isFirstOrderRecurrence(Phi)) &&
8501            "can only widen reductions and first-order recurrences here");
8502     VPValue *StartV = Operands[0];
8503     if (Legal->isReductionVariable(Phi)) {
8504       const RecurrenceDescriptor &RdxDesc =
8505           Legal->getReductionVars().find(Phi)->second;
8506       assert(RdxDesc.getRecurrenceStartValue() ==
8507              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8508       PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8509                                            CM.isInLoopReduction(Phi),
8510                                            CM.useOrderedReductions(RdxDesc));
8511     } else {
8512       PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8513     }
8514 
8515     // Record the incoming value from the backedge, so we can add the incoming
8516     // value from the backedge after all recipes have been created.
8517     recordRecipeOf(cast<Instruction>(
8518         Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8519     PhisToFix.push_back(PhiRecipe);
8520     return toVPRecipeResult(PhiRecipe);
8521   }
8522 
8523   if (isa<TruncInst>(Instr) &&
8524       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8525                                                Range, *Plan)))
8526     return toVPRecipeResult(Recipe);
8527 
8528   // All widen recipes below deal only with VF > 1.
8529   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8530           [&](ElementCount VF) { return VF.isScalar(); }, Range))
8531     return nullptr;
8532 
8533   if (auto *CI = dyn_cast<CallInst>(Instr))
8534     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8535 
8536   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8537     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8538 
8539   if (!shouldWiden(Instr, Range))
8540     return nullptr;
8541 
8542   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8543     return toVPRecipeResult(new VPWidenGEPRecipe(
8544         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8545 
8546   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8547     bool InvariantCond =
8548         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8549     return toVPRecipeResult(new VPWidenSelectRecipe(
8550         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8551   }
8552 
8553   return toVPRecipeResult(tryToWiden(Instr, Operands));
8554 }
8555 
8556 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8557                                                         ElementCount MaxVF) {
8558   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8559 
8560   // Add assume instructions we need to drop to DeadInstructions, to prevent
8561   // them from being added to the VPlan.
8562   // TODO: We only need to drop assumes in blocks that get flattend. If the
8563   // control flow is preserved, we should keep them.
8564   SmallPtrSet<Instruction *, 4> DeadInstructions;
8565   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8566   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8567 
8568   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8569   // Dead instructions do not need sinking. Remove them from SinkAfter.
8570   for (Instruction *I : DeadInstructions)
8571     SinkAfter.erase(I);
8572 
8573   // Cannot sink instructions after dead instructions (there won't be any
8574   // recipes for them). Instead, find the first non-dead previous instruction.
8575   for (auto &P : Legal->getSinkAfter()) {
8576     Instruction *SinkTarget = P.second;
8577     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8578     (void)FirstInst;
8579     while (DeadInstructions.contains(SinkTarget)) {
8580       assert(
8581           SinkTarget != FirstInst &&
8582           "Must find a live instruction (at least the one feeding the "
8583           "first-order recurrence PHI) before reaching beginning of the block");
8584       SinkTarget = SinkTarget->getPrevNode();
8585       assert(SinkTarget != P.first &&
8586              "sink source equals target, no sinking required");
8587     }
8588     P.second = SinkTarget;
8589   }
8590 
8591   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8592   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8593     VFRange SubRange = {VF, MaxVFPlusOne};
8594     VPlans.push_back(
8595         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8596     VF = SubRange.End;
8597   }
8598 }
8599 
8600 // Add the necessary canonical IV and branch recipes required to control the
8601 // loop.
8602 static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
8603                                   bool HasNUW,
8604                                   bool UseLaneMaskForLoopControlFlow) {
8605   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8606   auto *StartV = Plan.getOrAddVPValue(StartIdx);
8607 
8608   // Add a VPCanonicalIVPHIRecipe starting at 0 to the header.
8609   auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
8610   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
8611   VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
8612   Header->insert(CanonicalIVPHI, Header->begin());
8613 
8614   // Add a CanonicalIVIncrement{NUW} VPInstruction to increment the scalar
8615   // IV by VF * UF.
8616   auto *CanonicalIVIncrement =
8617       new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
8618                                : VPInstruction::CanonicalIVIncrement,
8619                         {CanonicalIVPHI}, DL, "index.next");
8620   CanonicalIVPHI->addOperand(CanonicalIVIncrement);
8621 
8622   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
8623   EB->appendRecipe(CanonicalIVIncrement);
8624 
8625   if (UseLaneMaskForLoopControlFlow) {
8626     // Create the active lane mask instruction in the vplan preheader.
8627     VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
8628 
8629     // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
8630     // we have to take unrolling into account. Each part needs to start at
8631     //   Part * VF
8632     auto *CanonicalIVIncrementParts =
8633         new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementForPartNUW
8634                                  : VPInstruction::CanonicalIVIncrementForPart,
8635                           {StartV}, DL, "index.part.next");
8636     Preheader->appendRecipe(CanonicalIVIncrementParts);
8637 
8638     // Create the ActiveLaneMask instruction using the correct start values.
8639     VPValue *TC = Plan.getOrCreateTripCount();
8640     auto *EntryALM = new VPInstruction(VPInstruction::ActiveLaneMask,
8641                                        {CanonicalIVIncrementParts, TC}, DL,
8642                                        "active.lane.mask.entry");
8643     Preheader->appendRecipe(EntryALM);
8644 
8645     // Now create the ActiveLaneMaskPhi recipe in the main loop using the
8646     // preheader ActiveLaneMask instruction.
8647     auto *LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
8648     Header->insert(LaneMaskPhi, Header->getFirstNonPhi());
8649 
8650     // Create the active lane mask for the next iteration of the loop.
8651     CanonicalIVIncrementParts =
8652         new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementForPartNUW
8653                                  : VPInstruction::CanonicalIVIncrementForPart,
8654                           {CanonicalIVIncrement}, DL);
8655     EB->appendRecipe(CanonicalIVIncrementParts);
8656 
8657     auto *ALM = new VPInstruction(VPInstruction::ActiveLaneMask,
8658                                   {CanonicalIVIncrementParts, TC}, DL,
8659                                   "active.lane.mask.next");
8660     EB->appendRecipe(ALM);
8661     LaneMaskPhi->addOperand(ALM);
8662 
8663     // We have to invert the mask here because a true condition means jumping
8664     // to the exit block.
8665     auto *NotMask = new VPInstruction(VPInstruction::Not, ALM, DL);
8666     EB->appendRecipe(NotMask);
8667 
8668     VPInstruction *BranchBack =
8669         new VPInstruction(VPInstruction::BranchOnCond, {NotMask}, DL);
8670     EB->appendRecipe(BranchBack);
8671   } else {
8672     // Add the BranchOnCount VPInstruction to the latch.
8673     VPInstruction *BranchBack = new VPInstruction(
8674         VPInstruction::BranchOnCount,
8675         {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
8676     EB->appendRecipe(BranchBack);
8677   }
8678 }
8679 
8680 // Add exit values to \p Plan. VPLiveOuts are added for each LCSSA phi in the
8681 // original exit block.
8682 static void addUsersInExitBlock(VPBasicBlock *HeaderVPBB,
8683                                 VPBasicBlock *MiddleVPBB, Loop *OrigLoop,
8684                                 VPlan &Plan) {
8685   BasicBlock *ExitBB = OrigLoop->getUniqueExitBlock();
8686   BasicBlock *ExitingBB = OrigLoop->getExitingBlock();
8687   // Only handle single-exit loops with unique exit blocks for now.
8688   if (!ExitBB || !ExitBB->getSinglePredecessor() || !ExitingBB)
8689     return;
8690 
8691   // Introduce VPUsers modeling the exit values.
8692   for (PHINode &ExitPhi : ExitBB->phis()) {
8693     Value *IncomingValue =
8694         ExitPhi.getIncomingValueForBlock(ExitingBB);
8695     VPValue *V = Plan.getOrAddVPValue(IncomingValue, true);
8696     Plan.addLiveOut(&ExitPhi, V);
8697   }
8698 }
8699 
8700 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8701     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8702     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8703 
8704   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8705 
8706   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8707 
8708   // ---------------------------------------------------------------------------
8709   // Pre-construction: record ingredients whose recipes we'll need to further
8710   // process after constructing the initial VPlan.
8711   // ---------------------------------------------------------------------------
8712 
8713   // Mark instructions we'll need to sink later and their targets as
8714   // ingredients whose recipe we'll need to record.
8715   for (auto &Entry : SinkAfter) {
8716     RecipeBuilder.recordRecipeOf(Entry.first);
8717     RecipeBuilder.recordRecipeOf(Entry.second);
8718   }
8719   for (auto &Reduction : CM.getInLoopReductionChains()) {
8720     PHINode *Phi = Reduction.first;
8721     RecurKind Kind =
8722         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8723     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8724 
8725     RecipeBuilder.recordRecipeOf(Phi);
8726     for (auto &R : ReductionOperations) {
8727       RecipeBuilder.recordRecipeOf(R);
8728       // For min/max reductions, where we have a pair of icmp/select, we also
8729       // need to record the ICmp recipe, so it can be removed later.
8730       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
8731              "Only min/max recurrences allowed for inloop reductions");
8732       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8733         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8734     }
8735   }
8736 
8737   // For each interleave group which is relevant for this (possibly trimmed)
8738   // Range, add it to the set of groups to be later applied to the VPlan and add
8739   // placeholders for its members' Recipes which we'll be replacing with a
8740   // single VPInterleaveRecipe.
8741   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8742     auto applyIG = [IG, this](ElementCount VF) -> bool {
8743       return (VF.isVector() && // Query is illegal for VF == 1
8744               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8745                   LoopVectorizationCostModel::CM_Interleave);
8746     };
8747     if (!getDecisionAndClampRange(applyIG, Range))
8748       continue;
8749     InterleaveGroups.insert(IG);
8750     for (unsigned i = 0; i < IG->getFactor(); i++)
8751       if (Instruction *Member = IG->getMember(i))
8752         RecipeBuilder.recordRecipeOf(Member);
8753   };
8754 
8755   // ---------------------------------------------------------------------------
8756   // Build initial VPlan: Scan the body of the loop in a topological order to
8757   // visit each basic block after having visited its predecessor basic blocks.
8758   // ---------------------------------------------------------------------------
8759 
8760   // Create initial VPlan skeleton, starting with a block for the pre-header,
8761   // followed by a region for the vector loop, followed by the middle block. The
8762   // skeleton vector loop region contains a header and latch block.
8763   VPBasicBlock *Preheader = new VPBasicBlock("vector.ph");
8764   auto Plan = std::make_unique<VPlan>(Preheader);
8765 
8766   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
8767   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
8768   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
8769   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
8770   VPBlockUtils::insertBlockAfter(TopRegion, Preheader);
8771   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
8772   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
8773 
8774   Instruction *DLInst =
8775       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
8776   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
8777                         DLInst ? DLInst->getDebugLoc() : DebugLoc(),
8778                         !CM.foldTailByMasking(),
8779                         CM.useActiveLaneMaskForControlFlow());
8780 
8781   // Scan the body of the loop in a topological order to visit each basic block
8782   // after having visited its predecessor basic blocks.
8783   LoopBlocksDFS DFS(OrigLoop);
8784   DFS.perform(LI);
8785 
8786   VPBasicBlock *VPBB = HeaderVPBB;
8787   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
8788   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8789     // Relevant instructions from basic block BB will be grouped into VPRecipe
8790     // ingredients and fill a new VPBasicBlock.
8791     unsigned VPBBsForBB = 0;
8792     if (VPBB != HeaderVPBB)
8793       VPBB->setName(BB->getName());
8794     Builder.setInsertPoint(VPBB);
8795 
8796     // Introduce each ingredient into VPlan.
8797     // TODO: Model and preserve debug intrinsics in VPlan.
8798     for (Instruction &I : BB->instructionsWithoutDebug()) {
8799       Instruction *Instr = &I;
8800 
8801       // First filter out irrelevant instructions, to ensure no recipes are
8802       // built for them.
8803       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8804         continue;
8805 
8806       SmallVector<VPValue *, 4> Operands;
8807       auto *Phi = dyn_cast<PHINode>(Instr);
8808       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8809         Operands.push_back(Plan->getOrAddVPValue(
8810             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8811       } else {
8812         auto OpRange = Plan->mapToVPValues(Instr->operands());
8813         Operands = {OpRange.begin(), OpRange.end()};
8814       }
8815 
8816       // Invariant stores inside loop will be deleted and a single store
8817       // with the final reduction value will be added to the exit block
8818       StoreInst *SI;
8819       if ((SI = dyn_cast<StoreInst>(&I)) &&
8820           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
8821         continue;
8822 
8823       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8824               Instr, Operands, Range, Plan)) {
8825         // If Instr can be simplified to an existing VPValue, use it.
8826         if (RecipeOrValue.is<VPValue *>()) {
8827           auto *VPV = RecipeOrValue.get<VPValue *>();
8828           Plan->addVPValue(Instr, VPV);
8829           // If the re-used value is a recipe, register the recipe for the
8830           // instruction, in case the recipe for Instr needs to be recorded.
8831           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
8832             RecipeBuilder.setRecipe(Instr, R);
8833           continue;
8834         }
8835         // Otherwise, add the new recipe.
8836         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8837         for (auto *Def : Recipe->definedValues()) {
8838           auto *UV = Def->getUnderlyingValue();
8839           Plan->addVPValue(UV, Def);
8840         }
8841 
8842         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
8843             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
8844           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
8845           // of the header block. That can happen for truncates of induction
8846           // variables. Those recipes are moved to the phi section of the header
8847           // block after applying SinkAfter, which relies on the original
8848           // position of the trunc.
8849           assert(isa<TruncInst>(Instr));
8850           InductionsToMove.push_back(
8851               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
8852         }
8853         RecipeBuilder.setRecipe(Instr, Recipe);
8854         VPBB->appendRecipe(Recipe);
8855         continue;
8856       }
8857 
8858       // Otherwise, if all widening options failed, Instruction is to be
8859       // replicated. This may create a successor for VPBB.
8860       VPBasicBlock *NextVPBB =
8861           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8862       if (NextVPBB != VPBB) {
8863         VPBB = NextVPBB;
8864         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8865                                     : "");
8866       }
8867     }
8868 
8869     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
8870     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
8871   }
8872 
8873   HeaderVPBB->setName("vector.body");
8874 
8875   // Fold the last, empty block into its predecessor.
8876   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
8877   assert(VPBB && "expected to fold last (empty) block");
8878   // After here, VPBB should not be used.
8879   VPBB = nullptr;
8880 
8881   addUsersInExitBlock(HeaderVPBB, MiddleVPBB, OrigLoop, *Plan);
8882 
8883   assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8884          !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8885          "entry block must be set to a VPRegionBlock having a non-empty entry "
8886          "VPBasicBlock");
8887   RecipeBuilder.fixHeaderPhis();
8888 
8889   // ---------------------------------------------------------------------------
8890   // Transform initial VPlan: Apply previously taken decisions, in order, to
8891   // bring the VPlan to its final state.
8892   // ---------------------------------------------------------------------------
8893 
8894   // Apply Sink-After legal constraints.
8895   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
8896     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
8897     if (Region && Region->isReplicator()) {
8898       assert(Region->getNumSuccessors() == 1 &&
8899              Region->getNumPredecessors() == 1 && "Expected SESE region!");
8900       assert(R->getParent()->size() == 1 &&
8901              "A recipe in an original replicator region must be the only "
8902              "recipe in its block");
8903       return Region;
8904     }
8905     return nullptr;
8906   };
8907   for (auto &Entry : SinkAfter) {
8908     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8909     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8910 
8911     auto *TargetRegion = GetReplicateRegion(Target);
8912     auto *SinkRegion = GetReplicateRegion(Sink);
8913     if (!SinkRegion) {
8914       // If the sink source is not a replicate region, sink the recipe directly.
8915       if (TargetRegion) {
8916         // The target is in a replication region, make sure to move Sink to
8917         // the block after it, not into the replication region itself.
8918         VPBasicBlock *NextBlock =
8919             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
8920         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8921       } else
8922         Sink->moveAfter(Target);
8923       continue;
8924     }
8925 
8926     // The sink source is in a replicate region. Unhook the region from the CFG.
8927     auto *SinkPred = SinkRegion->getSinglePredecessor();
8928     auto *SinkSucc = SinkRegion->getSingleSuccessor();
8929     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
8930     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
8931     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
8932 
8933     if (TargetRegion) {
8934       // The target recipe is also in a replicate region, move the sink region
8935       // after the target region.
8936       auto *TargetSucc = TargetRegion->getSingleSuccessor();
8937       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
8938       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
8939       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
8940     } else {
8941       // The sink source is in a replicate region, we need to move the whole
8942       // replicate region, which should only contain a single recipe in the
8943       // main block.
8944       auto *SplitBlock =
8945           Target->getParent()->splitAt(std::next(Target->getIterator()));
8946 
8947       auto *SplitPred = SplitBlock->getSinglePredecessor();
8948 
8949       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
8950       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
8951       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
8952     }
8953   }
8954 
8955   VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
8956   VPlanTransforms::removeRedundantInductionCasts(*Plan);
8957 
8958   // Now that sink-after is done, move induction recipes for optimized truncates
8959   // to the phi section of the header block.
8960   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
8961     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8962 
8963   // Adjust the recipes for any inloop reductions.
8964   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExiting()), Plan,
8965                              RecipeBuilder, Range.Start);
8966 
8967   // Introduce a recipe to combine the incoming and previous values of a
8968   // first-order recurrence.
8969   for (VPRecipeBase &R :
8970        Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8971     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
8972     if (!RecurPhi)
8973       continue;
8974 
8975     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
8976     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
8977     auto *Region = GetReplicateRegion(PrevRecipe);
8978     if (Region)
8979       InsertBlock = dyn_cast<VPBasicBlock>(Region->getSingleSuccessor());
8980     if (!InsertBlock) {
8981       InsertBlock = new VPBasicBlock(Region->getName() + ".succ");
8982       VPBlockUtils::insertBlockAfter(InsertBlock, Region);
8983     }
8984     if (Region || PrevRecipe->isPhi())
8985       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
8986     else
8987       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
8988 
8989     auto *RecurSplice = cast<VPInstruction>(
8990         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
8991                              {RecurPhi, RecurPhi->getBackedgeValue()}));
8992 
8993     RecurPhi->replaceAllUsesWith(RecurSplice);
8994     // Set the first operand of RecurSplice to RecurPhi again, after replacing
8995     // all users.
8996     RecurSplice->setOperand(0, RecurPhi);
8997   }
8998 
8999   // Interleave memory: for each Interleave Group we marked earlier as relevant
9000   // for this VPlan, replace the Recipes widening its memory instructions with a
9001   // single VPInterleaveRecipe at its insertion point.
9002   for (auto IG : InterleaveGroups) {
9003     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9004         RecipeBuilder.getRecipe(IG->getInsertPos()));
9005     SmallVector<VPValue *, 4> StoredValues;
9006     for (unsigned i = 0; i < IG->getFactor(); ++i)
9007       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9008         auto *StoreR =
9009             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9010         StoredValues.push_back(StoreR->getStoredValue());
9011       }
9012 
9013     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9014                                         Recipe->getMask());
9015     VPIG->insertBefore(Recipe);
9016     unsigned J = 0;
9017     for (unsigned i = 0; i < IG->getFactor(); ++i)
9018       if (Instruction *Member = IG->getMember(i)) {
9019         if (!Member->getType()->isVoidTy()) {
9020           VPValue *OriginalV = Plan->getVPValue(Member);
9021           Plan->removeVPValueFor(Member);
9022           Plan->addVPValue(Member, VPIG->getVPValue(J));
9023           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9024           J++;
9025         }
9026         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9027       }
9028   }
9029 
9030   std::string PlanName;
9031   raw_string_ostream RSO(PlanName);
9032   ElementCount VF = Range.Start;
9033   Plan->addVF(VF);
9034   RSO << "Initial VPlan for VF={" << VF;
9035   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9036     Plan->addVF(VF);
9037     RSO << "," << VF;
9038   }
9039   RSO << "},UF>=1";
9040   RSO.flush();
9041   Plan->setName(PlanName);
9042 
9043   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9044   // in ways that accessing values using original IR values is incorrect.
9045   Plan->disableValue2VPValue();
9046 
9047   VPlanTransforms::optimizeInductions(*Plan, *PSE.getSE());
9048   VPlanTransforms::sinkScalarOperands(*Plan);
9049   VPlanTransforms::removeDeadRecipes(*Plan);
9050   VPlanTransforms::mergeReplicateRegions(*Plan);
9051   VPlanTransforms::removeRedundantExpandSCEVRecipes(*Plan);
9052 
9053   // Fold Exit block into its predecessor if possible.
9054   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9055   // VPBasicBlock as exit.
9056   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExiting());
9057 
9058   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9059   return Plan;
9060 }
9061 
9062 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9063   // Outer loop handling: They may require CFG and instruction level
9064   // transformations before even evaluating whether vectorization is profitable.
9065   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9066   // the vectorization pipeline.
9067   assert(!OrigLoop->isInnermost());
9068   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9069 
9070   // Create new empty VPlan
9071   auto Plan = std::make_unique<VPlan>();
9072 
9073   // Build hierarchical CFG
9074   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9075   HCFGBuilder.buildHierarchicalCFG();
9076 
9077   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9078        VF *= 2)
9079     Plan->addVF(VF);
9080 
9081   SmallPtrSet<Instruction *, 1> DeadInstructions;
9082   VPlanTransforms::VPInstructionsToVPRecipes(
9083       OrigLoop, Plan,
9084       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9085       DeadInstructions, *PSE.getSE());
9086 
9087   // Remove the existing terminator of the exiting block of the top-most region.
9088   // A BranchOnCount will be added instead when adding the canonical IV recipes.
9089   auto *Term =
9090       Plan->getVectorLoopRegion()->getExitingBasicBlock()->getTerminator();
9091   Term->eraseFromParent();
9092 
9093   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
9094                         true, CM.useActiveLaneMaskForControlFlow());
9095   return Plan;
9096 }
9097 
9098 // Adjust the recipes for reductions. For in-loop reductions the chain of
9099 // instructions leading from the loop exit instr to the phi need to be converted
9100 // to reductions, with one operand being vector and the other being the scalar
9101 // reduction chain. For other reductions, a select is introduced between the phi
9102 // and live-out recipes when folding the tail.
9103 void LoopVectorizationPlanner::adjustRecipesForReductions(
9104     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9105     ElementCount MinVF) {
9106   for (auto &Reduction : CM.getInLoopReductionChains()) {
9107     PHINode *Phi = Reduction.first;
9108     const RecurrenceDescriptor &RdxDesc =
9109         Legal->getReductionVars().find(Phi)->second;
9110     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9111 
9112     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9113       continue;
9114 
9115     // ReductionOperations are orders top-down from the phi's use to the
9116     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9117     // which of the two operands will remain scalar and which will be reduced.
9118     // For minmax the chain will be the select instructions.
9119     Instruction *Chain = Phi;
9120     for (Instruction *R : ReductionOperations) {
9121       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9122       RecurKind Kind = RdxDesc.getRecurrenceKind();
9123 
9124       VPValue *ChainOp = Plan->getVPValue(Chain);
9125       unsigned FirstOpId;
9126       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9127              "Only min/max recurrences allowed for inloop reductions");
9128       // Recognize a call to the llvm.fmuladd intrinsic.
9129       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9130       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9131              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9132       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9133         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9134                "Expected to replace a VPWidenSelectSC");
9135         FirstOpId = 1;
9136       } else {
9137         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9138                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9139                "Expected to replace a VPWidenSC");
9140         FirstOpId = 0;
9141       }
9142       unsigned VecOpId =
9143           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9144       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9145 
9146       auto *CondOp = CM.blockNeedsPredicationForAnyReason(R->getParent())
9147                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9148                          : nullptr;
9149 
9150       if (IsFMulAdd) {
9151         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9152         // need to create an fmul recipe to use as the vector operand for the
9153         // fadd reduction.
9154         VPInstruction *FMulRecipe = new VPInstruction(
9155             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9156         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9157         WidenRecipe->getParent()->insert(FMulRecipe,
9158                                          WidenRecipe->getIterator());
9159         VecOp = FMulRecipe;
9160       }
9161       VPReductionRecipe *RedRecipe =
9162           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9163       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9164       Plan->removeVPValueFor(R);
9165       Plan->addVPValue(R, RedRecipe);
9166       // Append the recipe to the end of the VPBasicBlock because we need to
9167       // ensure that it comes after all of it's inputs, including CondOp.
9168       WidenRecipe->getParent()->appendRecipe(RedRecipe);
9169       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9170       WidenRecipe->eraseFromParent();
9171 
9172       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9173         VPRecipeBase *CompareRecipe =
9174             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9175         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9176                "Expected to replace a VPWidenSC");
9177         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9178                "Expected no remaining users");
9179         CompareRecipe->eraseFromParent();
9180       }
9181       Chain = R;
9182     }
9183   }
9184 
9185   // If tail is folded by masking, introduce selects between the phi
9186   // and the live-out instruction of each reduction, at the beginning of the
9187   // dedicated latch block.
9188   if (CM.foldTailByMasking()) {
9189     Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
9190     for (VPRecipeBase &R :
9191          Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9192       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9193       if (!PhiR || PhiR->isInLoop())
9194         continue;
9195       VPValue *Cond =
9196           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9197       VPValue *Red = PhiR->getBackedgeValue();
9198       assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
9199              "reduction recipe must be defined before latch");
9200       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9201     }
9202   }
9203 }
9204 
9205 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9206 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9207                                VPSlotTracker &SlotTracker) const {
9208   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9209   IG->getInsertPos()->printAsOperand(O, false);
9210   O << ", ";
9211   getAddr()->printAsOperand(O, SlotTracker);
9212   VPValue *Mask = getMask();
9213   if (Mask) {
9214     O << ", ";
9215     Mask->printAsOperand(O, SlotTracker);
9216   }
9217 
9218   unsigned OpIdx = 0;
9219   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9220     if (!IG->getMember(i))
9221       continue;
9222     if (getNumStoreOperands() > 0) {
9223       O << "\n" << Indent << "  store ";
9224       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9225       O << " to index " << i;
9226     } else {
9227       O << "\n" << Indent << "  ";
9228       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9229       O << " = load from index " << i;
9230     }
9231     ++OpIdx;
9232   }
9233 }
9234 #endif
9235 
9236 void VPWidenCallRecipe::execute(VPTransformState &State) {
9237   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9238                                   *this, State);
9239 }
9240 
9241 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9242   assert(!State.Instance && "Int or FP induction being replicated.");
9243 
9244   Value *Start = getStartValue()->getLiveInIRValue();
9245   const InductionDescriptor &ID = getInductionDescriptor();
9246   TruncInst *Trunc = getTruncInst();
9247   IRBuilderBase &Builder = State.Builder;
9248   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
9249   assert(State.VF.isVector() && "must have vector VF");
9250 
9251   // The value from the original loop to which we are mapping the new induction
9252   // variable.
9253   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
9254 
9255   // Fast-math-flags propagate from the original induction instruction.
9256   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9257   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
9258     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
9259 
9260   // Now do the actual transformations, and start with fetching the step value.
9261   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9262 
9263   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
9264          "Expected either an induction phi-node or a truncate of it!");
9265 
9266   // Construct the initial value of the vector IV in the vector loop preheader
9267   auto CurrIP = Builder.saveIP();
9268   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9269   Builder.SetInsertPoint(VectorPH->getTerminator());
9270   if (isa<TruncInst>(EntryVal)) {
9271     assert(Start->getType()->isIntegerTy() &&
9272            "Truncation requires an integer type");
9273     auto *TruncType = cast<IntegerType>(EntryVal->getType());
9274     Step = Builder.CreateTrunc(Step, TruncType);
9275     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
9276   }
9277 
9278   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
9279   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
9280   Value *SteppedStart = getStepVector(
9281       SplatStart, Zero, Step, ID.getInductionOpcode(), State.VF, State.Builder);
9282 
9283   // We create vector phi nodes for both integer and floating-point induction
9284   // variables. Here, we determine the kind of arithmetic we will perform.
9285   Instruction::BinaryOps AddOp;
9286   Instruction::BinaryOps MulOp;
9287   if (Step->getType()->isIntegerTy()) {
9288     AddOp = Instruction::Add;
9289     MulOp = Instruction::Mul;
9290   } else {
9291     AddOp = ID.getInductionOpcode();
9292     MulOp = Instruction::FMul;
9293   }
9294 
9295   // Multiply the vectorization factor by the step using integer or
9296   // floating-point arithmetic as appropriate.
9297   Type *StepType = Step->getType();
9298   Value *RuntimeVF;
9299   if (Step->getType()->isFloatingPointTy())
9300     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
9301   else
9302     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
9303   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
9304 
9305   // Create a vector splat to use in the induction update.
9306   //
9307   // FIXME: If the step is non-constant, we create the vector splat with
9308   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
9309   //        handle a constant vector splat.
9310   Value *SplatVF = isa<Constant>(Mul)
9311                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
9312                        : Builder.CreateVectorSplat(State.VF, Mul);
9313   Builder.restoreIP(CurrIP);
9314 
9315   // We may need to add the step a number of times, depending on the unroll
9316   // factor. The last of those goes into the PHI.
9317   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
9318                                     &*State.CFG.PrevBB->getFirstInsertionPt());
9319   VecInd->setDebugLoc(EntryVal->getDebugLoc());
9320   Instruction *LastInduction = VecInd;
9321   for (unsigned Part = 0; Part < State.UF; ++Part) {
9322     State.set(this, LastInduction, Part);
9323 
9324     if (isa<TruncInst>(EntryVal))
9325       State.addMetadata(LastInduction, EntryVal);
9326 
9327     LastInduction = cast<Instruction>(
9328         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
9329     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
9330   }
9331 
9332   LastInduction->setName("vec.ind.next");
9333   VecInd->addIncoming(SteppedStart, VectorPH);
9334   // Add induction update using an incorrect block temporarily. The phi node
9335   // will be fixed after VPlan execution. Note that at this point the latch
9336   // block cannot be used, as it does not exist yet.
9337   // TODO: Model increment value in VPlan, by turning the recipe into a
9338   // multi-def and a subclass of VPHeaderPHIRecipe.
9339   VecInd->addIncoming(LastInduction, VectorPH);
9340 }
9341 
9342 void VPWidenPointerInductionRecipe::execute(VPTransformState &State) {
9343   assert(IndDesc.getKind() == InductionDescriptor::IK_PtrInduction &&
9344          "Not a pointer induction according to InductionDescriptor!");
9345   assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
9346          "Unexpected type.");
9347 
9348   auto *IVR = getParent()->getPlan()->getCanonicalIV();
9349   PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
9350 
9351   if (onlyScalarsGenerated(State.VF)) {
9352     // This is the normalized GEP that starts counting at zero.
9353     Value *PtrInd = State.Builder.CreateSExtOrTrunc(
9354         CanonicalIV, IndDesc.getStep()->getType());
9355     // Determine the number of scalars we need to generate for each unroll
9356     // iteration. If the instruction is uniform, we only need to generate the
9357     // first lane. Otherwise, we generate all VF values.
9358     bool IsUniform = vputils::onlyFirstLaneUsed(this);
9359     assert((IsUniform || !State.VF.isScalable()) &&
9360            "Cannot scalarize a scalable VF");
9361     unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
9362 
9363     for (unsigned Part = 0; Part < State.UF; ++Part) {
9364       Value *PartStart =
9365           createStepForVF(State.Builder, PtrInd->getType(), State.VF, Part);
9366 
9367       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
9368         Value *Idx = State.Builder.CreateAdd(
9369             PartStart, ConstantInt::get(PtrInd->getType(), Lane));
9370         Value *GlobalIdx = State.Builder.CreateAdd(PtrInd, Idx);
9371 
9372         Value *Step = CreateStepValue(IndDesc.getStep(), SE,
9373                                       State.CFG.PrevBB->getTerminator());
9374         Value *SclrGep = emitTransformedIndex(
9375             State.Builder, GlobalIdx, IndDesc.getStartValue(), Step, IndDesc);
9376         SclrGep->setName("next.gep");
9377         State.set(this, SclrGep, VPIteration(Part, Lane));
9378       }
9379     }
9380     return;
9381   }
9382 
9383   assert(isa<SCEVConstant>(IndDesc.getStep()) &&
9384          "Induction step not a SCEV constant!");
9385   Type *PhiType = IndDesc.getStep()->getType();
9386 
9387   // Build a pointer phi
9388   Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
9389   Type *ScStValueType = ScalarStartValue->getType();
9390   PHINode *NewPointerPhi =
9391       PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
9392 
9393   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9394   NewPointerPhi->addIncoming(ScalarStartValue, VectorPH);
9395 
9396   // A pointer induction, performed by using a gep
9397   const DataLayout &DL = NewPointerPhi->getModule()->getDataLayout();
9398   Instruction *InductionLoc = &*State.Builder.GetInsertPoint();
9399 
9400   const SCEV *ScalarStep = IndDesc.getStep();
9401   SCEVExpander Exp(SE, DL, "induction");
9402   Value *ScalarStepValue = Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
9403   Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
9404   Value *NumUnrolledElems =
9405       State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
9406   Value *InductionGEP = GetElementPtrInst::Create(
9407       IndDesc.getElementType(), NewPointerPhi,
9408       State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
9409       InductionLoc);
9410   // Add induction update using an incorrect block temporarily. The phi node
9411   // will be fixed after VPlan execution. Note that at this point the latch
9412   // block cannot be used, as it does not exist yet.
9413   // TODO: Model increment value in VPlan, by turning the recipe into a
9414   // multi-def and a subclass of VPHeaderPHIRecipe.
9415   NewPointerPhi->addIncoming(InductionGEP, VectorPH);
9416 
9417   // Create UF many actual address geps that use the pointer
9418   // phi as base and a vectorized version of the step value
9419   // (<step*0, ..., step*N>) as offset.
9420   for (unsigned Part = 0; Part < State.UF; ++Part) {
9421     Type *VecPhiType = VectorType::get(PhiType, State.VF);
9422     Value *StartOffsetScalar =
9423         State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
9424     Value *StartOffset =
9425         State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
9426     // Create a vector of consecutive numbers from zero to VF.
9427     StartOffset = State.Builder.CreateAdd(
9428         StartOffset, State.Builder.CreateStepVector(VecPhiType));
9429 
9430     Value *GEP = State.Builder.CreateGEP(
9431         IndDesc.getElementType(), NewPointerPhi,
9432         State.Builder.CreateMul(
9433             StartOffset,
9434             State.Builder.CreateVectorSplat(State.VF, ScalarStepValue),
9435             "vector.gep"));
9436     State.set(this, GEP, Part);
9437   }
9438 }
9439 
9440 void VPScalarIVStepsRecipe::execute(VPTransformState &State) {
9441   assert(!State.Instance && "VPScalarIVStepsRecipe being replicated.");
9442 
9443   // Fast-math-flags propagate from the original induction instruction.
9444   IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9445   if (IndDesc.getInductionBinOp() &&
9446       isa<FPMathOperator>(IndDesc.getInductionBinOp()))
9447     State.Builder.setFastMathFlags(
9448         IndDesc.getInductionBinOp()->getFastMathFlags());
9449 
9450   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9451   auto CreateScalarIV = [&](Value *&Step) -> Value * {
9452     Value *ScalarIV = State.get(getCanonicalIV(), VPIteration(0, 0));
9453     auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
9454     if (!isCanonical() || CanonicalIV->getType() != Ty) {
9455       ScalarIV =
9456           Ty->isIntegerTy()
9457               ? State.Builder.CreateSExtOrTrunc(ScalarIV, Ty)
9458               : State.Builder.CreateCast(Instruction::SIToFP, ScalarIV, Ty);
9459       ScalarIV = emitTransformedIndex(State.Builder, ScalarIV,
9460                                       getStartValue()->getLiveInIRValue(), Step,
9461                                       IndDesc);
9462       ScalarIV->setName("offset.idx");
9463     }
9464     if (TruncToTy) {
9465       assert(Step->getType()->isIntegerTy() &&
9466              "Truncation requires an integer step");
9467       ScalarIV = State.Builder.CreateTrunc(ScalarIV, TruncToTy);
9468       Step = State.Builder.CreateTrunc(Step, TruncToTy);
9469     }
9470     return ScalarIV;
9471   };
9472 
9473   Value *ScalarIV = CreateScalarIV(Step);
9474   if (State.VF.isVector()) {
9475     buildScalarSteps(ScalarIV, Step, IndDesc, this, State);
9476     return;
9477   }
9478 
9479   for (unsigned Part = 0; Part < State.UF; ++Part) {
9480     assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
9481     Value *EntryPart;
9482     if (Step->getType()->isFloatingPointTy()) {
9483       Value *StartIdx =
9484           getRuntimeVFAsFloat(State.Builder, Step->getType(), State.VF * Part);
9485       // Floating-point operations inherit FMF via the builder's flags.
9486       Value *MulOp = State.Builder.CreateFMul(StartIdx, Step);
9487       EntryPart = State.Builder.CreateBinOp(IndDesc.getInductionOpcode(),
9488                                             ScalarIV, MulOp);
9489     } else {
9490       Value *StartIdx =
9491           getRuntimeVF(State.Builder, Step->getType(), State.VF * Part);
9492       EntryPart = State.Builder.CreateAdd(
9493           ScalarIV, State.Builder.CreateMul(StartIdx, Step), "induction");
9494     }
9495     State.set(this, EntryPart, Part);
9496   }
9497 }
9498 
9499 void VPInterleaveRecipe::execute(VPTransformState &State) {
9500   assert(!State.Instance && "Interleave group being replicated.");
9501   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9502                                       getStoredValues(), getMask());
9503 }
9504 
9505 void VPReductionRecipe::execute(VPTransformState &State) {
9506   assert(!State.Instance && "Reduction being replicated.");
9507   Value *PrevInChain = State.get(getChainOp(), 0);
9508   RecurKind Kind = RdxDesc->getRecurrenceKind();
9509   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9510   // Propagate the fast-math flags carried by the underlying instruction.
9511   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9512   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9513   for (unsigned Part = 0; Part < State.UF; ++Part) {
9514     Value *NewVecOp = State.get(getVecOp(), Part);
9515     if (VPValue *Cond = getCondOp()) {
9516       Value *NewCond = State.get(Cond, Part);
9517       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9518       Value *Iden = RdxDesc->getRecurrenceIdentity(
9519           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9520       Value *IdenVec =
9521           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9522       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9523       NewVecOp = Select;
9524     }
9525     Value *NewRed;
9526     Value *NextInChain;
9527     if (IsOrdered) {
9528       if (State.VF.isVector())
9529         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9530                                         PrevInChain);
9531       else
9532         NewRed = State.Builder.CreateBinOp(
9533             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9534             NewVecOp);
9535       PrevInChain = NewRed;
9536     } else {
9537       PrevInChain = State.get(getChainOp(), Part);
9538       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9539     }
9540     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9541       NextInChain =
9542           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9543                          NewRed, PrevInChain);
9544     } else if (IsOrdered)
9545       NextInChain = NewRed;
9546     else
9547       NextInChain = State.Builder.CreateBinOp(
9548           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9549           PrevInChain);
9550     State.set(this, NextInChain, Part);
9551   }
9552 }
9553 
9554 void VPReplicateRecipe::execute(VPTransformState &State) {
9555   if (State.Instance) { // Generate a single instance.
9556     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9557     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9558                                     IsPredicated, State);
9559     // Insert scalar instance packing it into a vector.
9560     if (AlsoPack && State.VF.isVector()) {
9561       // If we're constructing lane 0, initialize to start from poison.
9562       if (State.Instance->Lane.isFirstLane()) {
9563         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9564         Value *Poison = PoisonValue::get(
9565             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9566         State.set(this, Poison, State.Instance->Part);
9567       }
9568       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9569     }
9570     return;
9571   }
9572 
9573   // Generate scalar instances for all VF lanes of all UF parts, unless the
9574   // instruction is uniform inwhich case generate only the first lane for each
9575   // of the UF parts.
9576   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9577   assert((!State.VF.isScalable() || IsUniform) &&
9578          "Can't scalarize a scalable vector");
9579   for (unsigned Part = 0; Part < State.UF; ++Part)
9580     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9581       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9582                                       VPIteration(Part, Lane), IsPredicated,
9583                                       State);
9584 }
9585 
9586 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9587   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9588 
9589   // Attempt to issue a wide load.
9590   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9591   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9592 
9593   assert((LI || SI) && "Invalid Load/Store instruction");
9594   assert((!SI || StoredValue) && "No stored value provided for widened store");
9595   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9596 
9597   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9598 
9599   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9600   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9601   bool CreateGatherScatter = !Consecutive;
9602 
9603   auto &Builder = State.Builder;
9604   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9605   bool isMaskRequired = getMask();
9606   if (isMaskRequired)
9607     for (unsigned Part = 0; Part < State.UF; ++Part)
9608       BlockInMaskParts[Part] = State.get(getMask(), Part);
9609 
9610   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9611     // Calculate the pointer for the specific unroll-part.
9612     GetElementPtrInst *PartPtr = nullptr;
9613 
9614     bool InBounds = false;
9615     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9616       InBounds = gep->isInBounds();
9617     if (Reverse) {
9618       // If the address is consecutive but reversed, then the
9619       // wide store needs to start at the last vector element.
9620       // RunTimeVF =  VScale * VF.getKnownMinValue()
9621       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9622       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9623       // NumElt = -Part * RunTimeVF
9624       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9625       // LastLane = 1 - RunTimeVF
9626       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9627       PartPtr =
9628           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9629       PartPtr->setIsInBounds(InBounds);
9630       PartPtr = cast<GetElementPtrInst>(
9631           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9632       PartPtr->setIsInBounds(InBounds);
9633       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
9634         BlockInMaskParts[Part] =
9635             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
9636     } else {
9637       Value *Increment =
9638           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
9639       PartPtr = cast<GetElementPtrInst>(
9640           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
9641       PartPtr->setIsInBounds(InBounds);
9642     }
9643 
9644     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
9645     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
9646   };
9647 
9648   // Handle Stores:
9649   if (SI) {
9650     State.setDebugLocFromInst(SI);
9651 
9652     for (unsigned Part = 0; Part < State.UF; ++Part) {
9653       Instruction *NewSI = nullptr;
9654       Value *StoredVal = State.get(StoredValue, Part);
9655       if (CreateGatherScatter) {
9656         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9657         Value *VectorGep = State.get(getAddr(), Part);
9658         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
9659                                             MaskPart);
9660       } else {
9661         if (Reverse) {
9662           // If we store to reverse consecutive memory locations, then we need
9663           // to reverse the order of elements in the stored value.
9664           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
9665           // We don't want to update the value in the map as it might be used in
9666           // another expression. So don't call resetVectorValue(StoredVal).
9667         }
9668         auto *VecPtr =
9669             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9670         if (isMaskRequired)
9671           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
9672                                             BlockInMaskParts[Part]);
9673         else
9674           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
9675       }
9676       State.addMetadata(NewSI, SI);
9677     }
9678     return;
9679   }
9680 
9681   // Handle loads.
9682   assert(LI && "Must have a load instruction");
9683   State.setDebugLocFromInst(LI);
9684   for (unsigned Part = 0; Part < State.UF; ++Part) {
9685     Value *NewLI;
9686     if (CreateGatherScatter) {
9687       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9688       Value *VectorGep = State.get(getAddr(), Part);
9689       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
9690                                          nullptr, "wide.masked.gather");
9691       State.addMetadata(NewLI, LI);
9692     } else {
9693       auto *VecPtr =
9694           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9695       if (isMaskRequired)
9696         NewLI = Builder.CreateMaskedLoad(
9697             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
9698             PoisonValue::get(DataTy), "wide.masked.load");
9699       else
9700         NewLI =
9701             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
9702 
9703       // Add metadata to the load, but setVectorValue to the reverse shuffle.
9704       State.addMetadata(NewLI, LI);
9705       if (Reverse)
9706         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
9707     }
9708 
9709     State.set(getVPSingleValue(), NewLI, Part);
9710   }
9711 }
9712 
9713 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9714 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9715 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9716 // for predication.
9717 static ScalarEpilogueLowering getScalarEpilogueLowering(
9718     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9719     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9720     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9721     LoopVectorizationLegality &LVL) {
9722   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9723   // don't look at hints or options, and don't request a scalar epilogue.
9724   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9725   // LoopAccessInfo (due to code dependency and not being able to reliably get
9726   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9727   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9728   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9729   // back to the old way and vectorize with versioning when forced. See D81345.)
9730   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9731                                                       PGSOQueryType::IRPass) &&
9732                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9733     return CM_ScalarEpilogueNotAllowedOptSize;
9734 
9735   // 2) If set, obey the directives
9736   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9737     switch (PreferPredicateOverEpilogue) {
9738     case PreferPredicateTy::ScalarEpilogue:
9739       return CM_ScalarEpilogueAllowed;
9740     case PreferPredicateTy::PredicateElseScalarEpilogue:
9741       return CM_ScalarEpilogueNotNeededUsePredicate;
9742     case PreferPredicateTy::PredicateOrDontVectorize:
9743       return CM_ScalarEpilogueNotAllowedUsePredicate;
9744     };
9745   }
9746 
9747   // 3) If set, obey the hints
9748   switch (Hints.getPredicate()) {
9749   case LoopVectorizeHints::FK_Enabled:
9750     return CM_ScalarEpilogueNotNeededUsePredicate;
9751   case LoopVectorizeHints::FK_Disabled:
9752     return CM_ScalarEpilogueAllowed;
9753   };
9754 
9755   // 4) if the TTI hook indicates this is profitable, request predication.
9756   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT, &LVL))
9757     return CM_ScalarEpilogueNotNeededUsePredicate;
9758 
9759   return CM_ScalarEpilogueAllowed;
9760 }
9761 
9762 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9763   // If Values have been set for this Def return the one relevant for \p Part.
9764   if (hasVectorValue(Def, Part))
9765     return Data.PerPartOutput[Def][Part];
9766 
9767   if (!hasScalarValue(Def, {Part, 0})) {
9768     Value *IRV = Def->getLiveInIRValue();
9769     Value *B = ILV->getBroadcastInstrs(IRV);
9770     set(Def, B, Part);
9771     return B;
9772   }
9773 
9774   Value *ScalarValue = get(Def, {Part, 0});
9775   // If we aren't vectorizing, we can just copy the scalar map values over
9776   // to the vector map.
9777   if (VF.isScalar()) {
9778     set(Def, ScalarValue, Part);
9779     return ScalarValue;
9780   }
9781 
9782   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9783   bool IsUniform = RepR && RepR->isUniform();
9784 
9785   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9786   // Check if there is a scalar value for the selected lane.
9787   if (!hasScalarValue(Def, {Part, LastLane})) {
9788     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9789     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) ||
9790             isa<VPScalarIVStepsRecipe>(Def->getDef())) &&
9791            "unexpected recipe found to be invariant");
9792     IsUniform = true;
9793     LastLane = 0;
9794   }
9795 
9796   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9797   // Set the insert point after the last scalarized instruction or after the
9798   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
9799   // will directly follow the scalar definitions.
9800   auto OldIP = Builder.saveIP();
9801   auto NewIP =
9802       isa<PHINode>(LastInst)
9803           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
9804           : std::next(BasicBlock::iterator(LastInst));
9805   Builder.SetInsertPoint(&*NewIP);
9806 
9807   // However, if we are vectorizing, we need to construct the vector values.
9808   // If the value is known to be uniform after vectorization, we can just
9809   // broadcast the scalar value corresponding to lane zero for each unroll
9810   // iteration. Otherwise, we construct the vector values using
9811   // insertelement instructions. Since the resulting vectors are stored in
9812   // State, we will only generate the insertelements once.
9813   Value *VectorValue = nullptr;
9814   if (IsUniform) {
9815     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9816     set(Def, VectorValue, Part);
9817   } else {
9818     // Initialize packing with insertelements to start from undef.
9819     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9820     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9821     set(Def, Undef, Part);
9822     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9823       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9824     VectorValue = get(Def, Part);
9825   }
9826   Builder.restoreIP(OldIP);
9827   return VectorValue;
9828 }
9829 
9830 // Process the loop in the VPlan-native vectorization path. This path builds
9831 // VPlan upfront in the vectorization pipeline, which allows to apply
9832 // VPlan-to-VPlan transformations from the very beginning without modifying the
9833 // input LLVM IR.
9834 static bool processLoopInVPlanNativePath(
9835     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9836     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9837     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9838     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9839     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9840     LoopVectorizationRequirements &Requirements) {
9841 
9842   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9843     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9844     return false;
9845   }
9846   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9847   Function *F = L->getHeader()->getParent();
9848   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9849 
9850   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9851       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9852 
9853   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9854                                 &Hints, IAI);
9855   // Use the planner for outer loop vectorization.
9856   // TODO: CM is not used at this point inside the planner. Turn CM into an
9857   // optional argument if we don't need it in the future.
9858   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints, ORE);
9859 
9860   // Get user vectorization factor.
9861   ElementCount UserVF = Hints.getWidth();
9862 
9863   CM.collectElementTypesForWidening();
9864 
9865   // Plan how to best vectorize, return the best VF and its cost.
9866   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9867 
9868   // If we are stress testing VPlan builds, do not attempt to generate vector
9869   // code. Masked vector code generation support will follow soon.
9870   // Also, do not attempt to vectorize if no vector code will be produced.
9871   if (VPlanBuildStressTest || VectorizationFactor::Disabled() == VF)
9872     return false;
9873 
9874   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
9875 
9876   {
9877     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI, TTI,
9878                              F->getParent()->getDataLayout());
9879     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width,
9880                            VF.Width, 1, LVL, &CM, BFI, PSI, Checks);
9881     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9882                       << L->getHeader()->getParent()->getName() << "\"\n");
9883     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT, false);
9884   }
9885 
9886   // Mark the loop as already vectorized to avoid vectorizing again.
9887   Hints.setAlreadyVectorized();
9888   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9889   return true;
9890 }
9891 
9892 // Emit a remark if there are stores to floats that required a floating point
9893 // extension. If the vectorized loop was generated with floating point there
9894 // will be a performance penalty from the conversion overhead and the change in
9895 // the vector width.
9896 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9897   SmallVector<Instruction *, 4> Worklist;
9898   for (BasicBlock *BB : L->getBlocks()) {
9899     for (Instruction &Inst : *BB) {
9900       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9901         if (S->getValueOperand()->getType()->isFloatTy())
9902           Worklist.push_back(S);
9903       }
9904     }
9905   }
9906 
9907   // Traverse the floating point stores upwards searching, for floating point
9908   // conversions.
9909   SmallPtrSet<const Instruction *, 4> Visited;
9910   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9911   while (!Worklist.empty()) {
9912     auto *I = Worklist.pop_back_val();
9913     if (!L->contains(I))
9914       continue;
9915     if (!Visited.insert(I).second)
9916       continue;
9917 
9918     // Emit a remark if the floating point store required a floating
9919     // point conversion.
9920     // TODO: More work could be done to identify the root cause such as a
9921     // constant or a function return type and point the user to it.
9922     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9923       ORE->emit([&]() {
9924         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9925                                           I->getDebugLoc(), L->getHeader())
9926                << "floating point conversion changes vector width. "
9927                << "Mixed floating point precision requires an up/down "
9928                << "cast that will negatively impact performance.";
9929       });
9930 
9931     for (Use &Op : I->operands())
9932       if (auto *OpI = dyn_cast<Instruction>(Op))
9933         Worklist.push_back(OpI);
9934   }
9935 }
9936 
9937 static bool areRuntimeChecksProfitable(GeneratedRTChecks &Checks,
9938                                        VectorizationFactor &VF,
9939                                        Optional<unsigned> VScale, Loop *L,
9940                                        ScalarEvolution &SE) {
9941   InstructionCost CheckCost = Checks.getCost();
9942   if (!CheckCost.isValid())
9943     return false;
9944 
9945   // When interleaving only scalar and vector cost will be equal, which in turn
9946   // would lead to a divide by 0. Fall back to hard threshold.
9947   if (VF.Width.isScalar()) {
9948     if (CheckCost > VectorizeMemoryCheckThreshold) {
9949       LLVM_DEBUG(
9950           dbgs()
9951           << "LV: Interleaving only is not profitable due to runtime checks\n");
9952       return false;
9953     }
9954     return true;
9955   }
9956 
9957   // The scalar cost should only be 0 when vectorizing with a user specified VF/IC. In those cases, runtime checks should always be generated.
9958   double ScalarC = *VF.ScalarCost.getValue();
9959   if (ScalarC == 0)
9960     return true;
9961 
9962   // First, compute the minimum iteration count required so that the vector
9963   // loop outperforms the scalar loop.
9964   //  The total cost of the scalar loop is
9965   //   ScalarC * TC
9966   //  where
9967   //  * TC is the actual trip count of the loop.
9968   //  * ScalarC is the cost of a single scalar iteration.
9969   //
9970   //  The total cost of the vector loop is
9971   //    RtC + VecC * (TC / VF) + EpiC
9972   //  where
9973   //  * RtC is the cost of the generated runtime checks
9974   //  * VecC is the cost of a single vector iteration.
9975   //  * TC is the actual trip count of the loop
9976   //  * VF is the vectorization factor
9977   //  * EpiCost is the cost of the generated epilogue, including the cost
9978   //    of the remaining scalar operations.
9979   //
9980   // Vectorization is profitable once the total vector cost is less than the
9981   // total scalar cost:
9982   //   RtC + VecC * (TC / VF) + EpiC <  ScalarC * TC
9983   //
9984   // Now we can compute the minimum required trip count TC as
9985   //   (RtC + EpiC) / (ScalarC - (VecC / VF)) < TC
9986   //
9987   // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
9988   // the computations are performed on doubles, not integers and the result
9989   // is rounded up, hence we get an upper estimate of the TC.
9990   unsigned IntVF = VF.Width.getKnownMinValue();
9991   if (VF.Width.isScalable()) {
9992     unsigned AssumedMinimumVscale = 1;
9993     if (VScale)
9994       AssumedMinimumVscale = *VScale;
9995     IntVF *= AssumedMinimumVscale;
9996   }
9997   double VecCOverVF = double(*VF.Cost.getValue()) / IntVF;
9998   double RtC = *CheckCost.getValue();
9999   double MinTC1 = RtC / (ScalarC - VecCOverVF);
10000 
10001   // Second, compute a minimum iteration count so that the cost of the
10002   // runtime checks is only a fraction of the total scalar loop cost. This
10003   // adds a loop-dependent bound on the overhead incurred if the runtime
10004   // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
10005   // * TC. To bound the runtime check to be a fraction 1/X of the scalar
10006   // cost, compute
10007   //   RtC < ScalarC * TC * (1 / X)  ==>  RtC * X / ScalarC < TC
10008   double MinTC2 = RtC * 10 / ScalarC;
10009 
10010   // Now pick the larger minimum. If it is not a multiple of VF, choose the
10011   // next closest multiple of VF. This should partly compensate for ignoring
10012   // the epilogue cost.
10013   uint64_t MinTC = std::ceil(std::max(MinTC1, MinTC2));
10014   VF.MinProfitableTripCount = ElementCount::getFixed(alignTo(MinTC, IntVF));
10015 
10016   LLVM_DEBUG(
10017       dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
10018              << VF.MinProfitableTripCount << "\n");
10019 
10020   // Skip vectorization if the expected trip count is less than the minimum
10021   // required trip count.
10022   if (auto ExpectedTC = getSmallBestKnownTC(SE, L)) {
10023     if (ElementCount::isKnownLT(ElementCount::getFixed(*ExpectedTC),
10024                                 VF.MinProfitableTripCount)) {
10025       LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
10026                            "trip count < minimum profitable VF ("
10027                         << *ExpectedTC << " < " << VF.MinProfitableTripCount
10028                         << ")\n");
10029 
10030       return false;
10031     }
10032   }
10033   return true;
10034 }
10035 
10036 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10037     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10038                                !EnableLoopInterleaving),
10039       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10040                               !EnableLoopVectorization) {}
10041 
10042 bool LoopVectorizePass::processLoop(Loop *L) {
10043   assert((EnableVPlanNativePath || L->isInnermost()) &&
10044          "VPlan-native path is not enabled. Only process inner loops.");
10045 
10046 #ifndef NDEBUG
10047   const std::string DebugLocStr = getDebugLocString(L);
10048 #endif /* NDEBUG */
10049 
10050   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
10051                     << L->getHeader()->getParent()->getName() << "' from "
10052                     << DebugLocStr << "\n");
10053 
10054   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10055 
10056   LLVM_DEBUG(
10057       dbgs() << "LV: Loop hints:"
10058              << " force="
10059              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10060                      ? "disabled"
10061                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10062                             ? "enabled"
10063                             : "?"))
10064              << " width=" << Hints.getWidth()
10065              << " interleave=" << Hints.getInterleave() << "\n");
10066 
10067   // Function containing loop
10068   Function *F = L->getHeader()->getParent();
10069 
10070   // Looking at the diagnostic output is the only way to determine if a loop
10071   // was vectorized (other than looking at the IR or machine code), so it
10072   // is important to generate an optimization remark for each loop. Most of
10073   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10074   // generated as OptimizationRemark and OptimizationRemarkMissed are
10075   // less verbose reporting vectorized loops and unvectorized loops that may
10076   // benefit from vectorization, respectively.
10077 
10078   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10079     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10080     return false;
10081   }
10082 
10083   PredicatedScalarEvolution PSE(*SE, *L);
10084 
10085   // Check if it is legal to vectorize the loop.
10086   LoopVectorizationRequirements Requirements;
10087   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10088                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10089   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10090     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10091     Hints.emitRemarkWithHints();
10092     return false;
10093   }
10094 
10095   // Check the function attributes and profiles to find out if this function
10096   // should be optimized for size.
10097   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10098       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10099 
10100   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10101   // here. They may require CFG and instruction level transformations before
10102   // even evaluating whether vectorization is profitable. Since we cannot modify
10103   // the incoming IR, we need to build VPlan upfront in the vectorization
10104   // pipeline.
10105   if (!L->isInnermost())
10106     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10107                                         ORE, BFI, PSI, Hints, Requirements);
10108 
10109   assert(L->isInnermost() && "Inner loop expected.");
10110 
10111   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10112   // count by optimizing for size, to minimize overheads.
10113   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10114   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10115     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10116                       << "This loop is worth vectorizing only if no scalar "
10117                       << "iteration overheads are incurred.");
10118     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10119       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10120     else {
10121       LLVM_DEBUG(dbgs() << "\n");
10122       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10123     }
10124   }
10125 
10126   // Check the function attributes to see if implicit floats are allowed.
10127   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10128   // an integer loop and the vector instructions selected are purely integer
10129   // vector instructions?
10130   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10131     reportVectorizationFailure(
10132         "Can't vectorize when the NoImplicitFloat attribute is used",
10133         "loop not vectorized due to NoImplicitFloat attribute",
10134         "NoImplicitFloat", ORE, L);
10135     Hints.emitRemarkWithHints();
10136     return false;
10137   }
10138 
10139   // Check if the target supports potentially unsafe FP vectorization.
10140   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10141   // for the target we're vectorizing for, to make sure none of the
10142   // additional fp-math flags can help.
10143   if (Hints.isPotentiallyUnsafe() &&
10144       TTI->isFPVectorizationPotentiallyUnsafe()) {
10145     reportVectorizationFailure(
10146         "Potentially unsafe FP op prevents vectorization",
10147         "loop not vectorized due to unsafe FP support.",
10148         "UnsafeFP", ORE, L);
10149     Hints.emitRemarkWithHints();
10150     return false;
10151   }
10152 
10153   bool AllowOrderedReductions;
10154   // If the flag is set, use that instead and override the TTI behaviour.
10155   if (ForceOrderedReductions.getNumOccurrences() > 0)
10156     AllowOrderedReductions = ForceOrderedReductions;
10157   else
10158     AllowOrderedReductions = TTI->enableOrderedReductions();
10159   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10160     ORE->emit([&]() {
10161       auto *ExactFPMathInst = Requirements.getExactFPInst();
10162       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10163                                                  ExactFPMathInst->getDebugLoc(),
10164                                                  ExactFPMathInst->getParent())
10165              << "loop not vectorized: cannot prove it is safe to reorder "
10166                 "floating-point operations";
10167     });
10168     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10169                          "reorder floating-point operations\n");
10170     Hints.emitRemarkWithHints();
10171     return false;
10172   }
10173 
10174   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10175   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10176 
10177   // If an override option has been passed in for interleaved accesses, use it.
10178   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10179     UseInterleaved = EnableInterleavedMemAccesses;
10180 
10181   // Analyze interleaved memory accesses.
10182   if (UseInterleaved) {
10183     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10184   }
10185 
10186   // Use the cost model.
10187   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10188                                 F, &Hints, IAI);
10189   CM.collectValuesToIgnore();
10190   CM.collectElementTypesForWidening();
10191 
10192   // Use the planner for vectorization.
10193   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints, ORE);
10194 
10195   // Get user vectorization factor and interleave count.
10196   ElementCount UserVF = Hints.getWidth();
10197   unsigned UserIC = Hints.getInterleave();
10198 
10199   // Plan how to best vectorize, return the best VF and its cost.
10200   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10201 
10202   VectorizationFactor VF = VectorizationFactor::Disabled();
10203   unsigned IC = 1;
10204 
10205   GeneratedRTChecks Checks(*PSE.getSE(), DT, LI, TTI,
10206                            F->getParent()->getDataLayout());
10207   if (MaybeVF) {
10208     VF = *MaybeVF;
10209     // Select the interleave count.
10210     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10211 
10212     unsigned SelectedIC = std::max(IC, UserIC);
10213     //  Optimistically generate runtime checks if they are needed. Drop them if
10214     //  they turn out to not be profitable.
10215     if (VF.Width.isVector() || SelectedIC > 1)
10216       Checks.Create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC);
10217 
10218     // Check if it is profitable to vectorize with runtime checks.
10219     bool ForceVectorization =
10220         Hints.getForce() == LoopVectorizeHints::FK_Enabled;
10221     if (!ForceVectorization &&
10222         !areRuntimeChecksProfitable(Checks, VF, CM.getVScaleForTuning(), L,
10223                                     *PSE.getSE())) {
10224       ORE->emit([&]() {
10225         return OptimizationRemarkAnalysisAliasing(
10226                    DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
10227                    L->getHeader())
10228                << "loop not vectorized: cannot prove it is safe to reorder "
10229                   "memory operations";
10230       });
10231       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
10232       Hints.emitRemarkWithHints();
10233       return false;
10234     }
10235   }
10236 
10237   // Identify the diagnostic messages that should be produced.
10238   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10239   bool VectorizeLoop = true, InterleaveLoop = true;
10240   if (VF.Width.isScalar()) {
10241     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10242     VecDiagMsg = std::make_pair(
10243         "VectorizationNotBeneficial",
10244         "the cost-model indicates that vectorization is not beneficial");
10245     VectorizeLoop = false;
10246   }
10247 
10248   if (!MaybeVF && UserIC > 1) {
10249     // Tell the user interleaving was avoided up-front, despite being explicitly
10250     // requested.
10251     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10252                          "interleaving should be avoided up front\n");
10253     IntDiagMsg = std::make_pair(
10254         "InterleavingAvoided",
10255         "Ignoring UserIC, because interleaving was avoided up front");
10256     InterleaveLoop = false;
10257   } else if (IC == 1 && UserIC <= 1) {
10258     // Tell the user interleaving is not beneficial.
10259     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10260     IntDiagMsg = std::make_pair(
10261         "InterleavingNotBeneficial",
10262         "the cost-model indicates that interleaving is not beneficial");
10263     InterleaveLoop = false;
10264     if (UserIC == 1) {
10265       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10266       IntDiagMsg.second +=
10267           " and is explicitly disabled or interleave count is set to 1";
10268     }
10269   } else if (IC > 1 && UserIC == 1) {
10270     // Tell the user interleaving is beneficial, but it explicitly disabled.
10271     LLVM_DEBUG(
10272         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10273     IntDiagMsg = std::make_pair(
10274         "InterleavingBeneficialButDisabled",
10275         "the cost-model indicates that interleaving is beneficial "
10276         "but is explicitly disabled or interleave count is set to 1");
10277     InterleaveLoop = false;
10278   }
10279 
10280   // Override IC if user provided an interleave count.
10281   IC = UserIC > 0 ? UserIC : IC;
10282 
10283   // Emit diagnostic messages, if any.
10284   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10285   if (!VectorizeLoop && !InterleaveLoop) {
10286     // Do not vectorize or interleaving the loop.
10287     ORE->emit([&]() {
10288       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10289                                       L->getStartLoc(), L->getHeader())
10290              << VecDiagMsg.second;
10291     });
10292     ORE->emit([&]() {
10293       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10294                                       L->getStartLoc(), L->getHeader())
10295              << IntDiagMsg.second;
10296     });
10297     return false;
10298   } else if (!VectorizeLoop && InterleaveLoop) {
10299     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10300     ORE->emit([&]() {
10301       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10302                                         L->getStartLoc(), L->getHeader())
10303              << VecDiagMsg.second;
10304     });
10305   } else if (VectorizeLoop && !InterleaveLoop) {
10306     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10307                       << ") in " << DebugLocStr << '\n');
10308     ORE->emit([&]() {
10309       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10310                                         L->getStartLoc(), L->getHeader())
10311              << IntDiagMsg.second;
10312     });
10313   } else if (VectorizeLoop && InterleaveLoop) {
10314     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10315                       << ") in " << DebugLocStr << '\n');
10316     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10317   }
10318 
10319   bool DisableRuntimeUnroll = false;
10320   MDNode *OrigLoopID = L->getLoopID();
10321   {
10322     using namespace ore;
10323     if (!VectorizeLoop) {
10324       assert(IC > 1 && "interleave count should not be 1 or 0");
10325       // If we decided that it is not legal to vectorize the loop, then
10326       // interleave it.
10327       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10328                                  &CM, BFI, PSI, Checks);
10329 
10330       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10331       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT, false);
10332 
10333       ORE->emit([&]() {
10334         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10335                                   L->getHeader())
10336                << "interleaved loop (interleaved count: "
10337                << NV("InterleaveCount", IC) << ")";
10338       });
10339     } else {
10340       // If we decided that it is *legal* to vectorize the loop, then do it.
10341 
10342       // Consider vectorizing the epilogue too if it's profitable.
10343       VectorizationFactor EpilogueVF =
10344           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10345       if (EpilogueVF.Width.isVector()) {
10346 
10347         // The first pass vectorizes the main loop and creates a scalar epilogue
10348         // to be vectorized by executing the plan (potentially with a different
10349         // factor) again shortly afterwards.
10350         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10351         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10352                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10353 
10354         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10355         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10356                         DT, true);
10357         ++LoopsVectorized;
10358 
10359         // Second pass vectorizes the epilogue and adjusts the control flow
10360         // edges from the first pass.
10361         EPI.MainLoopVF = EPI.EpilogueVF;
10362         EPI.MainLoopUF = EPI.EpilogueUF;
10363         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10364                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10365                                                  Checks);
10366 
10367         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10368         VPRegionBlock *VectorLoop = BestEpiPlan.getVectorLoopRegion();
10369         VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
10370         Header->setName("vec.epilog.vector.body");
10371 
10372         // Ensure that the start values for any VPReductionPHIRecipes are
10373         // updated before vectorising the epilogue loop.
10374         for (VPRecipeBase &R : Header->phis()) {
10375           if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10376             if (auto *Resume = MainILV.getReductionResumeValue(
10377                     ReductionPhi->getRecurrenceDescriptor())) {
10378               VPValue *StartVal = BestEpiPlan.getOrAddExternalDef(Resume);
10379               ReductionPhi->setOperand(0, StartVal);
10380             }
10381           }
10382         }
10383 
10384         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10385                         DT, true);
10386         ++LoopsEpilogueVectorized;
10387 
10388         if (!MainILV.areSafetyChecksAdded())
10389           DisableRuntimeUnroll = true;
10390       } else {
10391         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width,
10392                                VF.MinProfitableTripCount, IC, &LVL, &CM, BFI,
10393                                PSI, Checks);
10394 
10395         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10396         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT, false);
10397         ++LoopsVectorized;
10398 
10399         // Add metadata to disable runtime unrolling a scalar loop when there
10400         // are no runtime checks about strides and memory. A scalar loop that is
10401         // rarely used is not worth unrolling.
10402         if (!LB.areSafetyChecksAdded())
10403           DisableRuntimeUnroll = true;
10404       }
10405       // Report the vectorization decision.
10406       ORE->emit([&]() {
10407         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10408                                   L->getHeader())
10409                << "vectorized loop (vectorization width: "
10410                << NV("VectorizationFactor", VF.Width)
10411                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10412       });
10413     }
10414 
10415     if (ORE->allowExtraAnalysis(LV_NAME))
10416       checkMixedPrecision(L, ORE);
10417   }
10418 
10419   Optional<MDNode *> RemainderLoopID =
10420       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10421                                       LLVMLoopVectorizeFollowupEpilogue});
10422   if (RemainderLoopID) {
10423     L->setLoopID(RemainderLoopID.value());
10424   } else {
10425     if (DisableRuntimeUnroll)
10426       AddRuntimeUnrollDisableMetaData(L);
10427 
10428     // Mark the loop as already vectorized to avoid vectorizing again.
10429     Hints.setAlreadyVectorized();
10430   }
10431 
10432   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10433   return true;
10434 }
10435 
10436 LoopVectorizeResult LoopVectorizePass::runImpl(
10437     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10438     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10439     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10440     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10441     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10442   SE = &SE_;
10443   LI = &LI_;
10444   TTI = &TTI_;
10445   DT = &DT_;
10446   BFI = &BFI_;
10447   TLI = TLI_;
10448   AA = &AA_;
10449   AC = &AC_;
10450   GetLAA = &GetLAA_;
10451   DB = &DB_;
10452   ORE = &ORE_;
10453   PSI = PSI_;
10454 
10455   // Don't attempt if
10456   // 1. the target claims to have no vector registers, and
10457   // 2. interleaving won't help ILP.
10458   //
10459   // The second condition is necessary because, even if the target has no
10460   // vector registers, loop vectorization may still enable scalar
10461   // interleaving.
10462   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10463       TTI->getMaxInterleaveFactor(1) < 2)
10464     return LoopVectorizeResult(false, false);
10465 
10466   bool Changed = false, CFGChanged = false;
10467 
10468   // The vectorizer requires loops to be in simplified form.
10469   // Since simplification may add new inner loops, it has to run before the
10470   // legality and profitability checks. This means running the loop vectorizer
10471   // will simplify all loops, regardless of whether anything end up being
10472   // vectorized.
10473   for (auto &L : *LI)
10474     Changed |= CFGChanged |=
10475         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10476 
10477   // Build up a worklist of inner-loops to vectorize. This is necessary as
10478   // the act of vectorizing or partially unrolling a loop creates new loops
10479   // and can invalidate iterators across the loops.
10480   SmallVector<Loop *, 8> Worklist;
10481 
10482   for (Loop *L : *LI)
10483     collectSupportedLoops(*L, LI, ORE, Worklist);
10484 
10485   LoopsAnalyzed += Worklist.size();
10486 
10487   // Now walk the identified inner loops.
10488   while (!Worklist.empty()) {
10489     Loop *L = Worklist.pop_back_val();
10490 
10491     // For the inner loops we actually process, form LCSSA to simplify the
10492     // transform.
10493     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10494 
10495     Changed |= CFGChanged |= processLoop(L);
10496   }
10497 
10498   // Process each loop nest in the function.
10499   return LoopVectorizeResult(Changed, CFGChanged);
10500 }
10501 
10502 PreservedAnalyses LoopVectorizePass::run(Function &F,
10503                                          FunctionAnalysisManager &AM) {
10504     auto &LI = AM.getResult<LoopAnalysis>(F);
10505     // There are no loops in the function. Return before computing other expensive
10506     // analyses.
10507     if (LI.empty())
10508       return PreservedAnalyses::all();
10509     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10510     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10511     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10512     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10513     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10514     auto &AA = AM.getResult<AAManager>(F);
10515     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10516     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10517     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10518 
10519     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10520     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10521         [&](Loop &L) -> const LoopAccessInfo & {
10522       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10523                                         TLI, TTI, nullptr, nullptr, nullptr};
10524       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10525     };
10526     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10527     ProfileSummaryInfo *PSI =
10528         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10529     LoopVectorizeResult Result =
10530         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10531     if (!Result.MadeAnyChange)
10532       return PreservedAnalyses::all();
10533     PreservedAnalyses PA;
10534 
10535     // We currently do not preserve loopinfo/dominator analyses with outer loop
10536     // vectorization. Until this is addressed, mark these analyses as preserved
10537     // only for non-VPlan-native path.
10538     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10539     if (!EnableVPlanNativePath) {
10540       PA.preserve<LoopAnalysis>();
10541       PA.preserve<DominatorTreeAnalysis>();
10542     }
10543 
10544     if (Result.MadeCFGChange) {
10545       // Making CFG changes likely means a loop got vectorized. Indicate that
10546       // extra simplification passes should be run.
10547       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10548       // be run if runtime checks have been added.
10549       AM.getResult<ShouldRunExtraVectorPasses>(F);
10550       PA.preserve<ShouldRunExtraVectorPasses>();
10551     } else {
10552       PA.preserveSet<CFGAnalyses>();
10553     }
10554     return PA;
10555 }
10556 
10557 void LoopVectorizePass::printPipeline(
10558     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10559   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10560       OS, MapClassName2PassName);
10561 
10562   OS << "<";
10563   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10564   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10565   OS << ">";
10566 }
10567