1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10 // and generates target-independent LLVM-IR.
11 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12 // of instructions in order to estimate the profitability of vectorization.
13 //
14 // The loop vectorizer combines consecutive loop iterations into a single
15 // 'wide' iteration. After this transformation the index is incremented
16 // by the SIMD vector width, and not by one.
17 //
18 // This pass has three parts:
19 // 1. The main loop pass that drives the different parts.
20 // 2. LoopVectorizationLegality - A unit that checks for the legality
21 //    of the vectorization.
22 // 3. InnerLoopVectorizer - A unit that performs the actual
23 //    widening of instructions.
24 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
25 //    of vectorization. It decides on the optimal vector width, which
26 //    can be one, if vectorization is not profitable.
27 //
28 // There is a development effort going on to migrate loop vectorizer to the
29 // VPlan infrastructure and to introduce outer loop vectorization support (see
30 // docs/Proposal/VectorizationPlan.rst and
31 // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32 // purpose, we temporarily introduced the VPlan-native vectorization path: an
33 // alternative vectorization path that is natively implemented on top of the
34 // VPlan infrastructure. See EnableVPlanNativePath for enabling.
35 //
36 //===----------------------------------------------------------------------===//
37 //
38 // The reduction-variable vectorization is based on the paper:
39 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40 //
41 // Variable uniformity checks are inspired by:
42 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
43 //
44 // The interleaved access vectorization is based on the paper:
45 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
46 //  Data for SIMD
47 //
48 // Other ideas/concepts are from:
49 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50 //
51 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
52 //  Vectorizing Compilers.
53 //
54 //===----------------------------------------------------------------------===//
55 
56 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
57 #include "LoopVectorizationPlanner.h"
58 #include "VPRecipeBuilder.h"
59 #include "VPlan.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "VPlanPredicator.h"
62 #include "VPlanTransforms.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/ArrayRef.h"
65 #include "llvm/ADT/DenseMap.h"
66 #include "llvm/ADT/DenseMapInfo.h"
67 #include "llvm/ADT/Hashing.h"
68 #include "llvm/ADT/MapVector.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallPtrSet.h"
73 #include "llvm/ADT/SmallSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/Statistic.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Twine.h"
78 #include "llvm/ADT/iterator_range.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/BasicAliasAnalysis.h"
81 #include "llvm/Analysis/BlockFrequencyInfo.h"
82 #include "llvm/Analysis/CFG.h"
83 #include "llvm/Analysis/CodeMetrics.h"
84 #include "llvm/Analysis/DemandedBits.h"
85 #include "llvm/Analysis/GlobalsModRef.h"
86 #include "llvm/Analysis/LoopAccessAnalysis.h"
87 #include "llvm/Analysis/LoopAnalysisManager.h"
88 #include "llvm/Analysis/LoopInfo.h"
89 #include "llvm/Analysis/LoopIterator.h"
90 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
91 #include "llvm/Analysis/ProfileSummaryInfo.h"
92 #include "llvm/Analysis/ScalarEvolution.h"
93 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
94 #include "llvm/Analysis/TargetLibraryInfo.h"
95 #include "llvm/Analysis/TargetTransformInfo.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/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> PragmaVectorizeMemoryCheckThreshold(
201     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
202     cl::desc("The maximum allowed number of runtime memory checks with a "
203              "vectorize(enable) pragma."));
204 
205 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
206 // that predication is preferred, and this lists all options. I.e., the
207 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
208 // and predicate the instructions accordingly. If tail-folding fails, there are
209 // different fallback strategies depending on these values:
210 namespace PreferPredicateTy {
211   enum Option {
212     ScalarEpilogue = 0,
213     PredicateElseScalarEpilogue,
214     PredicateOrDontVectorize
215   };
216 } // namespace PreferPredicateTy
217 
218 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
219     "prefer-predicate-over-epilogue",
220     cl::init(PreferPredicateTy::ScalarEpilogue),
221     cl::Hidden,
222     cl::desc("Tail-folding and predication preferences over creating a scalar "
223              "epilogue loop."),
224     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
225                          "scalar-epilogue",
226                          "Don't tail-predicate loops, create scalar epilogue"),
227               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
228                          "predicate-else-scalar-epilogue",
229                          "prefer tail-folding, create scalar epilogue if tail "
230                          "folding fails."),
231               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
232                          "predicate-dont-vectorize",
233                          "prefers tail-folding, don't attempt vectorization if "
234                          "tail-folding fails.")));
235 
236 static cl::opt<bool> MaximizeBandwidth(
237     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
238     cl::desc("Maximize bandwidth when selecting vectorization factor which "
239              "will be determined by the smallest type in loop."));
240 
241 static cl::opt<bool> EnableInterleavedMemAccesses(
242     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
243     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
244 
245 /// An interleave-group may need masking if it resides in a block that needs
246 /// predication, or in order to mask away gaps.
247 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
248     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
249     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
250 
251 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
252     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
253     cl::desc("We don't interleave loops with a estimated constant trip count "
254              "below this number"));
255 
256 static cl::opt<unsigned> ForceTargetNumScalarRegs(
257     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
258     cl::desc("A flag that overrides the target's number of scalar registers."));
259 
260 static cl::opt<unsigned> ForceTargetNumVectorRegs(
261     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
262     cl::desc("A flag that overrides the target's number of vector registers."));
263 
264 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
265     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
266     cl::desc("A flag that overrides the target's max interleave factor for "
267              "scalar loops."));
268 
269 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
270     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
271     cl::desc("A flag that overrides the target's max interleave factor for "
272              "vectorized loops."));
273 
274 static cl::opt<unsigned> ForceTargetInstructionCost(
275     "force-target-instruction-cost", cl::init(0), cl::Hidden,
276     cl::desc("A flag that overrides the target's expected cost for "
277              "an instruction to a single constant value. Mostly "
278              "useful for getting consistent testing."));
279 
280 static cl::opt<bool> ForceTargetSupportsScalableVectors(
281     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
282     cl::desc(
283         "Pretend that scalable vectors are supported, even if the target does "
284         "not support them. This flag should only be used for testing."));
285 
286 static cl::opt<unsigned> SmallLoopCost(
287     "small-loop-cost", cl::init(20), cl::Hidden,
288     cl::desc(
289         "The cost of a loop that is considered 'small' by the interleaver."));
290 
291 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
292     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
293     cl::desc("Enable the use of the block frequency analysis to access PGO "
294              "heuristics minimizing code growth in cold regions and being more "
295              "aggressive in hot regions."));
296 
297 // Runtime interleave loops for load/store throughput.
298 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
299     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
300     cl::desc(
301         "Enable runtime interleaving until load/store ports are saturated"));
302 
303 /// Interleave small loops with scalar reductions.
304 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
305     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
306     cl::desc("Enable interleaving for loops with small iteration counts that "
307              "contain scalar reductions to expose ILP."));
308 
309 /// The number of stores in a loop that are allowed to need predication.
310 static cl::opt<unsigned> NumberOfStoresToPredicate(
311     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
312     cl::desc("Max number of stores to be predicated behind an if."));
313 
314 static cl::opt<bool> EnableIndVarRegisterHeur(
315     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
316     cl::desc("Count the induction variable only once when interleaving"));
317 
318 static cl::opt<bool> EnableCondStoresVectorization(
319     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
320     cl::desc("Enable if predication of stores during vectorization."));
321 
322 static cl::opt<unsigned> MaxNestedScalarReductionIC(
323     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
324     cl::desc("The maximum interleave count to use when interleaving a scalar "
325              "reduction in a nested loop."));
326 
327 static cl::opt<bool>
328     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
329                            cl::Hidden,
330                            cl::desc("Prefer in-loop vector reductions, "
331                                     "overriding the targets preference."));
332 
333 static cl::opt<bool> ForceOrderedReductions(
334     "force-ordered-reductions", cl::init(false), cl::Hidden,
335     cl::desc("Enable the vectorisation of loops with in-order (strict) "
336              "FP reductions"));
337 
338 static cl::opt<bool> PreferPredicatedReductionSelect(
339     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
340     cl::desc(
341         "Prefer predicating a reduction operation over an after loop select."));
342 
343 cl::opt<bool> EnableVPlanNativePath(
344     "enable-vplan-native-path", cl::init(false), cl::Hidden,
345     cl::desc("Enable VPlan-native vectorization path with "
346              "support for outer loop vectorization."));
347 
348 // FIXME: Remove this switch once we have divergence analysis. Currently we
349 // assume divergent non-backedge branches when this switch is true.
350 cl::opt<bool> EnableVPlanPredication(
351     "enable-vplan-predication", cl::init(false), cl::Hidden,
352     cl::desc("Enable VPlan-native vectorization path predicator with "
353              "support for outer loop vectorization."));
354 
355 // This flag enables the stress testing of the VPlan H-CFG construction in the
356 // VPlan-native vectorization path. It must be used in conjuction with
357 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
358 // verification of the H-CFGs built.
359 static cl::opt<bool> VPlanBuildStressTest(
360     "vplan-build-stress-test", cl::init(false), cl::Hidden,
361     cl::desc(
362         "Build VPlan for every supported loop nest in the function and bail "
363         "out right after the build (stress test the VPlan H-CFG construction "
364         "in the VPlan-native vectorization path)."));
365 
366 cl::opt<bool> llvm::EnableLoopInterleaving(
367     "interleave-loops", cl::init(true), cl::Hidden,
368     cl::desc("Enable loop interleaving in Loop vectorization passes"));
369 cl::opt<bool> llvm::EnableLoopVectorization(
370     "vectorize-loops", cl::init(true), cl::Hidden,
371     cl::desc("Run the Loop vectorization passes"));
372 
373 cl::opt<bool> PrintVPlansInDotFormat(
374     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
375     cl::desc("Use dot format instead of plain text when dumping VPlans"));
376 
377 /// A helper function that returns true if the given type is irregular. The
378 /// type is irregular if its allocated size doesn't equal the store size of an
379 /// element of the corresponding vector type.
380 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
381   // Determine if an array of N elements of type Ty is "bitcast compatible"
382   // with a <N x Ty> vector.
383   // This is only true if there is no padding between the array elements.
384   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
385 }
386 
387 /// A helper function that returns the reciprocal of the block probability of
388 /// predicated blocks. If we return X, we are assuming the predicated block
389 /// will execute once for every X iterations of the loop header.
390 ///
391 /// TODO: We should use actual block probability here, if available. Currently,
392 ///       we always assume predicated blocks have a 50% chance of executing.
393 static unsigned getReciprocalPredBlockProb() { return 2; }
394 
395 /// A helper function that returns an integer or floating-point constant with
396 /// value C.
397 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
398   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
399                            : ConstantFP::get(Ty, C);
400 }
401 
402 /// Returns "best known" trip count for the specified loop \p L as defined by
403 /// the following procedure:
404 ///   1) Returns exact trip count if it is known.
405 ///   2) Returns expected trip count according to profile data if any.
406 ///   3) Returns upper bound estimate if it is known.
407 ///   4) Returns None if all of the above failed.
408 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
409   // Check if exact trip count is known.
410   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
411     return ExpectedTC;
412 
413   // Check if there is an expected trip count available from profile data.
414   if (LoopVectorizeWithBlockFrequency)
415     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
416       return EstimatedTC;
417 
418   // Check if upper bound estimate is known.
419   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
420     return ExpectedTC;
421 
422   return None;
423 }
424 
425 // Forward declare GeneratedRTChecks.
426 class GeneratedRTChecks;
427 
428 namespace llvm {
429 
430 AnalysisKey ShouldRunExtraVectorPasses::Key;
431 
432 /// InnerLoopVectorizer vectorizes loops which contain only one basic
433 /// block to a specified vectorization factor (VF).
434 /// This class performs the widening of scalars into vectors, or multiple
435 /// scalars. This class also implements the following features:
436 /// * It inserts an epilogue loop for handling loops that don't have iteration
437 ///   counts that are known to be a multiple of the vectorization factor.
438 /// * It handles the code generation for reduction variables.
439 /// * Scalarization (implementation using scalars) of un-vectorizable
440 ///   instructions.
441 /// InnerLoopVectorizer does not perform any vectorization-legality
442 /// checks, and relies on the caller to check for the different legality
443 /// aspects. The InnerLoopVectorizer relies on the
444 /// LoopVectorizationLegality class to provide information about the induction
445 /// and reduction variables that were found to a given vectorization factor.
446 class InnerLoopVectorizer {
447 public:
448   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
449                       LoopInfo *LI, DominatorTree *DT,
450                       const TargetLibraryInfo *TLI,
451                       const TargetTransformInfo *TTI, AssumptionCache *AC,
452                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
453                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
454                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
455                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
456       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
457         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
458         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
459         PSI(PSI), RTChecks(RTChecks) {
460     // Query this against the original loop and save it here because the profile
461     // of the original loop header may change as the transformation happens.
462     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
463         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
464   }
465 
466   virtual ~InnerLoopVectorizer() = default;
467 
468   /// Create a new empty loop that will contain vectorized instructions later
469   /// on, while the old loop will be used as the scalar remainder. Control flow
470   /// is generated around the vectorized (and scalar epilogue) loops consisting
471   /// of various checks and bypasses. Return the pre-header block of the new
472   /// loop and the start value for the canonical induction, if it is != 0. The
473   /// latter is the case when vectorizing the epilogue loop. In the case of
474   /// epilogue vectorization, this function is overriden to handle the more
475   /// complex control flow around the loops.
476   virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
477 
478   /// Widen a single call instruction within the innermost loop.
479   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
480                             VPTransformState &State);
481 
482   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
483   void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
484 
485   // Return true if any runtime check is added.
486   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
487 
488   /// A type for vectorized values in the new loop. Each value from the
489   /// original loop, when vectorized, is represented by UF vector values in the
490   /// new unrolled loop, where UF is the unroll factor.
491   using VectorParts = SmallVector<Value *, 2>;
492 
493   /// Vectorize a single vector PHINode in a block in the VPlan-native path
494   /// only.
495   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
496                            VPTransformState &State);
497 
498   /// A helper function to scalarize a single Instruction in the innermost loop.
499   /// Generates a sequence of scalar instances for each lane between \p MinLane
500   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
501   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
502   /// Instr's operands.
503   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
504                             const VPIteration &Instance, bool IfPredicateInstr,
505                             VPTransformState &State);
506 
507   /// Construct the vector value of a scalarized value \p V one lane at a time.
508   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
509                                  VPTransformState &State);
510 
511   /// Try to vectorize interleaved access group \p Group with the base address
512   /// given in \p Addr, optionally masking the vector operations if \p
513   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
514   /// values in the vectorized loop.
515   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
516                                 ArrayRef<VPValue *> VPDefs,
517                                 VPTransformState &State, VPValue *Addr,
518                                 ArrayRef<VPValue *> StoredValues,
519                                 VPValue *BlockInMask = nullptr);
520 
521   /// Set the debug location in the builder \p Ptr using the debug location in
522   /// \p V. If \p Ptr is None then it uses the class member's Builder.
523   void setDebugLocFromInst(const Value *V,
524                            Optional<IRBuilderBase *> CustomBuilder = None);
525 
526   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
527   void fixNonInductionPHIs(VPTransformState &State);
528 
529   /// Returns true if the reordering of FP operations is not allowed, but we are
530   /// able to vectorize with strict in-order reductions for the given RdxDesc.
531   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
532 
533   /// Create a broadcast instruction. This method generates a broadcast
534   /// instruction (shuffle) for loop invariant values and for the induction
535   /// value. If this is the induction variable then we extend it to N, N+1, ...
536   /// this is needed because each iteration in the loop corresponds to a SIMD
537   /// element.
538   virtual Value *getBroadcastInstrs(Value *V);
539 
540   /// Add metadata from one instruction to another.
541   ///
542   /// This includes both the original MDs from \p From and additional ones (\see
543   /// addNewMetadata).  Use this for *newly created* instructions in the vector
544   /// loop.
545   void addMetadata(Instruction *To, Instruction *From);
546 
547   /// Similar to the previous function but it adds the metadata to a
548   /// vector of instructions.
549   void addMetadata(ArrayRef<Value *> To, Instruction *From);
550 
551   // Returns the resume value (bc.merge.rdx) for a reduction as
552   // generated by fixReduction.
553   PHINode *getReductionResumeValue(const RecurrenceDescriptor &RdxDesc);
554 
555 protected:
556   friend class LoopVectorizationPlanner;
557 
558   /// A small list of PHINodes.
559   using PhiVector = SmallVector<PHINode *, 4>;
560 
561   /// A type for scalarized values in the new loop. Each value from the
562   /// original loop, when scalarized, is represented by UF x VF scalar values
563   /// in the new unrolled loop, where UF is the unroll factor and VF is the
564   /// vectorization factor.
565   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
566 
567   /// Set up the values of the IVs correctly when exiting the vector loop.
568   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
569                     Value *VectorTripCount, Value *EndValue,
570                     BasicBlock *MiddleBlock, BasicBlock *VectorHeader);
571 
572   /// Handle all cross-iteration phis in the header.
573   void fixCrossIterationPHIs(VPTransformState &State);
574 
575   /// Create the exit value of first order recurrences in the middle block and
576   /// update their users.
577   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
578                                VPTransformState &State);
579 
580   /// Create code for the loop exit value of the reduction.
581   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
582 
583   /// Clear NSW/NUW flags from reduction instructions if necessary.
584   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
585                                VPTransformState &State);
586 
587   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
588   /// means we need to add the appropriate incoming value from the middle
589   /// block as exiting edges from the scalar epilogue loop (if present) are
590   /// already in place, and we exit the vector loop exclusively to the middle
591   /// block.
592   void fixLCSSAPHIs(VPTransformState &State);
593 
594   /// Iteratively sink the scalarized operands of a predicated instruction into
595   /// the block that was created for it.
596   void sinkScalarOperands(Instruction *PredInst);
597 
598   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
599   /// represented as.
600   void truncateToMinimalBitwidths(VPTransformState &State);
601 
602   /// Returns (and creates if needed) the original loop trip count.
603   Value *getOrCreateTripCount(BasicBlock *InsertBlock);
604 
605   /// Returns (and creates if needed) the trip count of the widened loop.
606   Value *getOrCreateVectorTripCount(BasicBlock *InsertBlock);
607 
608   /// Returns a bitcasted value to the requested vector type.
609   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
610   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
611                                 const DataLayout &DL);
612 
613   /// Emit a bypass check to see if the vector trip count is zero, including if
614   /// it overflows.
615   void emitIterationCountCheck(BasicBlock *Bypass);
616 
617   /// Emit a bypass check to see if all of the SCEV assumptions we've
618   /// had to make are correct. Returns the block containing the checks or
619   /// nullptr if no checks have been added.
620   BasicBlock *emitSCEVChecks(BasicBlock *Bypass);
621 
622   /// Emit bypass checks to check any memory assumptions we may have made.
623   /// Returns the block containing the checks or nullptr if no checks have been
624   /// added.
625   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass);
626 
627   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
628   /// vector loop preheader, middle block and scalar preheader.
629   void createVectorLoopSkeleton(StringRef Prefix);
630 
631   /// Create new phi nodes for the induction variables to resume iteration count
632   /// in the scalar epilogue, from where the vectorized loop left off.
633   /// In cases where the loop skeleton is more complicated (eg. epilogue
634   /// vectorization) and the resume values can come from an additional bypass
635   /// block, the \p AdditionalBypass pair provides information about the bypass
636   /// block and the end value on the edge from bypass to this loop.
637   void createInductionResumeValues(
638       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
639 
640   /// Complete the loop skeleton by adding debug MDs, creating appropriate
641   /// conditional branches in the middle block, preparing the builder and
642   /// running the verifier. Return the preheader of the completed vector loop.
643   BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
644 
645   /// Add additional metadata to \p To that was not present on \p Orig.
646   ///
647   /// Currently this is used to add the noalias annotations based on the
648   /// inserted memchecks.  Use this for instructions that are *cloned* into the
649   /// vector loop.
650   void addNewMetadata(Instruction *To, const Instruction *Orig);
651 
652   /// Collect poison-generating recipes that may generate a poison value that is
653   /// used after vectorization, even when their operands are not poison. Those
654   /// recipes meet the following conditions:
655   ///  * Contribute to the address computation of a recipe generating a widen
656   ///    memory load/store (VPWidenMemoryInstructionRecipe or
657   ///    VPInterleaveRecipe).
658   ///  * Such a widen memory load/store has at least one underlying Instruction
659   ///    that is in a basic block that needs predication and after vectorization
660   ///    the generated instruction won't be predicated.
661   void collectPoisonGeneratingRecipes(VPTransformState &State);
662 
663   /// Allow subclasses to override and print debug traces before/after vplan
664   /// execution, when trace information is requested.
665   virtual void printDebugTracesAtStart(){};
666   virtual void printDebugTracesAtEnd(){};
667 
668   /// The original loop.
669   Loop *OrigLoop;
670 
671   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
672   /// dynamic knowledge to simplify SCEV expressions and converts them to a
673   /// more usable form.
674   PredicatedScalarEvolution &PSE;
675 
676   /// Loop Info.
677   LoopInfo *LI;
678 
679   /// Dominator Tree.
680   DominatorTree *DT;
681 
682   /// Alias Analysis.
683   AAResults *AA;
684 
685   /// Target Library Info.
686   const TargetLibraryInfo *TLI;
687 
688   /// Target Transform Info.
689   const TargetTransformInfo *TTI;
690 
691   /// Assumption Cache.
692   AssumptionCache *AC;
693 
694   /// Interface to emit optimization remarks.
695   OptimizationRemarkEmitter *ORE;
696 
697   /// LoopVersioning.  It's only set up (non-null) if memchecks were
698   /// used.
699   ///
700   /// This is currently only used to add no-alias metadata based on the
701   /// memchecks.  The actually versioning is performed manually.
702   std::unique_ptr<LoopVersioning> LVer;
703 
704   /// The vectorization SIMD factor to use. Each vector will have this many
705   /// vector elements.
706   ElementCount VF;
707 
708   /// The vectorization unroll factor to use. Each scalar is vectorized to this
709   /// many different vector instructions.
710   unsigned UF;
711 
712   /// The builder that we use
713   IRBuilder<> Builder;
714 
715   // --- Vectorization state ---
716 
717   /// The vector-loop preheader.
718   BasicBlock *LoopVectorPreHeader;
719 
720   /// The scalar-loop preheader.
721   BasicBlock *LoopScalarPreHeader;
722 
723   /// Middle Block between the vector and the scalar.
724   BasicBlock *LoopMiddleBlock;
725 
726   /// The unique ExitBlock of the scalar loop if one exists.  Note that
727   /// there can be multiple exiting edges reaching this block.
728   BasicBlock *LoopExitBlock;
729 
730   /// The scalar loop body.
731   BasicBlock *LoopScalarBody;
732 
733   /// A list of all bypass blocks. The first block is the entry of the loop.
734   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
735 
736   /// Store instructions that were predicated.
737   SmallVector<Instruction *, 4> PredicatedInstructions;
738 
739   /// Trip count of the original loop.
740   Value *TripCount = nullptr;
741 
742   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
743   Value *VectorTripCount = nullptr;
744 
745   /// The legality analysis.
746   LoopVectorizationLegality *Legal;
747 
748   /// The profitablity analysis.
749   LoopVectorizationCostModel *Cost;
750 
751   // Record whether runtime checks are added.
752   bool AddedSafetyChecks = false;
753 
754   // Holds the end values for each induction variable. We save the end values
755   // so we can later fix-up the external users of the induction variables.
756   DenseMap<PHINode *, Value *> IVEndValues;
757 
758   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
759   // fixed up at the end of vector code generation.
760   SmallVector<PHINode *, 8> OrigPHIsToFix;
761 
762   /// BFI and PSI are used to check for profile guided size optimizations.
763   BlockFrequencyInfo *BFI;
764   ProfileSummaryInfo *PSI;
765 
766   // Whether this loop should be optimized for size based on profile guided size
767   // optimizatios.
768   bool OptForSizeBasedOnProfile;
769 
770   /// Structure to hold information about generated runtime checks, responsible
771   /// for cleaning the checks, if vectorization turns out unprofitable.
772   GeneratedRTChecks &RTChecks;
773 
774   // Holds the resume values for reductions in the loops, used to set the
775   // correct start value of reduction PHIs when vectorizing the epilogue.
776   SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
777       ReductionResumeValues;
778 };
779 
780 class InnerLoopUnroller : public InnerLoopVectorizer {
781 public:
782   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
783                     LoopInfo *LI, DominatorTree *DT,
784                     const TargetLibraryInfo *TLI,
785                     const TargetTransformInfo *TTI, AssumptionCache *AC,
786                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
787                     LoopVectorizationLegality *LVL,
788                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
789                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
790       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
791                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
792                             BFI, PSI, Check) {}
793 
794 private:
795   Value *getBroadcastInstrs(Value *V) override;
796 };
797 
798 /// Encapsulate information regarding vectorization of a loop and its epilogue.
799 /// This information is meant to be updated and used across two stages of
800 /// epilogue vectorization.
801 struct EpilogueLoopVectorizationInfo {
802   ElementCount MainLoopVF = ElementCount::getFixed(0);
803   unsigned MainLoopUF = 0;
804   ElementCount EpilogueVF = ElementCount::getFixed(0);
805   unsigned EpilogueUF = 0;
806   BasicBlock *MainLoopIterationCountCheck = nullptr;
807   BasicBlock *EpilogueIterationCountCheck = nullptr;
808   BasicBlock *SCEVSafetyCheck = nullptr;
809   BasicBlock *MemSafetyCheck = nullptr;
810   Value *TripCount = nullptr;
811   Value *VectorTripCount = nullptr;
812 
813   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
814                                 ElementCount EVF, unsigned EUF)
815       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
816     assert(EUF == 1 &&
817            "A high UF for the epilogue loop is likely not beneficial.");
818   }
819 };
820 
821 /// An extension of the inner loop vectorizer that creates a skeleton for a
822 /// vectorized loop that has its epilogue (residual) also vectorized.
823 /// The idea is to run the vplan on a given loop twice, firstly to setup the
824 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
825 /// from the first step and vectorize the epilogue.  This is achieved by
826 /// deriving two concrete strategy classes from this base class and invoking
827 /// them in succession from the loop vectorizer planner.
828 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
829 public:
830   InnerLoopAndEpilogueVectorizer(
831       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
832       DominatorTree *DT, const TargetLibraryInfo *TLI,
833       const TargetTransformInfo *TTI, AssumptionCache *AC,
834       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
835       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
836       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
837       GeneratedRTChecks &Checks)
838       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
839                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
840                             Checks),
841         EPI(EPI) {}
842 
843   // Override this function to handle the more complex control flow around the
844   // three loops.
845   std::pair<BasicBlock *, Value *>
846   createVectorizedLoopSkeleton() final override {
847     return createEpilogueVectorizedLoopSkeleton();
848   }
849 
850   /// The interface for creating a vectorized skeleton using one of two
851   /// different strategies, each corresponding to one execution of the vplan
852   /// as described above.
853   virtual std::pair<BasicBlock *, Value *>
854   createEpilogueVectorizedLoopSkeleton() = 0;
855 
856   /// Holds and updates state information required to vectorize the main loop
857   /// and its epilogue in two separate passes. This setup helps us avoid
858   /// regenerating and recomputing runtime safety checks. It also helps us to
859   /// shorten the iteration-count-check path length for the cases where the
860   /// iteration count of the loop is so small that the main vector loop is
861   /// completely skipped.
862   EpilogueLoopVectorizationInfo &EPI;
863 };
864 
865 /// A specialized derived class of inner loop vectorizer that performs
866 /// vectorization of *main* loops in the process of vectorizing loops and their
867 /// epilogues.
868 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
869 public:
870   EpilogueVectorizerMainLoop(
871       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
872       DominatorTree *DT, const TargetLibraryInfo *TLI,
873       const TargetTransformInfo *TTI, AssumptionCache *AC,
874       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
875       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
876       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
877       GeneratedRTChecks &Check)
878       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
879                                        EPI, LVL, CM, BFI, PSI, Check) {}
880   /// Implements the interface for creating a vectorized skeleton using the
881   /// *main loop* strategy (ie the first pass of vplan execution).
882   std::pair<BasicBlock *, Value *>
883   createEpilogueVectorizedLoopSkeleton() final override;
884 
885 protected:
886   /// Emits an iteration count bypass check once for the main loop (when \p
887   /// ForEpilogue is false) and once for the epilogue loop (when \p
888   /// ForEpilogue is true).
889   BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
890   void printDebugTracesAtStart() override;
891   void printDebugTracesAtEnd() override;
892 };
893 
894 // A specialized derived class of inner loop vectorizer that performs
895 // vectorization of *epilogue* loops in the process of vectorizing loops and
896 // their epilogues.
897 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
898 public:
899   EpilogueVectorizerEpilogueLoop(
900       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
901       DominatorTree *DT, const TargetLibraryInfo *TLI,
902       const TargetTransformInfo *TTI, AssumptionCache *AC,
903       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
904       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
905       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
906       GeneratedRTChecks &Checks)
907       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
908                                        EPI, LVL, CM, BFI, PSI, Checks) {
909     TripCount = EPI.TripCount;
910   }
911   /// Implements the interface for creating a vectorized skeleton using the
912   /// *epilogue loop* strategy (ie the second pass of vplan execution).
913   std::pair<BasicBlock *, Value *>
914   createEpilogueVectorizedLoopSkeleton() final override;
915 
916 protected:
917   /// Emits an iteration count bypass check after the main vector loop has
918   /// finished to see if there are any iterations left to execute by either
919   /// the vector epilogue or the scalar epilogue.
920   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
921                                                       BasicBlock *Bypass,
922                                                       BasicBlock *Insert);
923   void printDebugTracesAtStart() override;
924   void printDebugTracesAtEnd() override;
925 };
926 } // end namespace llvm
927 
928 /// Look for a meaningful debug location on the instruction or it's
929 /// operands.
930 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
931   if (!I)
932     return I;
933 
934   DebugLoc Empty;
935   if (I->getDebugLoc() != Empty)
936     return I;
937 
938   for (Use &Op : I->operands()) {
939     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
940       if (OpInst->getDebugLoc() != Empty)
941         return OpInst;
942   }
943 
944   return I;
945 }
946 
947 void InnerLoopVectorizer::setDebugLocFromInst(
948     const Value *V, Optional<IRBuilderBase *> CustomBuilder) {
949   IRBuilderBase *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
950   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
951     const DILocation *DIL = Inst->getDebugLoc();
952 
953     // When a FSDiscriminator is enabled, we don't need to add the multiply
954     // factors to the discriminators.
955     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
956         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
957       // FIXME: For scalable vectors, assume vscale=1.
958       auto NewDIL =
959           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
960       if (NewDIL)
961         B->SetCurrentDebugLocation(NewDIL.getValue());
962       else
963         LLVM_DEBUG(dbgs()
964                    << "Failed to create new discriminator: "
965                    << DIL->getFilename() << " Line: " << DIL->getLine());
966     } else
967       B->SetCurrentDebugLocation(DIL);
968   } else
969     B->SetCurrentDebugLocation(DebugLoc());
970 }
971 
972 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
973 /// is passed, the message relates to that particular instruction.
974 #ifndef NDEBUG
975 static void debugVectorizationMessage(const StringRef Prefix,
976                                       const StringRef DebugMsg,
977                                       Instruction *I) {
978   dbgs() << "LV: " << Prefix << DebugMsg;
979   if (I != nullptr)
980     dbgs() << " " << *I;
981   else
982     dbgs() << '.';
983   dbgs() << '\n';
984 }
985 #endif
986 
987 /// Create an analysis remark that explains why vectorization failed
988 ///
989 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
990 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
991 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
992 /// the location of the remark.  \return the remark object that can be
993 /// streamed to.
994 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
995     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
996   Value *CodeRegion = TheLoop->getHeader();
997   DebugLoc DL = TheLoop->getStartLoc();
998 
999   if (I) {
1000     CodeRegion = I->getParent();
1001     // If there is no debug location attached to the instruction, revert back to
1002     // using the loop's.
1003     if (I->getDebugLoc())
1004       DL = I->getDebugLoc();
1005   }
1006 
1007   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1008 }
1009 
1010 namespace llvm {
1011 
1012 /// Return a value for Step multiplied by VF.
1013 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
1014                        int64_t Step) {
1015   assert(Ty->isIntegerTy() && "Expected an integer step");
1016   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
1017   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1018 }
1019 
1020 /// Return the runtime value for VF.
1021 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF) {
1022   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1023   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1024 }
1025 
1026 static Value *getRuntimeVFAsFloat(IRBuilderBase &B, Type *FTy,
1027                                   ElementCount VF) {
1028   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1029   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1030   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1031   return B.CreateUIToFP(RuntimeVF, FTy);
1032 }
1033 
1034 void reportVectorizationFailure(const StringRef DebugMsg,
1035                                 const StringRef OREMsg, const StringRef ORETag,
1036                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1037                                 Instruction *I) {
1038   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1039   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1040   ORE->emit(
1041       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1042       << "loop not vectorized: " << OREMsg);
1043 }
1044 
1045 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1046                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1047                              Instruction *I) {
1048   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1049   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1050   ORE->emit(
1051       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1052       << Msg);
1053 }
1054 
1055 } // end namespace llvm
1056 
1057 #ifndef NDEBUG
1058 /// \return string containing a file name and a line # for the given loop.
1059 static std::string getDebugLocString(const Loop *L) {
1060   std::string Result;
1061   if (L) {
1062     raw_string_ostream OS(Result);
1063     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1064       LoopDbgLoc.print(OS);
1065     else
1066       // Just print the module name.
1067       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1068     OS.flush();
1069   }
1070   return Result;
1071 }
1072 #endif
1073 
1074 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1075                                          const Instruction *Orig) {
1076   // If the loop was versioned with memchecks, add the corresponding no-alias
1077   // metadata.
1078   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1079     LVer->annotateInstWithNoAlias(To, Orig);
1080 }
1081 
1082 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1083     VPTransformState &State) {
1084 
1085   // Collect recipes in the backward slice of `Root` that may generate a poison
1086   // value that is used after vectorization.
1087   SmallPtrSet<VPRecipeBase *, 16> Visited;
1088   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1089     SmallVector<VPRecipeBase *, 16> Worklist;
1090     Worklist.push_back(Root);
1091 
1092     // Traverse the backward slice of Root through its use-def chain.
1093     while (!Worklist.empty()) {
1094       VPRecipeBase *CurRec = Worklist.back();
1095       Worklist.pop_back();
1096 
1097       if (!Visited.insert(CurRec).second)
1098         continue;
1099 
1100       // Prune search if we find another recipe generating a widen memory
1101       // instruction. Widen memory instructions involved in address computation
1102       // will lead to gather/scatter instructions, which don't need to be
1103       // handled.
1104       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1105           isa<VPInterleaveRecipe>(CurRec) ||
1106           isa<VPScalarIVStepsRecipe>(CurRec) ||
1107           isa<VPCanonicalIVPHIRecipe>(CurRec))
1108         continue;
1109 
1110       // This recipe contributes to the address computation of a widen
1111       // load/store. Collect recipe if its underlying instruction has
1112       // poison-generating flags.
1113       Instruction *Instr = CurRec->getUnderlyingInstr();
1114       if (Instr && Instr->hasPoisonGeneratingFlags())
1115         State.MayGeneratePoisonRecipes.insert(CurRec);
1116 
1117       // Add new definitions to the worklist.
1118       for (VPValue *operand : CurRec->operands())
1119         if (VPDef *OpDef = operand->getDef())
1120           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1121     }
1122   });
1123 
1124   // Traverse all the recipes in the VPlan and collect the poison-generating
1125   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1126   // VPInterleaveRecipe.
1127   auto Iter = depth_first(
1128       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1129   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1130     for (VPRecipeBase &Recipe : *VPBB) {
1131       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1132         Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
1133         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1134         if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
1135             Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
1136           collectPoisonGeneratingInstrsInBackwardSlice(
1137               cast<VPRecipeBase>(AddrDef));
1138       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1139         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1140         if (AddrDef) {
1141           // Check if any member of the interleave group needs predication.
1142           const InterleaveGroup<Instruction> *InterGroup =
1143               InterleaveRec->getInterleaveGroup();
1144           bool NeedPredication = false;
1145           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1146                I < NumMembers; ++I) {
1147             Instruction *Member = InterGroup->getMember(I);
1148             if (Member)
1149               NeedPredication |=
1150                   Legal->blockNeedsPredication(Member->getParent());
1151           }
1152 
1153           if (NeedPredication)
1154             collectPoisonGeneratingInstrsInBackwardSlice(
1155                 cast<VPRecipeBase>(AddrDef));
1156         }
1157       }
1158     }
1159   }
1160 }
1161 
1162 void InnerLoopVectorizer::addMetadata(Instruction *To,
1163                                       Instruction *From) {
1164   propagateMetadata(To, From);
1165   addNewMetadata(To, From);
1166 }
1167 
1168 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1169                                       Instruction *From) {
1170   for (Value *V : To) {
1171     if (Instruction *I = dyn_cast<Instruction>(V))
1172       addMetadata(I, From);
1173   }
1174 }
1175 
1176 PHINode *InnerLoopVectorizer::getReductionResumeValue(
1177     const RecurrenceDescriptor &RdxDesc) {
1178   auto It = ReductionResumeValues.find(&RdxDesc);
1179   assert(It != ReductionResumeValues.end() &&
1180          "Expected to find a resume value for the reduction.");
1181   return It->second;
1182 }
1183 
1184 namespace llvm {
1185 
1186 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1187 // lowered.
1188 enum ScalarEpilogueLowering {
1189 
1190   // The default: allowing scalar epilogues.
1191   CM_ScalarEpilogueAllowed,
1192 
1193   // Vectorization with OptForSize: don't allow epilogues.
1194   CM_ScalarEpilogueNotAllowedOptSize,
1195 
1196   // A special case of vectorisation with OptForSize: loops with a very small
1197   // trip count are considered for vectorization under OptForSize, thereby
1198   // making sure the cost of their loop body is dominant, free of runtime
1199   // guards and scalar iteration overheads.
1200   CM_ScalarEpilogueNotAllowedLowTripLoop,
1201 
1202   // Loop hint predicate indicating an epilogue is undesired.
1203   CM_ScalarEpilogueNotNeededUsePredicate,
1204 
1205   // Directive indicating we must either tail fold or not vectorize
1206   CM_ScalarEpilogueNotAllowedUsePredicate
1207 };
1208 
1209 /// ElementCountComparator creates a total ordering for ElementCount
1210 /// for the purposes of using it in a set structure.
1211 struct ElementCountComparator {
1212   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1213     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1214            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1215   }
1216 };
1217 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1218 
1219 /// LoopVectorizationCostModel - estimates the expected speedups due to
1220 /// vectorization.
1221 /// In many cases vectorization is not profitable. This can happen because of
1222 /// a number of reasons. In this class we mainly attempt to predict the
1223 /// expected speedup/slowdowns due to the supported instruction set. We use the
1224 /// TargetTransformInfo to query the different backends for the cost of
1225 /// different operations.
1226 class LoopVectorizationCostModel {
1227 public:
1228   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1229                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1230                              LoopVectorizationLegality *Legal,
1231                              const TargetTransformInfo &TTI,
1232                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1233                              AssumptionCache *AC,
1234                              OptimizationRemarkEmitter *ORE, const Function *F,
1235                              const LoopVectorizeHints *Hints,
1236                              InterleavedAccessInfo &IAI)
1237       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1238         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1239         Hints(Hints), InterleaveInfo(IAI) {}
1240 
1241   /// \return An upper bound for the vectorization factors (both fixed and
1242   /// scalable). If the factors are 0, vectorization and interleaving should be
1243   /// avoided up front.
1244   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1245 
1246   /// \return True if runtime checks are required for vectorization, and false
1247   /// otherwise.
1248   bool runtimeChecksRequired();
1249 
1250   /// \return The most profitable vectorization factor and the cost of that VF.
1251   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1252   /// then this vectorization factor will be selected if vectorization is
1253   /// possible.
1254   VectorizationFactor
1255   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1256 
1257   VectorizationFactor
1258   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1259                                     const LoopVectorizationPlanner &LVP);
1260 
1261   /// Setup cost-based decisions for user vectorization factor.
1262   /// \return true if the UserVF is a feasible VF to be chosen.
1263   bool selectUserVectorizationFactor(ElementCount UserVF) {
1264     collectUniformsAndScalars(UserVF);
1265     collectInstsToScalarize(UserVF);
1266     return expectedCost(UserVF).first.isValid();
1267   }
1268 
1269   /// \return The size (in bits) of the smallest and widest types in the code
1270   /// that needs to be vectorized. We ignore values that remain scalar such as
1271   /// 64 bit loop indices.
1272   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1273 
1274   /// \return The desired interleave count.
1275   /// If interleave count has been specified by metadata it will be returned.
1276   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1277   /// are the selected vectorization factor and the cost of the selected VF.
1278   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1279 
1280   /// Memory access instruction may be vectorized in more than one way.
1281   /// Form of instruction after vectorization depends on cost.
1282   /// This function takes cost-based decisions for Load/Store instructions
1283   /// and collects them in a map. This decisions map is used for building
1284   /// the lists of loop-uniform and loop-scalar instructions.
1285   /// The calculated cost is saved with widening decision in order to
1286   /// avoid redundant calculations.
1287   void setCostBasedWideningDecision(ElementCount VF);
1288 
1289   /// A struct that represents some properties of the register usage
1290   /// of a loop.
1291   struct RegisterUsage {
1292     /// Holds the number of loop invariant values that are used in the loop.
1293     /// The key is ClassID of target-provided register class.
1294     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1295     /// Holds the maximum number of concurrent live intervals in the loop.
1296     /// The key is ClassID of target-provided register class.
1297     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1298   };
1299 
1300   /// \return Returns information about the register usages of the loop for the
1301   /// given vectorization factors.
1302   SmallVector<RegisterUsage, 8>
1303   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1304 
1305   /// Collect values we want to ignore in the cost model.
1306   void collectValuesToIgnore();
1307 
1308   /// Collect all element types in the loop for which widening is needed.
1309   void collectElementTypesForWidening();
1310 
1311   /// Split reductions into those that happen in the loop, and those that happen
1312   /// outside. In loop reductions are collected into InLoopReductionChains.
1313   void collectInLoopReductions();
1314 
1315   /// Returns true if we should use strict in-order reductions for the given
1316   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1317   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1318   /// of FP operations.
1319   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1320     return !Hints->allowReordering() && RdxDesc.isOrdered();
1321   }
1322 
1323   /// \returns The smallest bitwidth each instruction can be represented with.
1324   /// The vector equivalents of these instructions should be truncated to this
1325   /// type.
1326   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1327     return MinBWs;
1328   }
1329 
1330   /// \returns True if it is more profitable to scalarize instruction \p I for
1331   /// vectorization factor \p VF.
1332   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1333     assert(VF.isVector() &&
1334            "Profitable to scalarize relevant only for VF > 1.");
1335 
1336     // Cost model is not run in the VPlan-native path - return conservative
1337     // result until this changes.
1338     if (EnableVPlanNativePath)
1339       return false;
1340 
1341     auto Scalars = InstsToScalarize.find(VF);
1342     assert(Scalars != InstsToScalarize.end() &&
1343            "VF not yet analyzed for scalarization profitability");
1344     return Scalars->second.find(I) != Scalars->second.end();
1345   }
1346 
1347   /// Returns true if \p I is known to be uniform after vectorization.
1348   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1349     if (VF.isScalar())
1350       return true;
1351 
1352     // Cost model is not run in the VPlan-native path - return conservative
1353     // result until this changes.
1354     if (EnableVPlanNativePath)
1355       return false;
1356 
1357     auto UniformsPerVF = Uniforms.find(VF);
1358     assert(UniformsPerVF != Uniforms.end() &&
1359            "VF not yet analyzed for uniformity");
1360     return UniformsPerVF->second.count(I);
1361   }
1362 
1363   /// Returns true if \p I is known to be scalar after vectorization.
1364   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1365     if (VF.isScalar())
1366       return true;
1367 
1368     // Cost model is not run in the VPlan-native path - return conservative
1369     // result until this changes.
1370     if (EnableVPlanNativePath)
1371       return false;
1372 
1373     auto ScalarsPerVF = Scalars.find(VF);
1374     assert(ScalarsPerVF != Scalars.end() &&
1375            "Scalar values are not calculated for VF");
1376     return ScalarsPerVF->second.count(I);
1377   }
1378 
1379   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1380   /// for vectorization factor \p VF.
1381   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1382     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1383            !isProfitableToScalarize(I, VF) &&
1384            !isScalarAfterVectorization(I, VF);
1385   }
1386 
1387   /// Decision that was taken during cost calculation for memory instruction.
1388   enum InstWidening {
1389     CM_Unknown,
1390     CM_Widen,         // For consecutive accesses with stride +1.
1391     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1392     CM_Interleave,
1393     CM_GatherScatter,
1394     CM_Scalarize
1395   };
1396 
1397   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1398   /// instruction \p I and vector width \p VF.
1399   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1400                            InstructionCost Cost) {
1401     assert(VF.isVector() && "Expected VF >=2");
1402     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1403   }
1404 
1405   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1406   /// interleaving group \p Grp and vector width \p VF.
1407   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1408                            ElementCount VF, InstWidening W,
1409                            InstructionCost Cost) {
1410     assert(VF.isVector() && "Expected VF >=2");
1411     /// Broadcast this decicion to all instructions inside the group.
1412     /// But the cost will be assigned to one instruction only.
1413     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1414       if (auto *I = Grp->getMember(i)) {
1415         if (Grp->getInsertPos() == I)
1416           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1417         else
1418           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1419       }
1420     }
1421   }
1422 
1423   /// Return the cost model decision for the given instruction \p I and vector
1424   /// width \p VF. Return CM_Unknown if this instruction did not pass
1425   /// through the cost modeling.
1426   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1427     assert(VF.isVector() && "Expected VF to be a vector VF");
1428     // Cost model is not run in the VPlan-native path - return conservative
1429     // result until this changes.
1430     if (EnableVPlanNativePath)
1431       return CM_GatherScatter;
1432 
1433     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1434     auto Itr = WideningDecisions.find(InstOnVF);
1435     if (Itr == WideningDecisions.end())
1436       return CM_Unknown;
1437     return Itr->second.first;
1438   }
1439 
1440   /// Return the vectorization cost for the given instruction \p I and vector
1441   /// width \p VF.
1442   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1443     assert(VF.isVector() && "Expected VF >=2");
1444     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1445     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1446            "The cost is not calculated");
1447     return WideningDecisions[InstOnVF].second;
1448   }
1449 
1450   /// Return True if instruction \p I is an optimizable truncate whose operand
1451   /// is an induction variable. Such a truncate will be removed by adding a new
1452   /// induction variable with the destination type.
1453   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1454     // If the instruction is not a truncate, return false.
1455     auto *Trunc = dyn_cast<TruncInst>(I);
1456     if (!Trunc)
1457       return false;
1458 
1459     // Get the source and destination types of the truncate.
1460     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1461     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1462 
1463     // If the truncate is free for the given types, return false. Replacing a
1464     // free truncate with an induction variable would add an induction variable
1465     // update instruction to each iteration of the loop. We exclude from this
1466     // check the primary induction variable since it will need an update
1467     // instruction regardless.
1468     Value *Op = Trunc->getOperand(0);
1469     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1470       return false;
1471 
1472     // If the truncated value is not an induction variable, return false.
1473     return Legal->isInductionPhi(Op);
1474   }
1475 
1476   /// Collects the instructions to scalarize for each predicated instruction in
1477   /// the loop.
1478   void collectInstsToScalarize(ElementCount VF);
1479 
1480   /// Collect Uniform and Scalar values for the given \p VF.
1481   /// The sets depend on CM decision for Load/Store instructions
1482   /// that may be vectorized as interleave, gather-scatter or scalarized.
1483   void collectUniformsAndScalars(ElementCount VF) {
1484     // Do the analysis once.
1485     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1486       return;
1487     setCostBasedWideningDecision(VF);
1488     collectLoopUniforms(VF);
1489     collectLoopScalars(VF);
1490   }
1491 
1492   /// Returns true if the target machine supports masked store operation
1493   /// for the given \p DataType and kind of access to \p Ptr.
1494   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1495     return Legal->isConsecutivePtr(DataType, Ptr) &&
1496            TTI.isLegalMaskedStore(DataType, Alignment);
1497   }
1498 
1499   /// Returns true if the target machine supports masked load operation
1500   /// for the given \p DataType and kind of access to \p Ptr.
1501   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1502     return Legal->isConsecutivePtr(DataType, Ptr) &&
1503            TTI.isLegalMaskedLoad(DataType, Alignment);
1504   }
1505 
1506   /// Returns true if the target machine can represent \p V as a masked gather
1507   /// or scatter operation.
1508   bool isLegalGatherOrScatter(Value *V,
1509                               ElementCount VF = ElementCount::getFixed(1)) {
1510     bool LI = isa<LoadInst>(V);
1511     bool SI = isa<StoreInst>(V);
1512     if (!LI && !SI)
1513       return false;
1514     auto *Ty = getLoadStoreType(V);
1515     Align Align = getLoadStoreAlignment(V);
1516     if (VF.isVector())
1517       Ty = VectorType::get(Ty, VF);
1518     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1519            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1520   }
1521 
1522   /// Returns true if the target machine supports all of the reduction
1523   /// variables found for the given VF.
1524   bool canVectorizeReductions(ElementCount VF) const {
1525     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1526       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1527       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1528     }));
1529   }
1530 
1531   /// Returns true if \p I is an instruction that will be scalarized with
1532   /// predication when vectorizing \p I with vectorization factor \p VF. Such
1533   /// instructions include conditional stores and instructions that may divide
1534   /// by zero.
1535   bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1536 
1537   // Returns true if \p I is an instruction that will be predicated either
1538   // through scalar predication or masked load/store or masked gather/scatter.
1539   // \p VF is the vectorization factor that will be used to vectorize \p I.
1540   // Superset of instructions that return true for isScalarWithPredication.
1541   bool isPredicatedInst(Instruction *I, ElementCount VF,
1542                         bool IsKnownUniform = false) {
1543     // When we know the load is uniform and the original scalar loop was not
1544     // predicated we don't need to mark it as a predicated instruction. Any
1545     // vectorised blocks created when tail-folding are something artificial we
1546     // have introduced and we know there is always at least one active lane.
1547     // That's why we call Legal->blockNeedsPredication here because it doesn't
1548     // query tail-folding.
1549     if (IsKnownUniform && isa<LoadInst>(I) &&
1550         !Legal->blockNeedsPredication(I->getParent()))
1551       return false;
1552     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1553       return false;
1554     // Loads and stores that need some form of masked operation are predicated
1555     // instructions.
1556     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1557       return Legal->isMaskRequired(I);
1558     return isScalarWithPredication(I, VF);
1559   }
1560 
1561   /// Returns true if \p I is a memory instruction with consecutive memory
1562   /// access that can be widened.
1563   bool
1564   memoryInstructionCanBeWidened(Instruction *I,
1565                                 ElementCount VF = ElementCount::getFixed(1));
1566 
1567   /// Returns true if \p I is a memory instruction in an interleaved-group
1568   /// of memory accesses that can be vectorized with wide vector loads/stores
1569   /// and shuffles.
1570   bool
1571   interleavedAccessCanBeWidened(Instruction *I,
1572                                 ElementCount VF = ElementCount::getFixed(1));
1573 
1574   /// Check if \p Instr belongs to any interleaved access group.
1575   bool isAccessInterleaved(Instruction *Instr) {
1576     return InterleaveInfo.isInterleaved(Instr);
1577   }
1578 
1579   /// Get the interleaved access group that \p Instr belongs to.
1580   const InterleaveGroup<Instruction> *
1581   getInterleavedAccessGroup(Instruction *Instr) {
1582     return InterleaveInfo.getInterleaveGroup(Instr);
1583   }
1584 
1585   /// Returns true if we're required to use a scalar epilogue for at least
1586   /// the final iteration of the original loop.
1587   bool requiresScalarEpilogue(ElementCount VF) const {
1588     if (!isScalarEpilogueAllowed())
1589       return false;
1590     // If we might exit from anywhere but the latch, must run the exiting
1591     // iteration in scalar form.
1592     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1593       return true;
1594     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1595   }
1596 
1597   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1598   /// loop hint annotation.
1599   bool isScalarEpilogueAllowed() const {
1600     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1601   }
1602 
1603   /// Returns true if all loop blocks should be masked to fold tail loop.
1604   bool foldTailByMasking() const { return FoldTailByMasking; }
1605 
1606   /// Returns true if the instructions in this block requires predication
1607   /// for any reason, e.g. because tail folding now requires a predicate
1608   /// or because the block in the original loop was predicated.
1609   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1610     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1611   }
1612 
1613   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1614   /// nodes to the chain of instructions representing the reductions. Uses a
1615   /// MapVector to ensure deterministic iteration order.
1616   using ReductionChainMap =
1617       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1618 
1619   /// Return the chain of instructions representing an inloop reduction.
1620   const ReductionChainMap &getInLoopReductionChains() const {
1621     return InLoopReductionChains;
1622   }
1623 
1624   /// Returns true if the Phi is part of an inloop reduction.
1625   bool isInLoopReduction(PHINode *Phi) const {
1626     return InLoopReductionChains.count(Phi);
1627   }
1628 
1629   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1630   /// with factor VF.  Return the cost of the instruction, including
1631   /// scalarization overhead if it's needed.
1632   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1633 
1634   /// Estimate cost of a call instruction CI if it were vectorized with factor
1635   /// VF. Return the cost of the instruction, including scalarization overhead
1636   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1637   /// scalarized -
1638   /// i.e. either vector version isn't available, or is too expensive.
1639   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1640                                     bool &NeedToScalarize) const;
1641 
1642   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1643   /// that of B.
1644   bool isMoreProfitable(const VectorizationFactor &A,
1645                         const VectorizationFactor &B) const;
1646 
1647   /// Invalidates decisions already taken by the cost model.
1648   void invalidateCostModelingDecisions() {
1649     WideningDecisions.clear();
1650     Uniforms.clear();
1651     Scalars.clear();
1652   }
1653 
1654 private:
1655   unsigned NumPredStores = 0;
1656 
1657   /// Convenience function that returns the value of vscale_range iff
1658   /// vscale_range.min == vscale_range.max or otherwise returns the value
1659   /// returned by the corresponding TLI method.
1660   Optional<unsigned> getVScaleForTuning() const;
1661 
1662   /// \return An upper bound for the vectorization factors for both
1663   /// fixed and scalable vectorization, where the minimum-known number of
1664   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1665   /// disabled or unsupported, then the scalable part will be equal to
1666   /// ElementCount::getScalable(0).
1667   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1668                                            ElementCount UserVF,
1669                                            bool FoldTailByMasking);
1670 
1671   /// \return the maximized element count based on the targets vector
1672   /// registers and the loop trip-count, but limited to a maximum safe VF.
1673   /// This is a helper function of computeFeasibleMaxVF.
1674   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1675   /// issue that occurred on one of the buildbots which cannot be reproduced
1676   /// without having access to the properietary compiler (see comments on
1677   /// D98509). The issue is currently under investigation and this workaround
1678   /// will be removed as soon as possible.
1679   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1680                                        unsigned SmallestType,
1681                                        unsigned WidestType,
1682                                        const ElementCount &MaxSafeVF,
1683                                        bool FoldTailByMasking);
1684 
1685   /// \return the maximum legal scalable VF, based on the safe max number
1686   /// of elements.
1687   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1688 
1689   /// The vectorization cost is a combination of the cost itself and a boolean
1690   /// indicating whether any of the contributing operations will actually
1691   /// operate on vector values after type legalization in the backend. If this
1692   /// latter value is false, then all operations will be scalarized (i.e. no
1693   /// vectorization has actually taken place).
1694   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1695 
1696   /// Returns the expected execution cost. The unit of the cost does
1697   /// not matter because we use the 'cost' units to compare different
1698   /// vector widths. The cost that is returned is *not* normalized by
1699   /// the factor width. If \p Invalid is not nullptr, this function
1700   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1701   /// each instruction that has an Invalid cost for the given VF.
1702   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1703   VectorizationCostTy
1704   expectedCost(ElementCount VF,
1705                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1706 
1707   /// Returns the execution time cost of an instruction for a given vector
1708   /// width. Vector width of one means scalar.
1709   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1710 
1711   /// The cost-computation logic from getInstructionCost which provides
1712   /// the vector type as an output parameter.
1713   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1714                                      Type *&VectorTy);
1715 
1716   /// Return the cost of instructions in an inloop reduction pattern, if I is
1717   /// part of that pattern.
1718   Optional<InstructionCost>
1719   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1720                           TTI::TargetCostKind CostKind);
1721 
1722   /// Calculate vectorization cost of memory instruction \p I.
1723   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1724 
1725   /// The cost computation for scalarized memory instruction.
1726   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1727 
1728   /// The cost computation for interleaving group of memory instructions.
1729   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1730 
1731   /// The cost computation for Gather/Scatter instruction.
1732   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1733 
1734   /// The cost computation for widening instruction \p I with consecutive
1735   /// memory access.
1736   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1737 
1738   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1739   /// Load: scalar load + broadcast.
1740   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1741   /// element)
1742   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1743 
1744   /// Estimate the overhead of scalarizing an instruction. This is a
1745   /// convenience wrapper for the type-based getScalarizationOverhead API.
1746   InstructionCost getScalarizationOverhead(Instruction *I,
1747                                            ElementCount VF) const;
1748 
1749   /// Returns whether the instruction is a load or store and will be a emitted
1750   /// as a vector operation.
1751   bool isConsecutiveLoadOrStore(Instruction *I);
1752 
1753   /// Returns true if an artificially high cost for emulated masked memrefs
1754   /// should be used.
1755   bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1756 
1757   /// Map of scalar integer values to the smallest bitwidth they can be legally
1758   /// represented as. The vector equivalents of these values should be truncated
1759   /// to this type.
1760   MapVector<Instruction *, uint64_t> MinBWs;
1761 
1762   /// A type representing the costs for instructions if they were to be
1763   /// scalarized rather than vectorized. The entries are Instruction-Cost
1764   /// pairs.
1765   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1766 
1767   /// A set containing all BasicBlocks that are known to present after
1768   /// vectorization as a predicated block.
1769   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1770 
1771   /// Records whether it is allowed to have the original scalar loop execute at
1772   /// least once. This may be needed as a fallback loop in case runtime
1773   /// aliasing/dependence checks fail, or to handle the tail/remainder
1774   /// iterations when the trip count is unknown or doesn't divide by the VF,
1775   /// or as a peel-loop to handle gaps in interleave-groups.
1776   /// Under optsize and when the trip count is very small we don't allow any
1777   /// iterations to execute in the scalar loop.
1778   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1779 
1780   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1781   bool FoldTailByMasking = false;
1782 
1783   /// A map holding scalar costs for different vectorization factors. The
1784   /// presence of a cost for an instruction in the mapping indicates that the
1785   /// instruction will be scalarized when vectorizing with the associated
1786   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1787   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1788 
1789   /// Holds the instructions known to be uniform after vectorization.
1790   /// The data is collected per VF.
1791   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1792 
1793   /// Holds the instructions known to be scalar after vectorization.
1794   /// The data is collected per VF.
1795   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1796 
1797   /// Holds the instructions (address computations) that are forced to be
1798   /// scalarized.
1799   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1800 
1801   /// PHINodes of the reductions that should be expanded in-loop along with
1802   /// their associated chains of reduction operations, in program order from top
1803   /// (PHI) to bottom
1804   ReductionChainMap InLoopReductionChains;
1805 
1806   /// A Map of inloop reduction operations and their immediate chain operand.
1807   /// FIXME: This can be removed once reductions can be costed correctly in
1808   /// vplan. This was added to allow quick lookup to the inloop operations,
1809   /// without having to loop through InLoopReductionChains.
1810   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1811 
1812   /// Returns the expected difference in cost from scalarizing the expression
1813   /// feeding a predicated instruction \p PredInst. The instructions to
1814   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1815   /// non-negative return value implies the expression will be scalarized.
1816   /// Currently, only single-use chains are considered for scalarization.
1817   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1818                               ElementCount VF);
1819 
1820   /// Collect the instructions that are uniform after vectorization. An
1821   /// instruction is uniform if we represent it with a single scalar value in
1822   /// the vectorized loop corresponding to each vector iteration. Examples of
1823   /// uniform instructions include pointer operands of consecutive or
1824   /// interleaved memory accesses. Note that although uniformity implies an
1825   /// instruction will be scalar, the reverse is not true. In general, a
1826   /// scalarized instruction will be represented by VF scalar values in the
1827   /// vectorized loop, each corresponding to an iteration of the original
1828   /// scalar loop.
1829   void collectLoopUniforms(ElementCount VF);
1830 
1831   /// Collect the instructions that are scalar after vectorization. An
1832   /// instruction is scalar if it is known to be uniform or will be scalarized
1833   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1834   /// to the list if they are used by a load/store instruction that is marked as
1835   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1836   /// VF values in the vectorized loop, each corresponding to an iteration of
1837   /// the original scalar loop.
1838   void collectLoopScalars(ElementCount VF);
1839 
1840   /// Keeps cost model vectorization decision and cost for instructions.
1841   /// Right now it is used for memory instructions only.
1842   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1843                                 std::pair<InstWidening, InstructionCost>>;
1844 
1845   DecisionList WideningDecisions;
1846 
1847   /// Returns true if \p V is expected to be vectorized and it needs to be
1848   /// extracted.
1849   bool needsExtract(Value *V, ElementCount VF) const {
1850     Instruction *I = dyn_cast<Instruction>(V);
1851     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1852         TheLoop->isLoopInvariant(I))
1853       return false;
1854 
1855     // Assume we can vectorize V (and hence we need extraction) if the
1856     // scalars are not computed yet. This can happen, because it is called
1857     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1858     // the scalars are collected. That should be a safe assumption in most
1859     // cases, because we check if the operands have vectorizable types
1860     // beforehand in LoopVectorizationLegality.
1861     return Scalars.find(VF) == Scalars.end() ||
1862            !isScalarAfterVectorization(I, VF);
1863   };
1864 
1865   /// Returns a range containing only operands needing to be extracted.
1866   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1867                                                    ElementCount VF) const {
1868     return SmallVector<Value *, 4>(make_filter_range(
1869         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1870   }
1871 
1872   /// Determines if we have the infrastructure to vectorize loop \p L and its
1873   /// epilogue, assuming the main loop is vectorized by \p VF.
1874   bool isCandidateForEpilogueVectorization(const Loop &L,
1875                                            const ElementCount VF) const;
1876 
1877   /// Returns true if epilogue vectorization is considered profitable, and
1878   /// false otherwise.
1879   /// \p VF is the vectorization factor chosen for the original loop.
1880   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1881 
1882 public:
1883   /// The loop that we evaluate.
1884   Loop *TheLoop;
1885 
1886   /// Predicated scalar evolution analysis.
1887   PredicatedScalarEvolution &PSE;
1888 
1889   /// Loop Info analysis.
1890   LoopInfo *LI;
1891 
1892   /// Vectorization legality.
1893   LoopVectorizationLegality *Legal;
1894 
1895   /// Vector target information.
1896   const TargetTransformInfo &TTI;
1897 
1898   /// Target Library Info.
1899   const TargetLibraryInfo *TLI;
1900 
1901   /// Demanded bits analysis.
1902   DemandedBits *DB;
1903 
1904   /// Assumption cache.
1905   AssumptionCache *AC;
1906 
1907   /// Interface to emit optimization remarks.
1908   OptimizationRemarkEmitter *ORE;
1909 
1910   const Function *TheFunction;
1911 
1912   /// Loop Vectorize Hint.
1913   const LoopVectorizeHints *Hints;
1914 
1915   /// The interleave access information contains groups of interleaved accesses
1916   /// with the same stride and close to each other.
1917   InterleavedAccessInfo &InterleaveInfo;
1918 
1919   /// Values to ignore in the cost model.
1920   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1921 
1922   /// Values to ignore in the cost model when VF > 1.
1923   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1924 
1925   /// All element types found in the loop.
1926   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1927 
1928   /// Profitable vector factors.
1929   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1930 };
1931 } // end namespace llvm
1932 
1933 /// Helper struct to manage generating runtime checks for vectorization.
1934 ///
1935 /// The runtime checks are created up-front in temporary blocks to allow better
1936 /// estimating the cost and un-linked from the existing IR. After deciding to
1937 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1938 /// temporary blocks are completely removed.
1939 class GeneratedRTChecks {
1940   /// Basic block which contains the generated SCEV checks, if any.
1941   BasicBlock *SCEVCheckBlock = nullptr;
1942 
1943   /// The value representing the result of the generated SCEV checks. If it is
1944   /// nullptr, either no SCEV checks have been generated or they have been used.
1945   Value *SCEVCheckCond = nullptr;
1946 
1947   /// Basic block which contains the generated memory runtime checks, if any.
1948   BasicBlock *MemCheckBlock = nullptr;
1949 
1950   /// The value representing the result of the generated memory runtime checks.
1951   /// If it is nullptr, either no memory runtime checks have been generated or
1952   /// they have been used.
1953   Value *MemRuntimeCheckCond = nullptr;
1954 
1955   DominatorTree *DT;
1956   LoopInfo *LI;
1957 
1958   SCEVExpander SCEVExp;
1959   SCEVExpander MemCheckExp;
1960 
1961 public:
1962   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1963                     const DataLayout &DL)
1964       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1965         MemCheckExp(SE, DL, "scev.check") {}
1966 
1967   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1968   /// accurately estimate the cost of the runtime checks. The blocks are
1969   /// un-linked from the IR and is added back during vector code generation. If
1970   /// there is no vector code generation, the check blocks are removed
1971   /// completely.
1972   void Create(Loop *L, const LoopAccessInfo &LAI,
1973               const SCEVPredicate &Pred) {
1974 
1975     BasicBlock *LoopHeader = L->getHeader();
1976     BasicBlock *Preheader = L->getLoopPreheader();
1977 
1978     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1979     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1980     // may be used by SCEVExpander. The blocks will be un-linked from their
1981     // predecessors and removed from LI & DT at the end of the function.
1982     if (!Pred.isAlwaysTrue()) {
1983       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1984                                   nullptr, "vector.scevcheck");
1985 
1986       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1987           &Pred, SCEVCheckBlock->getTerminator());
1988     }
1989 
1990     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1991     if (RtPtrChecking.Need) {
1992       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1993       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1994                                  "vector.memcheck");
1995 
1996       MemRuntimeCheckCond =
1997           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1998                            RtPtrChecking.getChecks(), MemCheckExp);
1999       assert(MemRuntimeCheckCond &&
2000              "no RT checks generated although RtPtrChecking "
2001              "claimed checks are required");
2002     }
2003 
2004     if (!MemCheckBlock && !SCEVCheckBlock)
2005       return;
2006 
2007     // Unhook the temporary block with the checks, update various places
2008     // accordingly.
2009     if (SCEVCheckBlock)
2010       SCEVCheckBlock->replaceAllUsesWith(Preheader);
2011     if (MemCheckBlock)
2012       MemCheckBlock->replaceAllUsesWith(Preheader);
2013 
2014     if (SCEVCheckBlock) {
2015       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2016       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
2017       Preheader->getTerminator()->eraseFromParent();
2018     }
2019     if (MemCheckBlock) {
2020       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2021       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2022       Preheader->getTerminator()->eraseFromParent();
2023     }
2024 
2025     DT->changeImmediateDominator(LoopHeader, Preheader);
2026     if (MemCheckBlock) {
2027       DT->eraseNode(MemCheckBlock);
2028       LI->removeBlock(MemCheckBlock);
2029     }
2030     if (SCEVCheckBlock) {
2031       DT->eraseNode(SCEVCheckBlock);
2032       LI->removeBlock(SCEVCheckBlock);
2033     }
2034   }
2035 
2036   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2037   /// unused.
2038   ~GeneratedRTChecks() {
2039     SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2040     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2041     if (!SCEVCheckCond)
2042       SCEVCleaner.markResultUsed();
2043 
2044     if (!MemRuntimeCheckCond)
2045       MemCheckCleaner.markResultUsed();
2046 
2047     if (MemRuntimeCheckCond) {
2048       auto &SE = *MemCheckExp.getSE();
2049       // Memory runtime check generation creates compares that use expanded
2050       // values. Remove them before running the SCEVExpanderCleaners.
2051       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2052         if (MemCheckExp.isInsertedInstruction(&I))
2053           continue;
2054         SE.forgetValue(&I);
2055         I.eraseFromParent();
2056       }
2057     }
2058     MemCheckCleaner.cleanup();
2059     SCEVCleaner.cleanup();
2060 
2061     if (SCEVCheckCond)
2062       SCEVCheckBlock->eraseFromParent();
2063     if (MemRuntimeCheckCond)
2064       MemCheckBlock->eraseFromParent();
2065   }
2066 
2067   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2068   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2069   /// depending on the generated condition.
2070   BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2071                              BasicBlock *LoopVectorPreHeader,
2072                              BasicBlock *LoopExitBlock) {
2073     if (!SCEVCheckCond)
2074       return nullptr;
2075 
2076     Value *Cond = SCEVCheckCond;
2077     // Mark the check as used, to prevent it from being removed during cleanup.
2078     SCEVCheckCond = nullptr;
2079     if (auto *C = dyn_cast<ConstantInt>(Cond))
2080       if (C->isZero())
2081         return nullptr;
2082 
2083     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2084 
2085     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2086     // Create new preheader for vector loop.
2087     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2088       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2089 
2090     SCEVCheckBlock->getTerminator()->eraseFromParent();
2091     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2092     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2093                                                 SCEVCheckBlock);
2094 
2095     DT->addNewBlock(SCEVCheckBlock, Pred);
2096     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2097 
2098     ReplaceInstWithInst(SCEVCheckBlock->getTerminator(),
2099                         BranchInst::Create(Bypass, LoopVectorPreHeader, Cond));
2100     return SCEVCheckBlock;
2101   }
2102 
2103   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2104   /// the branches to branch to the vector preheader or \p Bypass, depending on
2105   /// the generated condition.
2106   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2107                                    BasicBlock *LoopVectorPreHeader) {
2108     // Check if we generated code that checks in runtime if arrays overlap.
2109     if (!MemRuntimeCheckCond)
2110       return nullptr;
2111 
2112     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2113     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2114                                                 MemCheckBlock);
2115 
2116     DT->addNewBlock(MemCheckBlock, Pred);
2117     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2118     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2119 
2120     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2121       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2122 
2123     ReplaceInstWithInst(
2124         MemCheckBlock->getTerminator(),
2125         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2126     MemCheckBlock->getTerminator()->setDebugLoc(
2127         Pred->getTerminator()->getDebugLoc());
2128 
2129     // Mark the check as used, to prevent it from being removed during cleanup.
2130     MemRuntimeCheckCond = nullptr;
2131     return MemCheckBlock;
2132   }
2133 };
2134 
2135 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2136 // vectorization. The loop needs to be annotated with #pragma omp simd
2137 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2138 // vector length information is not provided, vectorization is not considered
2139 // explicit. Interleave hints are not allowed either. These limitations will be
2140 // relaxed in the future.
2141 // Please, note that we are currently forced to abuse the pragma 'clang
2142 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2143 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2144 // provides *explicit vectorization hints* (LV can bypass legal checks and
2145 // assume that vectorization is legal). However, both hints are implemented
2146 // using the same metadata (llvm.loop.vectorize, processed by
2147 // LoopVectorizeHints). This will be fixed in the future when the native IR
2148 // representation for pragma 'omp simd' is introduced.
2149 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2150                                    OptimizationRemarkEmitter *ORE) {
2151   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2152   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2153 
2154   // Only outer loops with an explicit vectorization hint are supported.
2155   // Unannotated outer loops are ignored.
2156   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2157     return false;
2158 
2159   Function *Fn = OuterLp->getHeader()->getParent();
2160   if (!Hints.allowVectorization(Fn, OuterLp,
2161                                 true /*VectorizeOnlyWhenForced*/)) {
2162     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2163     return false;
2164   }
2165 
2166   if (Hints.getInterleave() > 1) {
2167     // TODO: Interleave support is future work.
2168     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2169                          "outer loops.\n");
2170     Hints.emitRemarkWithHints();
2171     return false;
2172   }
2173 
2174   return true;
2175 }
2176 
2177 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2178                                   OptimizationRemarkEmitter *ORE,
2179                                   SmallVectorImpl<Loop *> &V) {
2180   // Collect inner loops and outer loops without irreducible control flow. For
2181   // now, only collect outer loops that have explicit vectorization hints. If we
2182   // are stress testing the VPlan H-CFG construction, we collect the outermost
2183   // loop of every loop nest.
2184   if (L.isInnermost() || VPlanBuildStressTest ||
2185       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2186     LoopBlocksRPO RPOT(&L);
2187     RPOT.perform(LI);
2188     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2189       V.push_back(&L);
2190       // TODO: Collect inner loops inside marked outer loops in case
2191       // vectorization fails for the outer loop. Do not invoke
2192       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2193       // already known to be reducible. We can use an inherited attribute for
2194       // that.
2195       return;
2196     }
2197   }
2198   for (Loop *InnerL : L)
2199     collectSupportedLoops(*InnerL, LI, ORE, V);
2200 }
2201 
2202 namespace {
2203 
2204 /// The LoopVectorize Pass.
2205 struct LoopVectorize : public FunctionPass {
2206   /// Pass identification, replacement for typeid
2207   static char ID;
2208 
2209   LoopVectorizePass Impl;
2210 
2211   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2212                          bool VectorizeOnlyWhenForced = false)
2213       : FunctionPass(ID),
2214         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2215     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2216   }
2217 
2218   bool runOnFunction(Function &F) override {
2219     if (skipFunction(F))
2220       return false;
2221 
2222     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2223     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2224     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2225     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2226     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2227     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2228     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2229     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2230     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2231     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2232     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2233     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2234     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2235 
2236     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2237         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2238 
2239     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2240                         GetLAA, *ORE, PSI).MadeAnyChange;
2241   }
2242 
2243   void getAnalysisUsage(AnalysisUsage &AU) const override {
2244     AU.addRequired<AssumptionCacheTracker>();
2245     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2246     AU.addRequired<DominatorTreeWrapperPass>();
2247     AU.addRequired<LoopInfoWrapperPass>();
2248     AU.addRequired<ScalarEvolutionWrapperPass>();
2249     AU.addRequired<TargetTransformInfoWrapperPass>();
2250     AU.addRequired<AAResultsWrapperPass>();
2251     AU.addRequired<LoopAccessLegacyAnalysis>();
2252     AU.addRequired<DemandedBitsWrapperPass>();
2253     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2254     AU.addRequired<InjectTLIMappingsLegacy>();
2255 
2256     // We currently do not preserve loopinfo/dominator analyses with outer loop
2257     // vectorization. Until this is addressed, mark these analyses as preserved
2258     // only for non-VPlan-native path.
2259     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2260     if (!EnableVPlanNativePath) {
2261       AU.addPreserved<LoopInfoWrapperPass>();
2262       AU.addPreserved<DominatorTreeWrapperPass>();
2263     }
2264 
2265     AU.addPreserved<BasicAAWrapperPass>();
2266     AU.addPreserved<GlobalsAAWrapperPass>();
2267     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2268   }
2269 };
2270 
2271 } // end anonymous namespace
2272 
2273 //===----------------------------------------------------------------------===//
2274 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2275 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2276 //===----------------------------------------------------------------------===//
2277 
2278 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2279   // We need to place the broadcast of invariant variables outside the loop,
2280   // but only if it's proven safe to do so. Else, broadcast will be inside
2281   // vector loop body.
2282   Instruction *Instr = dyn_cast<Instruction>(V);
2283   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2284                      (!Instr ||
2285                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2286   // Place the code for broadcasting invariant variables in the new preheader.
2287   IRBuilder<>::InsertPointGuard Guard(Builder);
2288   if (SafeToHoist)
2289     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2290 
2291   // Broadcast the scalar into all locations in the vector.
2292   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2293 
2294   return Shuf;
2295 }
2296 
2297 /// This function adds
2298 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2299 /// to each vector element of Val. The sequence starts at StartIndex.
2300 /// \p Opcode is relevant for FP induction variable.
2301 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2302                             Instruction::BinaryOps BinOp, ElementCount VF,
2303                             IRBuilderBase &Builder) {
2304   assert(VF.isVector() && "only vector VFs are supported");
2305 
2306   // Create and check the types.
2307   auto *ValVTy = cast<VectorType>(Val->getType());
2308   ElementCount VLen = ValVTy->getElementCount();
2309 
2310   Type *STy = Val->getType()->getScalarType();
2311   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2312          "Induction Step must be an integer or FP");
2313   assert(Step->getType() == STy && "Step has wrong type");
2314 
2315   SmallVector<Constant *, 8> Indices;
2316 
2317   // Create a vector of consecutive numbers from zero to VF.
2318   VectorType *InitVecValVTy = ValVTy;
2319   if (STy->isFloatingPointTy()) {
2320     Type *InitVecValSTy =
2321         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2322     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2323   }
2324   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2325 
2326   // Splat the StartIdx
2327   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2328 
2329   if (STy->isIntegerTy()) {
2330     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2331     Step = Builder.CreateVectorSplat(VLen, Step);
2332     assert(Step->getType() == Val->getType() && "Invalid step vec");
2333     // FIXME: The newly created binary instructions should contain nsw/nuw
2334     // flags, which can be found from the original scalar operations.
2335     Step = Builder.CreateMul(InitVec, Step);
2336     return Builder.CreateAdd(Val, Step, "induction");
2337   }
2338 
2339   // Floating point induction.
2340   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2341          "Binary Opcode should be specified for FP induction");
2342   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2343   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2344 
2345   Step = Builder.CreateVectorSplat(VLen, Step);
2346   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2347   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2348 }
2349 
2350 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2351 /// variable on which to base the steps, \p Step is the size of the step.
2352 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2353                              const InductionDescriptor &ID, VPValue *Def,
2354                              VPTransformState &State) {
2355   IRBuilderBase &Builder = State.Builder;
2356   // We shouldn't have to build scalar steps if we aren't vectorizing.
2357   assert(State.VF.isVector() && "VF should be greater than one");
2358   // Get the value type and ensure it and the step have the same integer type.
2359   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2360   assert(ScalarIVTy == Step->getType() &&
2361          "Val and Step should have the same type");
2362 
2363   // We build scalar steps for both integer and floating-point induction
2364   // variables. Here, we determine the kind of arithmetic we will perform.
2365   Instruction::BinaryOps AddOp;
2366   Instruction::BinaryOps MulOp;
2367   if (ScalarIVTy->isIntegerTy()) {
2368     AddOp = Instruction::Add;
2369     MulOp = Instruction::Mul;
2370   } else {
2371     AddOp = ID.getInductionOpcode();
2372     MulOp = Instruction::FMul;
2373   }
2374 
2375   // Determine the number of scalars we need to generate for each unroll
2376   // iteration.
2377   bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2378   unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2379   // Compute the scalar steps and save the results in State.
2380   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2381                                      ScalarIVTy->getScalarSizeInBits());
2382   Type *VecIVTy = nullptr;
2383   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2384   if (!FirstLaneOnly && State.VF.isScalable()) {
2385     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2386     UnitStepVec =
2387         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2388     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2389     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2390   }
2391 
2392   for (unsigned Part = 0; Part < State.UF; ++Part) {
2393     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2394 
2395     if (!FirstLaneOnly && State.VF.isScalable()) {
2396       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2397       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2398       if (ScalarIVTy->isFloatingPointTy())
2399         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2400       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2401       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2402       State.set(Def, Add, Part);
2403       // It's useful to record the lane values too for the known minimum number
2404       // of elements so we do those below. This improves the code quality when
2405       // trying to extract the first element, for example.
2406     }
2407 
2408     if (ScalarIVTy->isFloatingPointTy())
2409       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2410 
2411     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2412       Value *StartIdx = Builder.CreateBinOp(
2413           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2414       // The step returned by `createStepForVF` is a runtime-evaluated value
2415       // when VF is scalable. Otherwise, it should be folded into a Constant.
2416       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2417              "Expected StartIdx to be folded to a constant when VF is not "
2418              "scalable");
2419       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2420       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2421       State.set(Def, Add, VPIteration(Part, Lane));
2422     }
2423   }
2424 }
2425 
2426 // Generate code for the induction step. Note that induction steps are
2427 // required to be loop-invariant
2428 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2429                               Instruction *InsertBefore,
2430                               Loop *OrigLoop = nullptr) {
2431   const DataLayout &DL = SE.getDataLayout();
2432   assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2433          "Induction step should be loop invariant");
2434   if (auto *E = dyn_cast<SCEVUnknown>(Step))
2435     return E->getValue();
2436 
2437   SCEVExpander Exp(SE, DL, "induction");
2438   return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2439 }
2440 
2441 /// Compute the transformed value of Index at offset StartValue using step
2442 /// StepValue.
2443 /// For integer induction, returns StartValue + Index * StepValue.
2444 /// For pointer induction, returns StartValue[Index * StepValue].
2445 /// FIXME: The newly created binary instructions should contain nsw/nuw
2446 /// flags, which can be found from the original scalar operations.
2447 static Value *emitTransformedIndex(IRBuilderBase &B, Value *Index,
2448                                    Value *StartValue, Value *Step,
2449                                    const InductionDescriptor &ID) {
2450   assert(Index->getType()->getScalarType() == Step->getType() &&
2451          "Index scalar type does not match StepValue type");
2452 
2453   // Note: the IR at this point is broken. We cannot use SE to create any new
2454   // SCEV and then expand it, hoping that SCEV's simplification will give us
2455   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2456   // lead to various SCEV crashes. So all we can do is to use builder and rely
2457   // on InstCombine for future simplifications. Here we handle some trivial
2458   // cases only.
2459   auto CreateAdd = [&B](Value *X, Value *Y) {
2460     assert(X->getType() == Y->getType() && "Types don't match!");
2461     if (auto *CX = dyn_cast<ConstantInt>(X))
2462       if (CX->isZero())
2463         return Y;
2464     if (auto *CY = dyn_cast<ConstantInt>(Y))
2465       if (CY->isZero())
2466         return X;
2467     return B.CreateAdd(X, Y);
2468   };
2469 
2470   // We allow X to be a vector type, in which case Y will potentially be
2471   // splatted into a vector with the same element count.
2472   auto CreateMul = [&B](Value *X, Value *Y) {
2473     assert(X->getType()->getScalarType() == Y->getType() &&
2474            "Types don't match!");
2475     if (auto *CX = dyn_cast<ConstantInt>(X))
2476       if (CX->isOne())
2477         return Y;
2478     if (auto *CY = dyn_cast<ConstantInt>(Y))
2479       if (CY->isOne())
2480         return X;
2481     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2482     if (XVTy && !isa<VectorType>(Y->getType()))
2483       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2484     return B.CreateMul(X, Y);
2485   };
2486 
2487   switch (ID.getKind()) {
2488   case InductionDescriptor::IK_IntInduction: {
2489     assert(!isa<VectorType>(Index->getType()) &&
2490            "Vector indices not supported for integer inductions yet");
2491     assert(Index->getType() == StartValue->getType() &&
2492            "Index type does not match StartValue type");
2493     if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2494       return B.CreateSub(StartValue, Index);
2495     auto *Offset = CreateMul(Index, Step);
2496     return CreateAdd(StartValue, Offset);
2497   }
2498   case InductionDescriptor::IK_PtrInduction: {
2499     assert(isa<Constant>(Step) &&
2500            "Expected constant step for pointer induction");
2501     return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2502   }
2503   case InductionDescriptor::IK_FpInduction: {
2504     assert(!isa<VectorType>(Index->getType()) &&
2505            "Vector indices not supported for FP inductions yet");
2506     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2507     auto InductionBinOp = ID.getInductionBinOp();
2508     assert(InductionBinOp &&
2509            (InductionBinOp->getOpcode() == Instruction::FAdd ||
2510             InductionBinOp->getOpcode() == Instruction::FSub) &&
2511            "Original bin op should be defined for FP induction");
2512 
2513     Value *MulExp = B.CreateFMul(Step, Index);
2514     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2515                          "induction");
2516   }
2517   case InductionDescriptor::IK_NoInduction:
2518     return nullptr;
2519   }
2520   llvm_unreachable("invalid enum");
2521 }
2522 
2523 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2524                                                     const VPIteration &Instance,
2525                                                     VPTransformState &State) {
2526   Value *ScalarInst = State.get(Def, Instance);
2527   Value *VectorValue = State.get(Def, Instance.Part);
2528   VectorValue = Builder.CreateInsertElement(
2529       VectorValue, ScalarInst,
2530       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2531   State.set(Def, VectorValue, Instance.Part);
2532 }
2533 
2534 // Return whether we allow using masked interleave-groups (for dealing with
2535 // strided loads/stores that reside in predicated blocks, or for dealing
2536 // with gaps).
2537 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2538   // If an override option has been passed in for interleaved accesses, use it.
2539   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2540     return EnableMaskedInterleavedMemAccesses;
2541 
2542   return TTI.enableMaskedInterleavedAccessVectorization();
2543 }
2544 
2545 // Try to vectorize the interleave group that \p Instr belongs to.
2546 //
2547 // E.g. Translate following interleaved load group (factor = 3):
2548 //   for (i = 0; i < N; i+=3) {
2549 //     R = Pic[i];             // Member of index 0
2550 //     G = Pic[i+1];           // Member of index 1
2551 //     B = Pic[i+2];           // Member of index 2
2552 //     ... // do something to R, G, B
2553 //   }
2554 // To:
2555 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2556 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2557 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2558 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2559 //
2560 // Or translate following interleaved store group (factor = 3):
2561 //   for (i = 0; i < N; i+=3) {
2562 //     ... do something to R, G, B
2563 //     Pic[i]   = R;           // Member of index 0
2564 //     Pic[i+1] = G;           // Member of index 1
2565 //     Pic[i+2] = B;           // Member of index 2
2566 //   }
2567 // To:
2568 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2569 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2570 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2571 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2572 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2573 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2574     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2575     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2576     VPValue *BlockInMask) {
2577   Instruction *Instr = Group->getInsertPos();
2578   const DataLayout &DL = Instr->getModule()->getDataLayout();
2579 
2580   // Prepare for the vector type of the interleaved load/store.
2581   Type *ScalarTy = getLoadStoreType(Instr);
2582   unsigned InterleaveFactor = Group->getFactor();
2583   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2584   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2585 
2586   // Prepare for the new pointers.
2587   SmallVector<Value *, 2> AddrParts;
2588   unsigned Index = Group->getIndex(Instr);
2589 
2590   // TODO: extend the masked interleaved-group support to reversed access.
2591   assert((!BlockInMask || !Group->isReverse()) &&
2592          "Reversed masked interleave-group not supported.");
2593 
2594   // If the group is reverse, adjust the index to refer to the last vector lane
2595   // instead of the first. We adjust the index from the first vector lane,
2596   // rather than directly getting the pointer for lane VF - 1, because the
2597   // pointer operand of the interleaved access is supposed to be uniform. For
2598   // uniform instructions, we're only required to generate a value for the
2599   // first vector lane in each unroll iteration.
2600   if (Group->isReverse())
2601     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2602 
2603   for (unsigned Part = 0; Part < UF; Part++) {
2604     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2605     setDebugLocFromInst(AddrPart);
2606 
2607     // Notice current instruction could be any index. Need to adjust the address
2608     // to the member of index 0.
2609     //
2610     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2611     //       b = A[i];       // Member of index 0
2612     // Current pointer is pointed to A[i+1], adjust it to A[i].
2613     //
2614     // E.g.  A[i+1] = a;     // Member of index 1
2615     //       A[i]   = b;     // Member of index 0
2616     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2617     // Current pointer is pointed to A[i+2], adjust it to A[i].
2618 
2619     bool InBounds = false;
2620     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2621       InBounds = gep->isInBounds();
2622     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2623     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2624 
2625     // Cast to the vector pointer type.
2626     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2627     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2628     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2629   }
2630 
2631   setDebugLocFromInst(Instr);
2632   Value *PoisonVec = PoisonValue::get(VecTy);
2633 
2634   Value *MaskForGaps = nullptr;
2635   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2636     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2637     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2638   }
2639 
2640   // Vectorize the interleaved load group.
2641   if (isa<LoadInst>(Instr)) {
2642     // For each unroll part, create a wide load for the group.
2643     SmallVector<Value *, 2> NewLoads;
2644     for (unsigned Part = 0; Part < UF; Part++) {
2645       Instruction *NewLoad;
2646       if (BlockInMask || MaskForGaps) {
2647         assert(useMaskedInterleavedAccesses(*TTI) &&
2648                "masked interleaved groups are not allowed.");
2649         Value *GroupMask = MaskForGaps;
2650         if (BlockInMask) {
2651           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2652           Value *ShuffledMask = Builder.CreateShuffleVector(
2653               BlockInMaskPart,
2654               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2655               "interleaved.mask");
2656           GroupMask = MaskForGaps
2657                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2658                                                 MaskForGaps)
2659                           : ShuffledMask;
2660         }
2661         NewLoad =
2662             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2663                                      GroupMask, PoisonVec, "wide.masked.vec");
2664       }
2665       else
2666         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2667                                             Group->getAlign(), "wide.vec");
2668       Group->addMetadata(NewLoad);
2669       NewLoads.push_back(NewLoad);
2670     }
2671 
2672     // For each member in the group, shuffle out the appropriate data from the
2673     // wide loads.
2674     unsigned J = 0;
2675     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2676       Instruction *Member = Group->getMember(I);
2677 
2678       // Skip the gaps in the group.
2679       if (!Member)
2680         continue;
2681 
2682       auto StrideMask =
2683           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2684       for (unsigned Part = 0; Part < UF; Part++) {
2685         Value *StridedVec = Builder.CreateShuffleVector(
2686             NewLoads[Part], StrideMask, "strided.vec");
2687 
2688         // If this member has different type, cast the result type.
2689         if (Member->getType() != ScalarTy) {
2690           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2691           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2692           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2693         }
2694 
2695         if (Group->isReverse())
2696           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2697 
2698         State.set(VPDefs[J], StridedVec, Part);
2699       }
2700       ++J;
2701     }
2702     return;
2703   }
2704 
2705   // The sub vector type for current instruction.
2706   auto *SubVT = VectorType::get(ScalarTy, VF);
2707 
2708   // Vectorize the interleaved store group.
2709   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2710   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2711          "masked interleaved groups are not allowed.");
2712   assert((!MaskForGaps || !VF.isScalable()) &&
2713          "masking gaps for scalable vectors is not yet supported.");
2714   for (unsigned Part = 0; Part < UF; Part++) {
2715     // Collect the stored vector from each member.
2716     SmallVector<Value *, 4> StoredVecs;
2717     for (unsigned i = 0; i < InterleaveFactor; i++) {
2718       assert((Group->getMember(i) || MaskForGaps) &&
2719              "Fail to get a member from an interleaved store group");
2720       Instruction *Member = Group->getMember(i);
2721 
2722       // Skip the gaps in the group.
2723       if (!Member) {
2724         Value *Undef = PoisonValue::get(SubVT);
2725         StoredVecs.push_back(Undef);
2726         continue;
2727       }
2728 
2729       Value *StoredVec = State.get(StoredValues[i], Part);
2730 
2731       if (Group->isReverse())
2732         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2733 
2734       // If this member has different type, cast it to a unified type.
2735 
2736       if (StoredVec->getType() != SubVT)
2737         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2738 
2739       StoredVecs.push_back(StoredVec);
2740     }
2741 
2742     // Concatenate all vectors into a wide vector.
2743     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2744 
2745     // Interleave the elements in the wide vector.
2746     Value *IVec = Builder.CreateShuffleVector(
2747         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2748         "interleaved.vec");
2749 
2750     Instruction *NewStoreInstr;
2751     if (BlockInMask || MaskForGaps) {
2752       Value *GroupMask = MaskForGaps;
2753       if (BlockInMask) {
2754         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2755         Value *ShuffledMask = Builder.CreateShuffleVector(
2756             BlockInMaskPart,
2757             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2758             "interleaved.mask");
2759         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2760                                                       ShuffledMask, MaskForGaps)
2761                                 : ShuffledMask;
2762       }
2763       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2764                                                 Group->getAlign(), GroupMask);
2765     } else
2766       NewStoreInstr =
2767           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2768 
2769     Group->addMetadata(NewStoreInstr);
2770   }
2771 }
2772 
2773 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2774                                                VPReplicateRecipe *RepRecipe,
2775                                                const VPIteration &Instance,
2776                                                bool IfPredicateInstr,
2777                                                VPTransformState &State) {
2778   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2779 
2780   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2781   // the first lane and part.
2782   if (isa<NoAliasScopeDeclInst>(Instr))
2783     if (!Instance.isFirstIteration())
2784       return;
2785 
2786   // Does this instruction return a value ?
2787   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2788 
2789   Instruction *Cloned = Instr->clone();
2790   if (!IsVoidRetTy)
2791     Cloned->setName(Instr->getName() + ".cloned");
2792 
2793   // If the scalarized instruction contributes to the address computation of a
2794   // widen masked load/store which was in a basic block that needed predication
2795   // and is not predicated after vectorization, we can't propagate
2796   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2797   // instruction could feed a poison value to the base address of the widen
2798   // load/store.
2799   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2800     Cloned->dropPoisonGeneratingFlags();
2801 
2802   if (Instr->getDebugLoc())
2803     setDebugLocFromInst(Instr);
2804 
2805   // Replace the operands of the cloned instructions with their scalar
2806   // equivalents in the new loop.
2807   for (auto &I : enumerate(RepRecipe->operands())) {
2808     auto InputInstance = Instance;
2809     VPValue *Operand = I.value();
2810     VPReplicateRecipe *OperandR = dyn_cast<VPReplicateRecipe>(Operand);
2811     if (OperandR && OperandR->isUniform())
2812       InputInstance.Lane = VPLane::getFirstLane();
2813     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2814   }
2815   addNewMetadata(Cloned, Instr);
2816 
2817   // Place the cloned scalar in the new loop.
2818   State.Builder.Insert(Cloned);
2819 
2820   State.set(RepRecipe, Cloned, Instance);
2821 
2822   // If we just cloned a new assumption, add it the assumption cache.
2823   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2824     AC->registerAssumption(II);
2825 
2826   // End if-block.
2827   if (IfPredicateInstr)
2828     PredicatedInstructions.push_back(Cloned);
2829 }
2830 
2831 Value *InnerLoopVectorizer::getOrCreateTripCount(BasicBlock *InsertBlock) {
2832   if (TripCount)
2833     return TripCount;
2834 
2835   assert(InsertBlock);
2836   IRBuilder<> Builder(InsertBlock->getTerminator());
2837   // Find the loop boundaries.
2838   ScalarEvolution *SE = PSE.getSE();
2839   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2840   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2841          "Invalid loop count");
2842 
2843   Type *IdxTy = Legal->getWidestInductionType();
2844   assert(IdxTy && "No type for induction");
2845 
2846   // The exit count might have the type of i64 while the phi is i32. This can
2847   // happen if we have an induction variable that is sign extended before the
2848   // compare. The only way that we get a backedge taken count is that the
2849   // induction variable was signed and as such will not overflow. In such a case
2850   // truncation is legal.
2851   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2852       IdxTy->getPrimitiveSizeInBits())
2853     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2854   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2855 
2856   // Get the total trip count from the count by adding 1.
2857   const SCEV *ExitCount = SE->getAddExpr(
2858       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2859 
2860   const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2861 
2862   // Expand the trip count and place the new instructions in the preheader.
2863   // Notice that the pre-header does not change, only the loop body.
2864   SCEVExpander Exp(*SE, DL, "induction");
2865 
2866   // Count holds the overall loop count (N).
2867   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2868                                 InsertBlock->getTerminator());
2869 
2870   if (TripCount->getType()->isPointerTy())
2871     TripCount =
2872         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2873                                     InsertBlock->getTerminator());
2874 
2875   return TripCount;
2876 }
2877 
2878 Value *
2879 InnerLoopVectorizer::getOrCreateVectorTripCount(BasicBlock *InsertBlock) {
2880   if (VectorTripCount)
2881     return VectorTripCount;
2882 
2883   Value *TC = getOrCreateTripCount(InsertBlock);
2884   IRBuilder<> Builder(InsertBlock->getTerminator());
2885 
2886   Type *Ty = TC->getType();
2887   // This is where we can make the step a runtime constant.
2888   Value *Step = createStepForVF(Builder, Ty, VF, UF);
2889 
2890   // If the tail is to be folded by masking, round the number of iterations N
2891   // up to a multiple of Step instead of rounding down. This is done by first
2892   // adding Step-1 and then rounding down. Note that it's ok if this addition
2893   // overflows: the vector induction variable will eventually wrap to zero given
2894   // that it starts at zero and its Step is a power of two; the loop will then
2895   // exit, with the last early-exit vector comparison also producing all-true.
2896   // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2897   // is accounted for in emitIterationCountCheck that adds an overflow check.
2898   if (Cost->foldTailByMasking()) {
2899     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2900            "VF*UF must be a power of 2 when folding tail by masking");
2901     Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2902     TC = Builder.CreateAdd(
2903         TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2904   }
2905 
2906   // Now we need to generate the expression for the part of the loop that the
2907   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2908   // iterations are not required for correctness, or N - Step, otherwise. Step
2909   // is equal to the vectorization factor (number of SIMD elements) times the
2910   // unroll factor (number of SIMD instructions).
2911   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2912 
2913   // There are cases where we *must* run at least one iteration in the remainder
2914   // loop.  See the cost model for when this can happen.  If the step evenly
2915   // divides the trip count, we set the remainder to be equal to the step. If
2916   // the step does not evenly divide the trip count, no adjustment is necessary
2917   // since there will already be scalar iterations. Note that the minimum
2918   // iterations check ensures that N >= Step.
2919   if (Cost->requiresScalarEpilogue(VF)) {
2920     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2921     R = Builder.CreateSelect(IsZero, Step, R);
2922   }
2923 
2924   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2925 
2926   return VectorTripCount;
2927 }
2928 
2929 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2930                                                    const DataLayout &DL) {
2931   // Verify that V is a vector type with same number of elements as DstVTy.
2932   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2933   unsigned VF = DstFVTy->getNumElements();
2934   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2935   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2936   Type *SrcElemTy = SrcVecTy->getElementType();
2937   Type *DstElemTy = DstFVTy->getElementType();
2938   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2939          "Vector elements must have same size");
2940 
2941   // Do a direct cast if element types are castable.
2942   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2943     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2944   }
2945   // V cannot be directly casted to desired vector type.
2946   // May happen when V is a floating point vector but DstVTy is a vector of
2947   // pointers or vice-versa. Handle this using a two-step bitcast using an
2948   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2949   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2950          "Only one type should be a pointer type");
2951   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2952          "Only one type should be a floating point type");
2953   Type *IntTy =
2954       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2955   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2956   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2957   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2958 }
2959 
2960 void InnerLoopVectorizer::emitIterationCountCheck(BasicBlock *Bypass) {
2961   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
2962   // Reuse existing vector loop preheader for TC checks.
2963   // Note that new preheader block is generated for vector loop.
2964   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2965   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2966 
2967   // Generate code to check if the loop's trip count is less than VF * UF, or
2968   // equal to it in case a scalar epilogue is required; this implies that the
2969   // vector trip count is zero. This check also covers the case where adding one
2970   // to the backedge-taken count overflowed leading to an incorrect trip count
2971   // of zero. In this case we will also jump to the scalar loop.
2972   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
2973                                             : ICmpInst::ICMP_ULT;
2974 
2975   // If tail is to be folded, vector loop takes care of all iterations.
2976   Type *CountTy = Count->getType();
2977   Value *CheckMinIters = Builder.getFalse();
2978   Value *Step = createStepForVF(Builder, CountTy, VF, UF);
2979   if (!Cost->foldTailByMasking())
2980     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
2981   else if (VF.isScalable()) {
2982     // vscale is not necessarily a power-of-2, which means we cannot guarantee
2983     // an overflow to zero when updating induction variables and so an
2984     // additional overflow check is required before entering the vector loop.
2985 
2986     // Get the maximum unsigned value for the type.
2987     Value *MaxUIntTripCount =
2988         ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2989     Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2990 
2991     // Don't execute the vector loop if (UMax - n) < (VF * UF).
2992     CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, Step);
2993   }
2994   // Create new preheader for vector loop.
2995   LoopVectorPreHeader =
2996       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2997                  "vector.ph");
2998 
2999   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3000                                DT->getNode(Bypass)->getIDom()) &&
3001          "TC check is expected to dominate Bypass");
3002 
3003   // Update dominator for Bypass & LoopExit (if needed).
3004   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3005   if (!Cost->requiresScalarEpilogue(VF))
3006     // If there is an epilogue which must run, there's no edge from the
3007     // middle block to exit blocks  and thus no need to update the immediate
3008     // dominator of the exit blocks.
3009     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3010 
3011   ReplaceInstWithInst(
3012       TCCheckBlock->getTerminator(),
3013       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3014   LoopBypassBlocks.push_back(TCCheckBlock);
3015 }
3016 
3017 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(BasicBlock *Bypass) {
3018 
3019   BasicBlock *const SCEVCheckBlock =
3020       RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3021   if (!SCEVCheckBlock)
3022     return nullptr;
3023 
3024   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3025            (OptForSizeBasedOnProfile &&
3026             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3027          "Cannot SCEV check stride or overflow when optimizing for size");
3028 
3029 
3030   // Update dominator only if this is first RT check.
3031   if (LoopBypassBlocks.empty()) {
3032     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3033     if (!Cost->requiresScalarEpilogue(VF))
3034       // If there is an epilogue which must run, there's no edge from the
3035       // middle block to exit blocks  and thus no need to update the immediate
3036       // dominator of the exit blocks.
3037       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3038   }
3039 
3040   LoopBypassBlocks.push_back(SCEVCheckBlock);
3041   AddedSafetyChecks = true;
3042   return SCEVCheckBlock;
3043 }
3044 
3045 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(BasicBlock *Bypass) {
3046   // VPlan-native path does not do any analysis for runtime checks currently.
3047   if (EnableVPlanNativePath)
3048     return nullptr;
3049 
3050   BasicBlock *const MemCheckBlock =
3051       RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3052 
3053   // Check if we generated code that checks in runtime if arrays overlap. We put
3054   // the checks into a separate block to make the more common case of few
3055   // elements faster.
3056   if (!MemCheckBlock)
3057     return nullptr;
3058 
3059   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3060     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3061            "Cannot emit memory checks when optimizing for size, unless forced "
3062            "to vectorize.");
3063     ORE->emit([&]() {
3064       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3065                                         OrigLoop->getStartLoc(),
3066                                         OrigLoop->getHeader())
3067              << "Code-size may be reduced by not forcing "
3068                 "vectorization, or by source-code modifications "
3069                 "eliminating the need for runtime checks "
3070                 "(e.g., adding 'restrict').";
3071     });
3072   }
3073 
3074   LoopBypassBlocks.push_back(MemCheckBlock);
3075 
3076   AddedSafetyChecks = true;
3077 
3078   // We currently don't use LoopVersioning for the actual loop cloning but we
3079   // still use it to add the noalias metadata.
3080   LVer = std::make_unique<LoopVersioning>(
3081       *Legal->getLAI(),
3082       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3083       DT, PSE.getSE());
3084   LVer->prepareNoAliasMetadata();
3085   return MemCheckBlock;
3086 }
3087 
3088 void InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3089   LoopScalarBody = OrigLoop->getHeader();
3090   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3091   assert(LoopVectorPreHeader && "Invalid loop structure");
3092   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3093   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3094          "multiple exit loop without required epilogue?");
3095 
3096   LoopMiddleBlock =
3097       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3098                  LI, nullptr, Twine(Prefix) + "middle.block");
3099   LoopScalarPreHeader =
3100       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3101                  nullptr, Twine(Prefix) + "scalar.ph");
3102 
3103   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3104 
3105   // Set up the middle block terminator.  Two cases:
3106   // 1) If we know that we must execute the scalar epilogue, emit an
3107   //    unconditional branch.
3108   // 2) Otherwise, we must have a single unique exit block (due to how we
3109   //    implement the multiple exit case).  In this case, set up a conditonal
3110   //    branch from the middle block to the loop scalar preheader, and the
3111   //    exit block.  completeLoopSkeleton will update the condition to use an
3112   //    iteration check, if required to decide whether to execute the remainder.
3113   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3114     BranchInst::Create(LoopScalarPreHeader) :
3115     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3116                        Builder.getTrue());
3117   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3118   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3119 
3120   // Update dominator for loop exit. During skeleton creation, only the vector
3121   // pre-header and the middle block are created. The vector loop is entirely
3122   // created during VPlan exection.
3123   if (!Cost->requiresScalarEpilogue(VF))
3124     // If there is an epilogue which must run, there's no edge from the
3125     // middle block to exit blocks  and thus no need to update the immediate
3126     // dominator of the exit blocks.
3127     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3128 }
3129 
3130 void InnerLoopVectorizer::createInductionResumeValues(
3131     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3132   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3133           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3134          "Inconsistent information about additional bypass.");
3135 
3136   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3137   assert(VectorTripCount && "Expected valid arguments");
3138   // We are going to resume the execution of the scalar loop.
3139   // Go over all of the induction variables that we found and fix the
3140   // PHIs that are left in the scalar version of the loop.
3141   // The starting values of PHI nodes depend on the counter of the last
3142   // iteration in the vectorized loop.
3143   // If we come from a bypass edge then we need to start from the original
3144   // start value.
3145   Instruction *OldInduction = Legal->getPrimaryInduction();
3146   for (auto &InductionEntry : Legal->getInductionVars()) {
3147     PHINode *OrigPhi = InductionEntry.first;
3148     InductionDescriptor II = InductionEntry.second;
3149 
3150     // Create phi nodes to merge from the  backedge-taken check block.
3151     PHINode *BCResumeVal =
3152         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3153                         LoopScalarPreHeader->getTerminator());
3154     // Copy original phi DL over to the new one.
3155     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3156     Value *&EndValue = IVEndValues[OrigPhi];
3157     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3158     if (OrigPhi == OldInduction) {
3159       // We know what the end value is.
3160       EndValue = VectorTripCount;
3161     } else {
3162       IRBuilder<> B(LoopVectorPreHeader->getTerminator());
3163 
3164       // Fast-math-flags propagate from the original induction instruction.
3165       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3166         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3167 
3168       Type *StepType = II.getStep()->getType();
3169       Instruction::CastOps CastOp =
3170           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3171       Value *VTC = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.vtc");
3172       Value *Step =
3173           CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3174       EndValue = emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3175       EndValue->setName("ind.end");
3176 
3177       // Compute the end value for the additional bypass (if applicable).
3178       if (AdditionalBypass.first) {
3179         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3180         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3181                                          StepType, true);
3182         Value *Step =
3183             CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3184         VTC =
3185             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.vtc");
3186         EndValueFromAdditionalBypass =
3187             emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3188         EndValueFromAdditionalBypass->setName("ind.end");
3189       }
3190     }
3191     // The new PHI merges the original incoming value, in case of a bypass,
3192     // or the value at the end of the vectorized loop.
3193     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3194 
3195     // Fix the scalar body counter (PHI node).
3196     // The old induction's phi node in the scalar body needs the truncated
3197     // value.
3198     for (BasicBlock *BB : LoopBypassBlocks)
3199       BCResumeVal->addIncoming(II.getStartValue(), BB);
3200 
3201     if (AdditionalBypass.first)
3202       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3203                                             EndValueFromAdditionalBypass);
3204 
3205     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3206   }
3207 }
3208 
3209 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(MDNode *OrigLoopID) {
3210   // The trip counts should be cached by now.
3211   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
3212   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3213 
3214   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3215 
3216   // Add a check in the middle block to see if we have completed
3217   // all of the iterations in the first vector loop.  Three cases:
3218   // 1) If we require a scalar epilogue, there is no conditional branch as
3219   //    we unconditionally branch to the scalar preheader.  Do nothing.
3220   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3221   //    Thus if tail is to be folded, we know we don't need to run the
3222   //    remainder and we can use the previous value for the condition (true).
3223   // 3) Otherwise, construct a runtime check.
3224   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3225     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3226                                         Count, VectorTripCount, "cmp.n",
3227                                         LoopMiddleBlock->getTerminator());
3228 
3229     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3230     // of the corresponding compare because they may have ended up with
3231     // different line numbers and we want to avoid awkward line stepping while
3232     // debugging. Eg. if the compare has got a line number inside the loop.
3233     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3234     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3235   }
3236 
3237 #ifdef EXPENSIVE_CHECKS
3238   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3239 #endif
3240 
3241   return LoopVectorPreHeader;
3242 }
3243 
3244 std::pair<BasicBlock *, Value *>
3245 InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3246   /*
3247    In this function we generate a new loop. The new loop will contain
3248    the vectorized instructions while the old loop will continue to run the
3249    scalar remainder.
3250 
3251        [ ] <-- loop iteration number check.
3252     /   |
3253    /    v
3254   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3255   |  /  |
3256   | /   v
3257   ||   [ ]     <-- vector pre header.
3258   |/    |
3259   |     v
3260   |    [  ] \
3261   |    [  ]_|   <-- vector loop (created during VPlan execution).
3262   |     |
3263   |     v
3264   \   -[ ]   <--- middle-block.
3265    \/   |
3266    /\   v
3267    | ->[ ]     <--- new preheader.
3268    |    |
3269  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3270    |   [ ] \
3271    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3272     \   |
3273      \  v
3274       >[ ]     <-- exit block(s).
3275    ...
3276    */
3277 
3278   // Get the metadata of the original loop before it gets modified.
3279   MDNode *OrigLoopID = OrigLoop->getLoopID();
3280 
3281   // Workaround!  Compute the trip count of the original loop and cache it
3282   // before we start modifying the CFG.  This code has a systemic problem
3283   // wherein it tries to run analysis over partially constructed IR; this is
3284   // wrong, and not simply for SCEV.  The trip count of the original loop
3285   // simply happens to be prone to hitting this in practice.  In theory, we
3286   // can hit the same issue for any SCEV, or ValueTracking query done during
3287   // mutation.  See PR49900.
3288   getOrCreateTripCount(OrigLoop->getLoopPreheader());
3289 
3290   // Create an empty vector loop, and prepare basic blocks for the runtime
3291   // checks.
3292   createVectorLoopSkeleton("");
3293 
3294   // Now, compare the new count to zero. If it is zero skip the vector loop and
3295   // jump to the scalar loop. This check also covers the case where the
3296   // backedge-taken count is uint##_max: adding one to it will overflow leading
3297   // to an incorrect trip count of zero. In this (rare) case we will also jump
3298   // to the scalar loop.
3299   emitIterationCountCheck(LoopScalarPreHeader);
3300 
3301   // Generate the code to check any assumptions that we've made for SCEV
3302   // expressions.
3303   emitSCEVChecks(LoopScalarPreHeader);
3304 
3305   // Generate the code that checks in runtime if arrays overlap. We put the
3306   // checks into a separate block to make the more common case of few elements
3307   // faster.
3308   emitMemRuntimeChecks(LoopScalarPreHeader);
3309 
3310   // Emit phis for the new starting index of the scalar loop.
3311   createInductionResumeValues();
3312 
3313   return {completeLoopSkeleton(OrigLoopID), nullptr};
3314 }
3315 
3316 // Fix up external users of the induction variable. At this point, we are
3317 // in LCSSA form, with all external PHIs that use the IV having one input value,
3318 // coming from the remainder loop. We need those PHIs to also have a correct
3319 // value for the IV when arriving directly from the middle block.
3320 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3321                                        const InductionDescriptor &II,
3322                                        Value *VectorTripCount, Value *EndValue,
3323                                        BasicBlock *MiddleBlock,
3324                                        BasicBlock *VectorHeader) {
3325   // There are two kinds of external IV usages - those that use the value
3326   // computed in the last iteration (the PHI) and those that use the penultimate
3327   // value (the value that feeds into the phi from the loop latch).
3328   // We allow both, but they, obviously, have different values.
3329 
3330   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3331 
3332   DenseMap<Value *, Value *> MissingVals;
3333 
3334   // An external user of the last iteration's value should see the value that
3335   // the remainder loop uses to initialize its own IV.
3336   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3337   for (User *U : PostInc->users()) {
3338     Instruction *UI = cast<Instruction>(U);
3339     if (!OrigLoop->contains(UI)) {
3340       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3341       MissingVals[UI] = EndValue;
3342     }
3343   }
3344 
3345   // An external user of the penultimate value need to see EndValue - Step.
3346   // The simplest way to get this is to recompute it from the constituent SCEVs,
3347   // that is Start + (Step * (CRD - 1)).
3348   for (User *U : OrigPhi->users()) {
3349     auto *UI = cast<Instruction>(U);
3350     if (!OrigLoop->contains(UI)) {
3351       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3352 
3353       IRBuilder<> B(MiddleBlock->getTerminator());
3354 
3355       // Fast-math-flags propagate from the original induction instruction.
3356       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3357         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3358 
3359       Value *CountMinusOne = B.CreateSub(
3360           VectorTripCount, ConstantInt::get(VectorTripCount->getType(), 1));
3361       Value *CMO =
3362           !II.getStep()->getType()->isIntegerTy()
3363               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3364                              II.getStep()->getType())
3365               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3366       CMO->setName("cast.cmo");
3367 
3368       Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3369                                     VectorHeader->getTerminator());
3370       Value *Escape =
3371           emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3372       Escape->setName("ind.escape");
3373       MissingVals[UI] = Escape;
3374     }
3375   }
3376 
3377   for (auto &I : MissingVals) {
3378     PHINode *PHI = cast<PHINode>(I.first);
3379     // One corner case we have to handle is two IVs "chasing" each-other,
3380     // that is %IV2 = phi [...], [ %IV1, %latch ]
3381     // In this case, if IV1 has an external use, we need to avoid adding both
3382     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3383     // don't already have an incoming value for the middle block.
3384     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3385       PHI->addIncoming(I.second, MiddleBlock);
3386   }
3387 }
3388 
3389 namespace {
3390 
3391 struct CSEDenseMapInfo {
3392   static bool canHandle(const Instruction *I) {
3393     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3394            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3395   }
3396 
3397   static inline Instruction *getEmptyKey() {
3398     return DenseMapInfo<Instruction *>::getEmptyKey();
3399   }
3400 
3401   static inline Instruction *getTombstoneKey() {
3402     return DenseMapInfo<Instruction *>::getTombstoneKey();
3403   }
3404 
3405   static unsigned getHashValue(const Instruction *I) {
3406     assert(canHandle(I) && "Unknown instruction!");
3407     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3408                                                            I->value_op_end()));
3409   }
3410 
3411   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3412     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3413         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3414       return LHS == RHS;
3415     return LHS->isIdenticalTo(RHS);
3416   }
3417 };
3418 
3419 } // end anonymous namespace
3420 
3421 ///Perform cse of induction variable instructions.
3422 static void cse(BasicBlock *BB) {
3423   // Perform simple cse.
3424   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3425   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3426     if (!CSEDenseMapInfo::canHandle(&In))
3427       continue;
3428 
3429     // Check if we can replace this instruction with any of the
3430     // visited instructions.
3431     if (Instruction *V = CSEMap.lookup(&In)) {
3432       In.replaceAllUsesWith(V);
3433       In.eraseFromParent();
3434       continue;
3435     }
3436 
3437     CSEMap[&In] = &In;
3438   }
3439 }
3440 
3441 InstructionCost
3442 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3443                                               bool &NeedToScalarize) const {
3444   Function *F = CI->getCalledFunction();
3445   Type *ScalarRetTy = CI->getType();
3446   SmallVector<Type *, 4> Tys, ScalarTys;
3447   for (auto &ArgOp : CI->args())
3448     ScalarTys.push_back(ArgOp->getType());
3449 
3450   // Estimate cost of scalarized vector call. The source operands are assumed
3451   // to be vectors, so we need to extract individual elements from there,
3452   // execute VF scalar calls, and then gather the result into the vector return
3453   // value.
3454   InstructionCost ScalarCallCost =
3455       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3456   if (VF.isScalar())
3457     return ScalarCallCost;
3458 
3459   // Compute corresponding vector type for return value and arguments.
3460   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3461   for (Type *ScalarTy : ScalarTys)
3462     Tys.push_back(ToVectorTy(ScalarTy, VF));
3463 
3464   // Compute costs of unpacking argument values for the scalar calls and
3465   // packing the return values to a vector.
3466   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3467 
3468   InstructionCost Cost =
3469       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3470 
3471   // If we can't emit a vector call for this function, then the currently found
3472   // cost is the cost we need to return.
3473   NeedToScalarize = true;
3474   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3475   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3476 
3477   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3478     return Cost;
3479 
3480   // If the corresponding vector cost is cheaper, return its cost.
3481   InstructionCost VectorCallCost =
3482       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3483   if (VectorCallCost < Cost) {
3484     NeedToScalarize = false;
3485     Cost = VectorCallCost;
3486   }
3487   return Cost;
3488 }
3489 
3490 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3491   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3492     return Elt;
3493   return VectorType::get(Elt, VF);
3494 }
3495 
3496 InstructionCost
3497 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3498                                                    ElementCount VF) const {
3499   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3500   assert(ID && "Expected intrinsic call!");
3501   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3502   FastMathFlags FMF;
3503   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3504     FMF = FPMO->getFastMathFlags();
3505 
3506   SmallVector<const Value *> Arguments(CI->args());
3507   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3508   SmallVector<Type *> ParamTys;
3509   std::transform(FTy->param_begin(), FTy->param_end(),
3510                  std::back_inserter(ParamTys),
3511                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3512 
3513   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3514                                     dyn_cast<IntrinsicInst>(CI));
3515   return TTI.getIntrinsicInstrCost(CostAttrs,
3516                                    TargetTransformInfo::TCK_RecipThroughput);
3517 }
3518 
3519 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3520   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3521   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3522   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3523 }
3524 
3525 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3526   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3527   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3528   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3529 }
3530 
3531 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3532   // For every instruction `I` in MinBWs, truncate the operands, create a
3533   // truncated version of `I` and reextend its result. InstCombine runs
3534   // later and will remove any ext/trunc pairs.
3535   SmallPtrSet<Value *, 4> Erased;
3536   for (const auto &KV : Cost->getMinimalBitwidths()) {
3537     // If the value wasn't vectorized, we must maintain the original scalar
3538     // type. The absence of the value from State indicates that it
3539     // wasn't vectorized.
3540     // FIXME: Should not rely on getVPValue at this point.
3541     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3542     if (!State.hasAnyVectorValue(Def))
3543       continue;
3544     for (unsigned Part = 0; Part < UF; ++Part) {
3545       Value *I = State.get(Def, Part);
3546       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3547         continue;
3548       Type *OriginalTy = I->getType();
3549       Type *ScalarTruncatedTy =
3550           IntegerType::get(OriginalTy->getContext(), KV.second);
3551       auto *TruncatedTy = VectorType::get(
3552           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3553       if (TruncatedTy == OriginalTy)
3554         continue;
3555 
3556       IRBuilder<> B(cast<Instruction>(I));
3557       auto ShrinkOperand = [&](Value *V) -> Value * {
3558         if (auto *ZI = dyn_cast<ZExtInst>(V))
3559           if (ZI->getSrcTy() == TruncatedTy)
3560             return ZI->getOperand(0);
3561         return B.CreateZExtOrTrunc(V, TruncatedTy);
3562       };
3563 
3564       // The actual instruction modification depends on the instruction type,
3565       // unfortunately.
3566       Value *NewI = nullptr;
3567       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3568         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3569                              ShrinkOperand(BO->getOperand(1)));
3570 
3571         // Any wrapping introduced by shrinking this operation shouldn't be
3572         // considered undefined behavior. So, we can't unconditionally copy
3573         // arithmetic wrapping flags to NewI.
3574         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3575       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3576         NewI =
3577             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3578                          ShrinkOperand(CI->getOperand(1)));
3579       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3580         NewI = B.CreateSelect(SI->getCondition(),
3581                               ShrinkOperand(SI->getTrueValue()),
3582                               ShrinkOperand(SI->getFalseValue()));
3583       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3584         switch (CI->getOpcode()) {
3585         default:
3586           llvm_unreachable("Unhandled cast!");
3587         case Instruction::Trunc:
3588           NewI = ShrinkOperand(CI->getOperand(0));
3589           break;
3590         case Instruction::SExt:
3591           NewI = B.CreateSExtOrTrunc(
3592               CI->getOperand(0),
3593               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3594           break;
3595         case Instruction::ZExt:
3596           NewI = B.CreateZExtOrTrunc(
3597               CI->getOperand(0),
3598               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3599           break;
3600         }
3601       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3602         auto Elements0 =
3603             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3604         auto *O0 = B.CreateZExtOrTrunc(
3605             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3606         auto Elements1 =
3607             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3608         auto *O1 = B.CreateZExtOrTrunc(
3609             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3610 
3611         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3612       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3613         // Don't do anything with the operands, just extend the result.
3614         continue;
3615       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3616         auto Elements =
3617             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3618         auto *O0 = B.CreateZExtOrTrunc(
3619             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3620         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3621         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3622       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3623         auto Elements =
3624             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3625         auto *O0 = B.CreateZExtOrTrunc(
3626             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3627         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3628       } else {
3629         // If we don't know what to do, be conservative and don't do anything.
3630         continue;
3631       }
3632 
3633       // Lastly, extend the result.
3634       NewI->takeName(cast<Instruction>(I));
3635       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3636       I->replaceAllUsesWith(Res);
3637       cast<Instruction>(I)->eraseFromParent();
3638       Erased.insert(I);
3639       State.reset(Def, Res, Part);
3640     }
3641   }
3642 
3643   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3644   for (const auto &KV : Cost->getMinimalBitwidths()) {
3645     // If the value wasn't vectorized, we must maintain the original scalar
3646     // type. The absence of the value from State indicates that it
3647     // wasn't vectorized.
3648     // FIXME: Should not rely on getVPValue at this point.
3649     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3650     if (!State.hasAnyVectorValue(Def))
3651       continue;
3652     for (unsigned Part = 0; Part < UF; ++Part) {
3653       Value *I = State.get(Def, Part);
3654       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3655       if (Inst && Inst->use_empty()) {
3656         Value *NewI = Inst->getOperand(0);
3657         Inst->eraseFromParent();
3658         State.reset(Def, NewI, Part);
3659       }
3660     }
3661   }
3662 }
3663 
3664 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State,
3665                                             VPlan &Plan) {
3666   // Insert truncates and extends for any truncated instructions as hints to
3667   // InstCombine.
3668   if (VF.isVector())
3669     truncateToMinimalBitwidths(State);
3670 
3671   // Fix widened non-induction PHIs by setting up the PHI operands.
3672   if (OrigPHIsToFix.size()) {
3673     assert(EnableVPlanNativePath &&
3674            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
3675     fixNonInductionPHIs(State);
3676   }
3677 
3678   // At this point every instruction in the original loop is widened to a
3679   // vector form. Now we need to fix the recurrences in the loop. These PHI
3680   // nodes are currently empty because we did not want to introduce cycles.
3681   // This is the second stage of vectorizing recurrences.
3682   fixCrossIterationPHIs(State);
3683 
3684   // Forget the original basic block.
3685   PSE.getSE()->forgetLoop(OrigLoop);
3686 
3687   VPBasicBlock *LatchVPBB = Plan.getVectorLoopRegion()->getExitBasicBlock();
3688   Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3689   // If we inserted an edge from the middle block to the unique exit block,
3690   // update uses outside the loop (phis) to account for the newly inserted
3691   // edge.
3692   if (!Cost->requiresScalarEpilogue(VF)) {
3693     // Fix-up external users of the induction variables.
3694     for (auto &Entry : Legal->getInductionVars())
3695       fixupIVUsers(Entry.first, Entry.second,
3696                    getOrCreateVectorTripCount(VectorLoop->getLoopPreheader()),
3697                    IVEndValues[Entry.first], LoopMiddleBlock,
3698                    VectorLoop->getHeader());
3699 
3700     fixLCSSAPHIs(State);
3701   }
3702 
3703   for (Instruction *PI : PredicatedInstructions)
3704     sinkScalarOperands(&*PI);
3705 
3706   // Remove redundant induction instructions.
3707   cse(VectorLoop->getHeader());
3708 
3709   // Set/update profile weights for the vector and remainder loops as original
3710   // loop iterations are now distributed among them. Note that original loop
3711   // represented by LoopScalarBody becomes remainder loop after vectorization.
3712   //
3713   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3714   // end up getting slightly roughened result but that should be OK since
3715   // profile is not inherently precise anyway. Note also possible bypass of
3716   // vector code caused by legality checks is ignored, assigning all the weight
3717   // to the vector loop, optimistically.
3718   //
3719   // For scalable vectorization we can't know at compile time how many iterations
3720   // of the loop are handled in one vector iteration, so instead assume a pessimistic
3721   // vscale of '1'.
3722   setProfileInfoAfterUnrolling(LI->getLoopFor(LoopScalarBody), VectorLoop,
3723                                LI->getLoopFor(LoopScalarBody),
3724                                VF.getKnownMinValue() * UF);
3725 }
3726 
3727 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
3728   // In order to support recurrences we need to be able to vectorize Phi nodes.
3729   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3730   // stage #2: We now need to fix the recurrences by adding incoming edges to
3731   // the currently empty PHI nodes. At this point every instruction in the
3732   // original loop is widened to a vector form so we can use them to construct
3733   // the incoming edges.
3734   VPBasicBlock *Header =
3735       State.Plan->getVectorLoopRegion()->getEntryBasicBlock();
3736   for (VPRecipeBase &R : Header->phis()) {
3737     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3738       fixReduction(ReductionPhi, State);
3739     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3740       fixFirstOrderRecurrence(FOR, State);
3741   }
3742 }
3743 
3744 void InnerLoopVectorizer::fixFirstOrderRecurrence(
3745     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
3746   // This is the second phase of vectorizing first-order recurrences. An
3747   // overview of the transformation is described below. Suppose we have the
3748   // following loop.
3749   //
3750   //   for (int i = 0; i < n; ++i)
3751   //     b[i] = a[i] - a[i - 1];
3752   //
3753   // There is a first-order recurrence on "a". For this loop, the shorthand
3754   // scalar IR looks like:
3755   //
3756   //   scalar.ph:
3757   //     s_init = a[-1]
3758   //     br scalar.body
3759   //
3760   //   scalar.body:
3761   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3762   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3763   //     s2 = a[i]
3764   //     b[i] = s2 - s1
3765   //     br cond, scalar.body, ...
3766   //
3767   // In this example, s1 is a recurrence because it's value depends on the
3768   // previous iteration. In the first phase of vectorization, we created a
3769   // vector phi v1 for s1. We now complete the vectorization and produce the
3770   // shorthand vector IR shown below (for VF = 4, UF = 1).
3771   //
3772   //   vector.ph:
3773   //     v_init = vector(..., ..., ..., a[-1])
3774   //     br vector.body
3775   //
3776   //   vector.body
3777   //     i = phi [0, vector.ph], [i+4, vector.body]
3778   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3779   //     v2 = a[i, i+1, i+2, i+3];
3780   //     v3 = vector(v1(3), v2(0, 1, 2))
3781   //     b[i, i+1, i+2, i+3] = v2 - v3
3782   //     br cond, vector.body, middle.block
3783   //
3784   //   middle.block:
3785   //     x = v2(3)
3786   //     br scalar.ph
3787   //
3788   //   scalar.ph:
3789   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3790   //     br scalar.body
3791   //
3792   // After execution completes the vector loop, we extract the next value of
3793   // the recurrence (x) to use as the initial value in the scalar loop.
3794 
3795   // Extract the last vector element in the middle block. This will be the
3796   // initial value for the recurrence when jumping to the scalar loop.
3797   VPValue *PreviousDef = PhiR->getBackedgeValue();
3798   Value *Incoming = State.get(PreviousDef, UF - 1);
3799   auto *ExtractForScalar = Incoming;
3800   auto *IdxTy = Builder.getInt32Ty();
3801   if (VF.isVector()) {
3802     auto *One = ConstantInt::get(IdxTy, 1);
3803     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3804     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3805     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3806     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3807                                                     "vector.recur.extract");
3808   }
3809   // Extract the second last element in the middle block if the
3810   // Phi is used outside the loop. We need to extract the phi itself
3811   // and not the last element (the phi update in the current iteration). This
3812   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3813   // when the scalar loop is not run at all.
3814   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3815   if (VF.isVector()) {
3816     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3817     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3818     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3819         Incoming, Idx, "vector.recur.extract.for.phi");
3820   } else if (UF > 1)
3821     // When loop is unrolled without vectorizing, initialize
3822     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3823     // of `Incoming`. This is analogous to the vectorized case above: extracting
3824     // the second last element when VF > 1.
3825     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3826 
3827   // Fix the initial value of the original recurrence in the scalar loop.
3828   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3829   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3830   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3831   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3832   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3833     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3834     Start->addIncoming(Incoming, BB);
3835   }
3836 
3837   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3838   Phi->setName("scalar.recur");
3839 
3840   // Finally, fix users of the recurrence outside the loop. The users will need
3841   // either the last value of the scalar recurrence or the last value of the
3842   // vector recurrence we extracted in the middle block. Since the loop is in
3843   // LCSSA form, we just need to find all the phi nodes for the original scalar
3844   // recurrence in the exit block, and then add an edge for the middle block.
3845   // Note that LCSSA does not imply single entry when the original scalar loop
3846   // had multiple exiting edges (as we always run the last iteration in the
3847   // scalar epilogue); in that case, there is no edge from middle to exit and
3848   // and thus no phis which needed updated.
3849   if (!Cost->requiresScalarEpilogue(VF))
3850     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3851       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
3852         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3853 }
3854 
3855 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
3856                                        VPTransformState &State) {
3857   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3858   // Get it's reduction variable descriptor.
3859   assert(Legal->isReductionVariable(OrigPhi) &&
3860          "Unable to find the reduction variable");
3861   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3862 
3863   RecurKind RK = RdxDesc.getRecurrenceKind();
3864   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3865   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3866   setDebugLocFromInst(ReductionStartValue);
3867 
3868   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3869   // This is the vector-clone of the value that leaves the loop.
3870   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3871 
3872   // Wrap flags are in general invalid after vectorization, clear them.
3873   clearReductionWrapFlags(RdxDesc, State);
3874 
3875   // Before each round, move the insertion point right between
3876   // the PHIs and the values we are going to write.
3877   // This allows us to write both PHINodes and the extractelement
3878   // instructions.
3879   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3880 
3881   setDebugLocFromInst(LoopExitInst);
3882 
3883   Type *PhiTy = OrigPhi->getType();
3884 
3885   VPBasicBlock *LatchVPBB =
3886       PhiR->getParent()->getEnclosingLoopRegion()->getExitBasicBlock();
3887   BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3888   // If tail is folded by masking, the vector value to leave the loop should be
3889   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3890   // instead of the former. For an inloop reduction the reduction will already
3891   // be predicated, and does not need to be handled here.
3892   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3893     for (unsigned Part = 0; Part < UF; ++Part) {
3894       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3895       Value *Sel = nullptr;
3896       for (User *U : VecLoopExitInst->users()) {
3897         if (isa<SelectInst>(U)) {
3898           assert(!Sel && "Reduction exit feeding two selects");
3899           Sel = U;
3900         } else
3901           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3902       }
3903       assert(Sel && "Reduction exit feeds no select");
3904       State.reset(LoopExitInstDef, Sel, Part);
3905 
3906       // If the target can create a predicated operator for the reduction at no
3907       // extra cost in the loop (for example a predicated vadd), it can be
3908       // cheaper for the select to remain in the loop than be sunk out of it,
3909       // and so use the select value for the phi instead of the old
3910       // LoopExitValue.
3911       if (PreferPredicatedReductionSelect ||
3912           TTI->preferPredicatedReductionSelect(
3913               RdxDesc.getOpcode(), PhiTy,
3914               TargetTransformInfo::ReductionFlags())) {
3915         auto *VecRdxPhi =
3916             cast<PHINode>(State.get(PhiR, Part));
3917         VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3918       }
3919     }
3920   }
3921 
3922   // If the vector reduction can be performed in a smaller type, we truncate
3923   // then extend the loop exit value to enable InstCombine to evaluate the
3924   // entire expression in the smaller type.
3925   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3926     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3927     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3928     Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3929     VectorParts RdxParts(UF);
3930     for (unsigned Part = 0; Part < UF; ++Part) {
3931       RdxParts[Part] = State.get(LoopExitInstDef, Part);
3932       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3933       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3934                                         : Builder.CreateZExt(Trunc, VecTy);
3935       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3936         if (U != Trunc) {
3937           U->replaceUsesOfWith(RdxParts[Part], Extnd);
3938           RdxParts[Part] = Extnd;
3939         }
3940     }
3941     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3942     for (unsigned Part = 0; Part < UF; ++Part) {
3943       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3944       State.reset(LoopExitInstDef, RdxParts[Part], Part);
3945     }
3946   }
3947 
3948   // Reduce all of the unrolled parts into a single vector.
3949   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3950   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3951 
3952   // The middle block terminator has already been assigned a DebugLoc here (the
3953   // OrigLoop's single latch terminator). We want the whole middle block to
3954   // appear to execute on this line because: (a) it is all compiler generated,
3955   // (b) these instructions are always executed after evaluating the latch
3956   // conditional branch, and (c) other passes may add new predecessors which
3957   // terminate on this line. This is the easiest way to ensure we don't
3958   // accidentally cause an extra step back into the loop while debugging.
3959   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
3960   if (PhiR->isOrdered())
3961     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3962   else {
3963     // Floating-point operations should have some FMF to enable the reduction.
3964     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
3965     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
3966     for (unsigned Part = 1; Part < UF; ++Part) {
3967       Value *RdxPart = State.get(LoopExitInstDef, Part);
3968       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3969         ReducedPartRdx = Builder.CreateBinOp(
3970             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3971       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
3972         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3973                                            ReducedPartRdx, RdxPart);
3974       else
3975         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3976     }
3977   }
3978 
3979   // Create the reduction after the loop. Note that inloop reductions create the
3980   // target reduction in the loop using a Reduction recipe.
3981   if (VF.isVector() && !PhiR->isInLoop()) {
3982     ReducedPartRdx =
3983         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3984     // If the reduction can be performed in a smaller type, we need to extend
3985     // the reduction to the wider type before we branch to the original loop.
3986     if (PhiTy != RdxDesc.getRecurrenceType())
3987       ReducedPartRdx = RdxDesc.isSigned()
3988                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
3989                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
3990   }
3991 
3992   PHINode *ResumePhi =
3993       dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
3994 
3995   // Create a phi node that merges control-flow from the backedge-taken check
3996   // block and the middle block.
3997   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
3998                                         LoopScalarPreHeader->getTerminator());
3999 
4000   // If we are fixing reductions in the epilogue loop then we should already
4001   // have created a bc.merge.rdx Phi after the main vector body. Ensure that
4002   // we carry over the incoming values correctly.
4003   for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
4004     if (Incoming == LoopMiddleBlock)
4005       BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4006     else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4007       BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4008                               Incoming);
4009     else
4010       BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4011   }
4012 
4013   // Set the resume value for this reduction
4014   ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4015 
4016   // If there were stores of the reduction value to a uniform memory address
4017   // inside the loop, create the final store here.
4018   if (StoreInst *SI = RdxDesc.IntermediateStore) {
4019     StoreInst *NewSI =
4020         Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4021     propagateMetadata(NewSI, SI);
4022 
4023     // If the reduction value is used in other places,
4024     // then let the code below create PHI's for that.
4025   }
4026 
4027   // Now, we need to fix the users of the reduction variable
4028   // inside and outside of the scalar remainder loop.
4029 
4030   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4031   // in the exit blocks.  See comment on analogous loop in
4032   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4033   if (!Cost->requiresScalarEpilogue(VF))
4034     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4035       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4036         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4037 
4038   // Fix the scalar loop reduction variable with the incoming reduction sum
4039   // from the vector body and from the backedge value.
4040   int IncomingEdgeBlockIdx =
4041       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4042   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4043   // Pick the other block.
4044   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4045   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4046   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4047 }
4048 
4049 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4050                                                   VPTransformState &State) {
4051   RecurKind RK = RdxDesc.getRecurrenceKind();
4052   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4053     return;
4054 
4055   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4056   assert(LoopExitInstr && "null loop exit instruction");
4057   SmallVector<Instruction *, 8> Worklist;
4058   SmallPtrSet<Instruction *, 8> Visited;
4059   Worklist.push_back(LoopExitInstr);
4060   Visited.insert(LoopExitInstr);
4061 
4062   while (!Worklist.empty()) {
4063     Instruction *Cur = Worklist.pop_back_val();
4064     if (isa<OverflowingBinaryOperator>(Cur))
4065       for (unsigned Part = 0; Part < UF; ++Part) {
4066         // FIXME: Should not rely on getVPValue at this point.
4067         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4068         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4069       }
4070 
4071     for (User *U : Cur->users()) {
4072       Instruction *UI = cast<Instruction>(U);
4073       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4074           Visited.insert(UI).second)
4075         Worklist.push_back(UI);
4076     }
4077   }
4078 }
4079 
4080 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4081   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4082     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4083       // Some phis were already hand updated by the reduction and recurrence
4084       // code above, leave them alone.
4085       continue;
4086 
4087     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4088     // Non-instruction incoming values will have only one value.
4089 
4090     VPLane Lane = VPLane::getFirstLane();
4091     if (isa<Instruction>(IncomingValue) &&
4092         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4093                                            VF))
4094       Lane = VPLane::getLastLaneForVF(VF);
4095 
4096     // Can be a loop invariant incoming value or the last scalar value to be
4097     // extracted from the vectorized loop.
4098     // FIXME: Should not rely on getVPValue at this point.
4099     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4100     Value *lastIncomingValue =
4101         OrigLoop->isLoopInvariant(IncomingValue)
4102             ? IncomingValue
4103             : State.get(State.Plan->getVPValue(IncomingValue, true),
4104                         VPIteration(UF - 1, Lane));
4105     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4106   }
4107 }
4108 
4109 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4110   // The basic block and loop containing the predicated instruction.
4111   auto *PredBB = PredInst->getParent();
4112   auto *VectorLoop = LI->getLoopFor(PredBB);
4113 
4114   // Initialize a worklist with the operands of the predicated instruction.
4115   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4116 
4117   // Holds instructions that we need to analyze again. An instruction may be
4118   // reanalyzed if we don't yet know if we can sink it or not.
4119   SmallVector<Instruction *, 8> InstsToReanalyze;
4120 
4121   // Returns true if a given use occurs in the predicated block. Phi nodes use
4122   // their operands in their corresponding predecessor blocks.
4123   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4124     auto *I = cast<Instruction>(U.getUser());
4125     BasicBlock *BB = I->getParent();
4126     if (auto *Phi = dyn_cast<PHINode>(I))
4127       BB = Phi->getIncomingBlock(
4128           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4129     return BB == PredBB;
4130   };
4131 
4132   // Iteratively sink the scalarized operands of the predicated instruction
4133   // into the block we created for it. When an instruction is sunk, it's
4134   // operands are then added to the worklist. The algorithm ends after one pass
4135   // through the worklist doesn't sink a single instruction.
4136   bool Changed;
4137   do {
4138     // Add the instructions that need to be reanalyzed to the worklist, and
4139     // reset the changed indicator.
4140     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4141     InstsToReanalyze.clear();
4142     Changed = false;
4143 
4144     while (!Worklist.empty()) {
4145       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4146 
4147       // We can't sink an instruction if it is a phi node, is not in the loop,
4148       // or may have side effects.
4149       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4150           I->mayHaveSideEffects())
4151         continue;
4152 
4153       // If the instruction is already in PredBB, check if we can sink its
4154       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4155       // sinking the scalar instruction I, hence it appears in PredBB; but it
4156       // may have failed to sink I's operands (recursively), which we try
4157       // (again) here.
4158       if (I->getParent() == PredBB) {
4159         Worklist.insert(I->op_begin(), I->op_end());
4160         continue;
4161       }
4162 
4163       // It's legal to sink the instruction if all its uses occur in the
4164       // predicated block. Otherwise, there's nothing to do yet, and we may
4165       // need to reanalyze the instruction.
4166       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4167         InstsToReanalyze.push_back(I);
4168         continue;
4169       }
4170 
4171       // Move the instruction to the beginning of the predicated block, and add
4172       // it's operands to the worklist.
4173       I->moveBefore(&*PredBB->getFirstInsertionPt());
4174       Worklist.insert(I->op_begin(), I->op_end());
4175 
4176       // The sinking may have enabled other instructions to be sunk, so we will
4177       // need to iterate.
4178       Changed = true;
4179     }
4180   } while (Changed);
4181 }
4182 
4183 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4184   for (PHINode *OrigPhi : OrigPHIsToFix) {
4185     VPWidenPHIRecipe *VPPhi =
4186         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4187     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4188     // Make sure the builder has a valid insert point.
4189     Builder.SetInsertPoint(NewPhi);
4190     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4191       VPValue *Inc = VPPhi->getIncomingValue(i);
4192       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4193       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4194     }
4195   }
4196 }
4197 
4198 bool InnerLoopVectorizer::useOrderedReductions(
4199     const RecurrenceDescriptor &RdxDesc) {
4200   return Cost->useOrderedReductions(RdxDesc);
4201 }
4202 
4203 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4204                                               VPWidenPHIRecipe *PhiR,
4205                                               VPTransformState &State) {
4206   assert(EnableVPlanNativePath &&
4207          "Non-native vplans are not expected to have VPWidenPHIRecipes.");
4208   // Currently we enter here in the VPlan-native path for non-induction
4209   // PHIs where all control flow is uniform. We simply widen these PHIs.
4210   // Create a vector phi with no operands - the vector phi operands will be
4211   // set at the end of vector code generation.
4212   Type *VecTy = (State.VF.isScalar())
4213                     ? PN->getType()
4214                     : VectorType::get(PN->getType(), State.VF);
4215   Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4216   State.set(PhiR, VecPhi, 0);
4217   OrigPHIsToFix.push_back(cast<PHINode>(PN));
4218 }
4219 
4220 /// A helper function for checking whether an integer division-related
4221 /// instruction may divide by zero (in which case it must be predicated if
4222 /// executed conditionally in the scalar code).
4223 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4224 /// Non-zero divisors that are non compile-time constants will not be
4225 /// converted into multiplication, so we will still end up scalarizing
4226 /// the division, but can do so w/o predication.
4227 static bool mayDivideByZero(Instruction &I) {
4228   assert((I.getOpcode() == Instruction::UDiv ||
4229           I.getOpcode() == Instruction::SDiv ||
4230           I.getOpcode() == Instruction::URem ||
4231           I.getOpcode() == Instruction::SRem) &&
4232          "Unexpected instruction");
4233   Value *Divisor = I.getOperand(1);
4234   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4235   return !CInt || CInt->isZero();
4236 }
4237 
4238 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4239                                                VPUser &ArgOperands,
4240                                                VPTransformState &State) {
4241   assert(!isa<DbgInfoIntrinsic>(I) &&
4242          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4243   setDebugLocFromInst(&I);
4244 
4245   Module *M = I.getParent()->getParent()->getParent();
4246   auto *CI = cast<CallInst>(&I);
4247 
4248   SmallVector<Type *, 4> Tys;
4249   for (Value *ArgOperand : CI->args())
4250     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4251 
4252   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4253 
4254   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4255   // version of the instruction.
4256   // Is it beneficial to perform intrinsic call compared to lib call?
4257   bool NeedToScalarize = false;
4258   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4259   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4260   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4261   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4262          "Instruction should be scalarized elsewhere.");
4263   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4264          "Either the intrinsic cost or vector call cost must be valid");
4265 
4266   for (unsigned Part = 0; Part < UF; ++Part) {
4267     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4268     SmallVector<Value *, 4> Args;
4269     for (auto &I : enumerate(ArgOperands.operands())) {
4270       // Some intrinsics have a scalar argument - don't replace it with a
4271       // vector.
4272       Value *Arg;
4273       if (!UseVectorIntrinsic ||
4274           !isVectorIntrinsicWithScalarOpAtArg(ID, I.index()))
4275         Arg = State.get(I.value(), Part);
4276       else
4277         Arg = State.get(I.value(), VPIteration(0, 0));
4278       if (isVectorIntrinsicWithOverloadTypeAtArg(ID, I.index()))
4279         TysForDecl.push_back(Arg->getType());
4280       Args.push_back(Arg);
4281     }
4282 
4283     Function *VectorF;
4284     if (UseVectorIntrinsic) {
4285       // Use vector version of the intrinsic.
4286       if (VF.isVector())
4287         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4288       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4289       assert(VectorF && "Can't retrieve vector intrinsic.");
4290     } else {
4291       // Use vector version of the function call.
4292       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4293 #ifndef NDEBUG
4294       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4295              "Can't create vector function.");
4296 #endif
4297         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4298     }
4299       SmallVector<OperandBundleDef, 1> OpBundles;
4300       CI->getOperandBundlesAsDefs(OpBundles);
4301       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4302 
4303       if (isa<FPMathOperator>(V))
4304         V->copyFastMathFlags(CI);
4305 
4306       State.set(Def, V, Part);
4307       addMetadata(V, &I);
4308   }
4309 }
4310 
4311 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4312   // We should not collect Scalars more than once per VF. Right now, this
4313   // function is called from collectUniformsAndScalars(), which already does
4314   // this check. Collecting Scalars for VF=1 does not make any sense.
4315   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4316          "This function should not be visited twice for the same VF");
4317 
4318   // This avoids any chances of creating a REPLICATE recipe during planning
4319   // since that would result in generation of scalarized code during execution,
4320   // which is not supported for scalable vectors.
4321   if (VF.isScalable()) {
4322     Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4323     return;
4324   }
4325 
4326   SmallSetVector<Instruction *, 8> Worklist;
4327 
4328   // These sets are used to seed the analysis with pointers used by memory
4329   // accesses that will remain scalar.
4330   SmallSetVector<Instruction *, 8> ScalarPtrs;
4331   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4332   auto *Latch = TheLoop->getLoopLatch();
4333 
4334   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4335   // The pointer operands of loads and stores will be scalar as long as the
4336   // memory access is not a gather or scatter operation. The value operand of a
4337   // store will remain scalar if the store is scalarized.
4338   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4339     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4340     assert(WideningDecision != CM_Unknown &&
4341            "Widening decision should be ready at this moment");
4342     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4343       if (Ptr == Store->getValueOperand())
4344         return WideningDecision == CM_Scalarize;
4345     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4346            "Ptr is neither a value or pointer operand");
4347     return WideningDecision != CM_GatherScatter;
4348   };
4349 
4350   // A helper that returns true if the given value is a bitcast or
4351   // getelementptr instruction contained in the loop.
4352   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4353     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4354             isa<GetElementPtrInst>(V)) &&
4355            !TheLoop->isLoopInvariant(V);
4356   };
4357 
4358   // A helper that evaluates a memory access's use of a pointer. If the use will
4359   // be a scalar use and the pointer is only used by memory accesses, we place
4360   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4361   // PossibleNonScalarPtrs.
4362   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4363     // We only care about bitcast and getelementptr instructions contained in
4364     // the loop.
4365     if (!isLoopVaryingBitCastOrGEP(Ptr))
4366       return;
4367 
4368     // If the pointer has already been identified as scalar (e.g., if it was
4369     // also identified as uniform), there's nothing to do.
4370     auto *I = cast<Instruction>(Ptr);
4371     if (Worklist.count(I))
4372       return;
4373 
4374     // If the use of the pointer will be a scalar use, and all users of the
4375     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4376     // place the pointer in PossibleNonScalarPtrs.
4377     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4378           return isa<LoadInst>(U) || isa<StoreInst>(U);
4379         }))
4380       ScalarPtrs.insert(I);
4381     else
4382       PossibleNonScalarPtrs.insert(I);
4383   };
4384 
4385   // We seed the scalars analysis with three classes of instructions: (1)
4386   // instructions marked uniform-after-vectorization and (2) bitcast,
4387   // getelementptr and (pointer) phi instructions used by memory accesses
4388   // requiring a scalar use.
4389   //
4390   // (1) Add to the worklist all instructions that have been identified as
4391   // uniform-after-vectorization.
4392   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4393 
4394   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4395   // memory accesses requiring a scalar use. The pointer operands of loads and
4396   // stores will be scalar as long as the memory accesses is not a gather or
4397   // scatter operation. The value operand of a store will remain scalar if the
4398   // store is scalarized.
4399   for (auto *BB : TheLoop->blocks())
4400     for (auto &I : *BB) {
4401       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4402         evaluatePtrUse(Load, Load->getPointerOperand());
4403       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4404         evaluatePtrUse(Store, Store->getPointerOperand());
4405         evaluatePtrUse(Store, Store->getValueOperand());
4406       }
4407     }
4408   for (auto *I : ScalarPtrs)
4409     if (!PossibleNonScalarPtrs.count(I)) {
4410       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4411       Worklist.insert(I);
4412     }
4413 
4414   // Insert the forced scalars.
4415   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4416   // induction variable when the PHI user is scalarized.
4417   auto ForcedScalar = ForcedScalars.find(VF);
4418   if (ForcedScalar != ForcedScalars.end())
4419     for (auto *I : ForcedScalar->second)
4420       Worklist.insert(I);
4421 
4422   // Expand the worklist by looking through any bitcasts and getelementptr
4423   // instructions we've already identified as scalar. This is similar to the
4424   // expansion step in collectLoopUniforms(); however, here we're only
4425   // expanding to include additional bitcasts and getelementptr instructions.
4426   unsigned Idx = 0;
4427   while (Idx != Worklist.size()) {
4428     Instruction *Dst = Worklist[Idx++];
4429     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4430       continue;
4431     auto *Src = cast<Instruction>(Dst->getOperand(0));
4432     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4433           auto *J = cast<Instruction>(U);
4434           return !TheLoop->contains(J) || Worklist.count(J) ||
4435                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4436                   isScalarUse(J, Src));
4437         })) {
4438       Worklist.insert(Src);
4439       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4440     }
4441   }
4442 
4443   // An induction variable will remain scalar if all users of the induction
4444   // variable and induction variable update remain scalar.
4445   for (auto &Induction : Legal->getInductionVars()) {
4446     auto *Ind = Induction.first;
4447     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4448 
4449     // If tail-folding is applied, the primary induction variable will be used
4450     // to feed a vector compare.
4451     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4452       continue;
4453 
4454     // Returns true if \p Indvar is a pointer induction that is used directly by
4455     // load/store instruction \p I.
4456     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4457                                               Instruction *I) {
4458       return Induction.second.getKind() ==
4459                  InductionDescriptor::IK_PtrInduction &&
4460              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4461              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4462     };
4463 
4464     // Determine if all users of the induction variable are scalar after
4465     // vectorization.
4466     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4467       auto *I = cast<Instruction>(U);
4468       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4469              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4470     });
4471     if (!ScalarInd)
4472       continue;
4473 
4474     // Determine if all users of the induction variable update instruction are
4475     // scalar after vectorization.
4476     auto ScalarIndUpdate =
4477         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4478           auto *I = cast<Instruction>(U);
4479           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4480                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4481         });
4482     if (!ScalarIndUpdate)
4483       continue;
4484 
4485     // The induction variable and its update instruction will remain scalar.
4486     Worklist.insert(Ind);
4487     Worklist.insert(IndUpdate);
4488     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4489     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4490                       << "\n");
4491   }
4492 
4493   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4494 }
4495 
4496 bool LoopVectorizationCostModel::isScalarWithPredication(
4497     Instruction *I, ElementCount VF) const {
4498   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4499     return false;
4500   switch(I->getOpcode()) {
4501   default:
4502     break;
4503   case Instruction::Load:
4504   case Instruction::Store: {
4505     if (!Legal->isMaskRequired(I))
4506       return false;
4507     auto *Ptr = getLoadStorePointerOperand(I);
4508     auto *Ty = getLoadStoreType(I);
4509     Type *VTy = Ty;
4510     if (VF.isVector())
4511       VTy = VectorType::get(Ty, VF);
4512     const Align Alignment = getLoadStoreAlignment(I);
4513     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4514                                 TTI.isLegalMaskedGather(VTy, Alignment))
4515                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4516                                 TTI.isLegalMaskedScatter(VTy, Alignment));
4517   }
4518   case Instruction::UDiv:
4519   case Instruction::SDiv:
4520   case Instruction::SRem:
4521   case Instruction::URem:
4522     return mayDivideByZero(*I);
4523   }
4524   return false;
4525 }
4526 
4527 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4528     Instruction *I, ElementCount VF) {
4529   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4530   assert(getWideningDecision(I, VF) == CM_Unknown &&
4531          "Decision should not be set yet.");
4532   auto *Group = getInterleavedAccessGroup(I);
4533   assert(Group && "Must have a group.");
4534 
4535   // If the instruction's allocated size doesn't equal it's type size, it
4536   // requires padding and will be scalarized.
4537   auto &DL = I->getModule()->getDataLayout();
4538   auto *ScalarTy = getLoadStoreType(I);
4539   if (hasIrregularType(ScalarTy, DL))
4540     return false;
4541 
4542   // If the group involves a non-integral pointer, we may not be able to
4543   // losslessly cast all values to a common type.
4544   unsigned InterleaveFactor = Group->getFactor();
4545   bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
4546   for (unsigned i = 0; i < InterleaveFactor; i++) {
4547     Instruction *Member = Group->getMember(i);
4548     if (!Member)
4549       continue;
4550     auto *MemberTy = getLoadStoreType(Member);
4551     bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
4552     // Don't coerce non-integral pointers to integers or vice versa.
4553     if (MemberNI != ScalarNI) {
4554       // TODO: Consider adding special nullptr value case here
4555       return false;
4556     } else if (MemberNI && ScalarNI &&
4557                ScalarTy->getPointerAddressSpace() !=
4558                MemberTy->getPointerAddressSpace()) {
4559       return false;
4560     }
4561   }
4562 
4563   // Check if masking is required.
4564   // A Group may need masking for one of two reasons: it resides in a block that
4565   // needs predication, or it was decided to use masking to deal with gaps
4566   // (either a gap at the end of a load-access that may result in a speculative
4567   // load, or any gaps in a store-access).
4568   bool PredicatedAccessRequiresMasking =
4569       blockNeedsPredicationForAnyReason(I->getParent()) &&
4570       Legal->isMaskRequired(I);
4571   bool LoadAccessWithGapsRequiresEpilogMasking =
4572       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4573       !isScalarEpilogueAllowed();
4574   bool StoreAccessWithGapsRequiresMasking =
4575       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4576   if (!PredicatedAccessRequiresMasking &&
4577       !LoadAccessWithGapsRequiresEpilogMasking &&
4578       !StoreAccessWithGapsRequiresMasking)
4579     return true;
4580 
4581   // If masked interleaving is required, we expect that the user/target had
4582   // enabled it, because otherwise it either wouldn't have been created or
4583   // it should have been invalidated by the CostModel.
4584   assert(useMaskedInterleavedAccesses(TTI) &&
4585          "Masked interleave-groups for predicated accesses are not enabled.");
4586 
4587   if (Group->isReverse())
4588     return false;
4589 
4590   auto *Ty = getLoadStoreType(I);
4591   const Align Alignment = getLoadStoreAlignment(I);
4592   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4593                           : TTI.isLegalMaskedStore(Ty, Alignment);
4594 }
4595 
4596 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4597     Instruction *I, ElementCount VF) {
4598   // Get and ensure we have a valid memory instruction.
4599   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4600 
4601   auto *Ptr = getLoadStorePointerOperand(I);
4602   auto *ScalarTy = getLoadStoreType(I);
4603 
4604   // In order to be widened, the pointer should be consecutive, first of all.
4605   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4606     return false;
4607 
4608   // If the instruction is a store located in a predicated block, it will be
4609   // scalarized.
4610   if (isScalarWithPredication(I, VF))
4611     return false;
4612 
4613   // If the instruction's allocated size doesn't equal it's type size, it
4614   // requires padding and will be scalarized.
4615   auto &DL = I->getModule()->getDataLayout();
4616   if (hasIrregularType(ScalarTy, DL))
4617     return false;
4618 
4619   return true;
4620 }
4621 
4622 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4623   // We should not collect Uniforms more than once per VF. Right now,
4624   // this function is called from collectUniformsAndScalars(), which
4625   // already does this check. Collecting Uniforms for VF=1 does not make any
4626   // sense.
4627 
4628   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4629          "This function should not be visited twice for the same VF");
4630 
4631   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4632   // not analyze again.  Uniforms.count(VF) will return 1.
4633   Uniforms[VF].clear();
4634 
4635   // We now know that the loop is vectorizable!
4636   // Collect instructions inside the loop that will remain uniform after
4637   // vectorization.
4638 
4639   // Global values, params and instructions outside of current loop are out of
4640   // scope.
4641   auto isOutOfScope = [&](Value *V) -> bool {
4642     Instruction *I = dyn_cast<Instruction>(V);
4643     return (!I || !TheLoop->contains(I));
4644   };
4645 
4646   // Worklist containing uniform instructions demanding lane 0.
4647   SetVector<Instruction *> Worklist;
4648   BasicBlock *Latch = TheLoop->getLoopLatch();
4649 
4650   // Add uniform instructions demanding lane 0 to the worklist. Instructions
4651   // that are scalar with predication must not be considered uniform after
4652   // vectorization, because that would create an erroneous replicating region
4653   // where only a single instance out of VF should be formed.
4654   // TODO: optimize such seldom cases if found important, see PR40816.
4655   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4656     if (isOutOfScope(I)) {
4657       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4658                         << *I << "\n");
4659       return;
4660     }
4661     if (isScalarWithPredication(I, VF)) {
4662       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4663                         << *I << "\n");
4664       return;
4665     }
4666     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4667     Worklist.insert(I);
4668   };
4669 
4670   // Start with the conditional branch. If the branch condition is an
4671   // instruction contained in the loop that is only used by the branch, it is
4672   // uniform.
4673   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4674   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4675     addToWorklistIfAllowed(Cmp);
4676 
4677   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
4678     InstWidening WideningDecision = getWideningDecision(I, VF);
4679     assert(WideningDecision != CM_Unknown &&
4680            "Widening decision should be ready at this moment");
4681 
4682     // A uniform memory op is itself uniform.  We exclude uniform stores
4683     // here as they demand the last lane, not the first one.
4684     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
4685       assert(WideningDecision == CM_Scalarize);
4686       return true;
4687     }
4688 
4689     return (WideningDecision == CM_Widen ||
4690             WideningDecision == CM_Widen_Reverse ||
4691             WideningDecision == CM_Interleave);
4692   };
4693 
4694 
4695   // Returns true if Ptr is the pointer operand of a memory access instruction
4696   // I, and I is known to not require scalarization.
4697   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4698     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4699   };
4700 
4701   // Holds a list of values which are known to have at least one uniform use.
4702   // Note that there may be other uses which aren't uniform.  A "uniform use"
4703   // here is something which only demands lane 0 of the unrolled iterations;
4704   // it does not imply that all lanes produce the same value (e.g. this is not
4705   // the usual meaning of uniform)
4706   SetVector<Value *> HasUniformUse;
4707 
4708   // Scan the loop for instructions which are either a) known to have only
4709   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
4710   for (auto *BB : TheLoop->blocks())
4711     for (auto &I : *BB) {
4712       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
4713         switch (II->getIntrinsicID()) {
4714         case Intrinsic::sideeffect:
4715         case Intrinsic::experimental_noalias_scope_decl:
4716         case Intrinsic::assume:
4717         case Intrinsic::lifetime_start:
4718         case Intrinsic::lifetime_end:
4719           if (TheLoop->hasLoopInvariantOperands(&I))
4720             addToWorklistIfAllowed(&I);
4721           break;
4722         default:
4723           break;
4724         }
4725       }
4726 
4727       // ExtractValue instructions must be uniform, because the operands are
4728       // known to be loop-invariant.
4729       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
4730         assert(isOutOfScope(EVI->getAggregateOperand()) &&
4731                "Expected aggregate value to be loop invariant");
4732         addToWorklistIfAllowed(EVI);
4733         continue;
4734       }
4735 
4736       // If there's no pointer operand, there's nothing to do.
4737       auto *Ptr = getLoadStorePointerOperand(&I);
4738       if (!Ptr)
4739         continue;
4740 
4741       // A uniform memory op is itself uniform.  We exclude uniform stores
4742       // here as they demand the last lane, not the first one.
4743       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
4744         addToWorklistIfAllowed(&I);
4745 
4746       if (isUniformDecision(&I, VF)) {
4747         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
4748         HasUniformUse.insert(Ptr);
4749       }
4750     }
4751 
4752   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
4753   // demanding) users.  Since loops are assumed to be in LCSSA form, this
4754   // disallows uses outside the loop as well.
4755   for (auto *V : HasUniformUse) {
4756     if (isOutOfScope(V))
4757       continue;
4758     auto *I = cast<Instruction>(V);
4759     auto UsersAreMemAccesses =
4760       llvm::all_of(I->users(), [&](User *U) -> bool {
4761         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4762       });
4763     if (UsersAreMemAccesses)
4764       addToWorklistIfAllowed(I);
4765   }
4766 
4767   // Expand Worklist in topological order: whenever a new instruction
4768   // is added , its users should be already inside Worklist.  It ensures
4769   // a uniform instruction will only be used by uniform instructions.
4770   unsigned idx = 0;
4771   while (idx != Worklist.size()) {
4772     Instruction *I = Worklist[idx++];
4773 
4774     for (auto OV : I->operand_values()) {
4775       // isOutOfScope operands cannot be uniform instructions.
4776       if (isOutOfScope(OV))
4777         continue;
4778       // First order recurrence Phi's should typically be considered
4779       // non-uniform.
4780       auto *OP = dyn_cast<PHINode>(OV);
4781       if (OP && Legal->isFirstOrderRecurrence(OP))
4782         continue;
4783       // If all the users of the operand are uniform, then add the
4784       // operand into the uniform worklist.
4785       auto *OI = cast<Instruction>(OV);
4786       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4787             auto *J = cast<Instruction>(U);
4788             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4789           }))
4790         addToWorklistIfAllowed(OI);
4791     }
4792   }
4793 
4794   // For an instruction to be added into Worklist above, all its users inside
4795   // the loop should also be in Worklist. However, this condition cannot be
4796   // true for phi nodes that form a cyclic dependence. We must process phi
4797   // nodes separately. An induction variable will remain uniform if all users
4798   // of the induction variable and induction variable update remain uniform.
4799   // The code below handles both pointer and non-pointer induction variables.
4800   for (auto &Induction : Legal->getInductionVars()) {
4801     auto *Ind = Induction.first;
4802     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4803 
4804     // Determine if all users of the induction variable are uniform after
4805     // vectorization.
4806     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4807       auto *I = cast<Instruction>(U);
4808       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4809              isVectorizedMemAccessUse(I, Ind);
4810     });
4811     if (!UniformInd)
4812       continue;
4813 
4814     // Determine if all users of the induction variable update instruction are
4815     // uniform after vectorization.
4816     auto UniformIndUpdate =
4817         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4818           auto *I = cast<Instruction>(U);
4819           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4820                  isVectorizedMemAccessUse(I, IndUpdate);
4821         });
4822     if (!UniformIndUpdate)
4823       continue;
4824 
4825     // The induction variable and its update instruction will remain uniform.
4826     addToWorklistIfAllowed(Ind);
4827     addToWorklistIfAllowed(IndUpdate);
4828   }
4829 
4830   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4831 }
4832 
4833 bool LoopVectorizationCostModel::runtimeChecksRequired() {
4834   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
4835 
4836   if (Legal->getRuntimePointerChecking()->Need) {
4837     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
4838         "runtime pointer checks needed. Enable vectorization of this "
4839         "loop with '#pragma clang loop vectorize(enable)' when "
4840         "compiling with -Os/-Oz",
4841         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4842     return true;
4843   }
4844 
4845   if (!PSE.getPredicate().isAlwaysTrue()) {
4846     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
4847         "runtime SCEV checks needed. Enable vectorization of this "
4848         "loop with '#pragma clang loop vectorize(enable)' when "
4849         "compiling with -Os/-Oz",
4850         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4851     return true;
4852   }
4853 
4854   // FIXME: Avoid specializing for stride==1 instead of bailing out.
4855   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
4856     reportVectorizationFailure("Runtime stride check for small trip count",
4857         "runtime stride == 1 checks needed. Enable vectorization of "
4858         "this loop without such check by compiling with -Os/-Oz",
4859         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4860     return true;
4861   }
4862 
4863   return false;
4864 }
4865 
4866 ElementCount
4867 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
4868   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
4869     return ElementCount::getScalable(0);
4870 
4871   if (Hints->isScalableVectorizationDisabled()) {
4872     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
4873                             "ScalableVectorizationDisabled", ORE, TheLoop);
4874     return ElementCount::getScalable(0);
4875   }
4876 
4877   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
4878 
4879   auto MaxScalableVF = ElementCount::getScalable(
4880       std::numeric_limits<ElementCount::ScalarTy>::max());
4881 
4882   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
4883   // FIXME: While for scalable vectors this is currently sufficient, this should
4884   // be replaced by a more detailed mechanism that filters out specific VFs,
4885   // instead of invalidating vectorization for a whole set of VFs based on the
4886   // MaxVF.
4887 
4888   // Disable scalable vectorization if the loop contains unsupported reductions.
4889   if (!canVectorizeReductions(MaxScalableVF)) {
4890     reportVectorizationInfo(
4891         "Scalable vectorization not supported for the reduction "
4892         "operations found in this loop.",
4893         "ScalableVFUnfeasible", ORE, TheLoop);
4894     return ElementCount::getScalable(0);
4895   }
4896 
4897   // Disable scalable vectorization if the loop contains any instructions
4898   // with element types not supported for scalable vectors.
4899   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
4900         return !Ty->isVoidTy() &&
4901                !this->TTI.isElementTypeLegalForScalableVector(Ty);
4902       })) {
4903     reportVectorizationInfo("Scalable vectorization is not supported "
4904                             "for all element types found in this loop.",
4905                             "ScalableVFUnfeasible", ORE, TheLoop);
4906     return ElementCount::getScalable(0);
4907   }
4908 
4909   if (Legal->isSafeForAnyVectorWidth())
4910     return MaxScalableVF;
4911 
4912   // Limit MaxScalableVF by the maximum safe dependence distance.
4913   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
4914   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
4915     MaxVScale =
4916         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
4917   MaxScalableVF = ElementCount::getScalable(
4918       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
4919   if (!MaxScalableVF)
4920     reportVectorizationInfo(
4921         "Max legal vector width too small, scalable vectorization "
4922         "unfeasible.",
4923         "ScalableVFUnfeasible", ORE, TheLoop);
4924 
4925   return MaxScalableVF;
4926 }
4927 
4928 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
4929     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
4930   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4931   unsigned SmallestType, WidestType;
4932   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4933 
4934   // Get the maximum safe dependence distance in bits computed by LAA.
4935   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4936   // the memory accesses that is most restrictive (involved in the smallest
4937   // dependence distance).
4938   unsigned MaxSafeElements =
4939       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
4940 
4941   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
4942   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4943 
4944   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
4945                     << ".\n");
4946   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
4947                     << ".\n");
4948 
4949   // First analyze the UserVF, fall back if the UserVF should be ignored.
4950   if (UserVF) {
4951     auto MaxSafeUserVF =
4952         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4953 
4954     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
4955       // If `VF=vscale x N` is safe, then so is `VF=N`
4956       if (UserVF.isScalable())
4957         return FixedScalableVFPair(
4958             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
4959       else
4960         return UserVF;
4961     }
4962 
4963     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
4964 
4965     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
4966     // is better to ignore the hint and let the compiler choose a suitable VF.
4967     if (!UserVF.isScalable()) {
4968       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4969                         << " is unsafe, clamping to max safe VF="
4970                         << MaxSafeFixedVF << ".\n");
4971       ORE->emit([&]() {
4972         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4973                                           TheLoop->getStartLoc(),
4974                                           TheLoop->getHeader())
4975                << "User-specified vectorization factor "
4976                << ore::NV("UserVectorizationFactor", UserVF)
4977                << " is unsafe, clamping to maximum safe vectorization factor "
4978                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
4979       });
4980       return MaxSafeFixedVF;
4981     }
4982 
4983     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
4984       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4985                         << " is ignored because scalable vectors are not "
4986                            "available.\n");
4987       ORE->emit([&]() {
4988         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4989                                           TheLoop->getStartLoc(),
4990                                           TheLoop->getHeader())
4991                << "User-specified vectorization factor "
4992                << ore::NV("UserVectorizationFactor", UserVF)
4993                << " is ignored because the target does not support scalable "
4994                   "vectors. The compiler will pick a more suitable value.";
4995       });
4996     } else {
4997       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4998                         << " is unsafe. Ignoring scalable UserVF.\n");
4999       ORE->emit([&]() {
5000         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5001                                           TheLoop->getStartLoc(),
5002                                           TheLoop->getHeader())
5003                << "User-specified vectorization factor "
5004                << ore::NV("UserVectorizationFactor", UserVF)
5005                << " is unsafe. Ignoring the hint to let the compiler pick a "
5006                   "more suitable value.";
5007       });
5008     }
5009   }
5010 
5011   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5012                     << " / " << WidestType << " bits.\n");
5013 
5014   FixedScalableVFPair Result(ElementCount::getFixed(1),
5015                              ElementCount::getScalable(0));
5016   if (auto MaxVF =
5017           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5018                                   MaxSafeFixedVF, FoldTailByMasking))
5019     Result.FixedVF = MaxVF;
5020 
5021   if (auto MaxVF =
5022           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5023                                   MaxSafeScalableVF, FoldTailByMasking))
5024     if (MaxVF.isScalable()) {
5025       Result.ScalableVF = MaxVF;
5026       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5027                         << "\n");
5028     }
5029 
5030   return Result;
5031 }
5032 
5033 FixedScalableVFPair
5034 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5035   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5036     // TODO: It may by useful to do since it's still likely to be dynamically
5037     // uniform if the target can skip.
5038     reportVectorizationFailure(
5039         "Not inserting runtime ptr check for divergent target",
5040         "runtime pointer checks needed. Not enabled for divergent target",
5041         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5042     return FixedScalableVFPair::getNone();
5043   }
5044 
5045   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5046   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5047   if (TC == 1) {
5048     reportVectorizationFailure("Single iteration (non) loop",
5049         "loop trip count is one, irrelevant for vectorization",
5050         "SingleIterationLoop", ORE, TheLoop);
5051     return FixedScalableVFPair::getNone();
5052   }
5053 
5054   switch (ScalarEpilogueStatus) {
5055   case CM_ScalarEpilogueAllowed:
5056     return computeFeasibleMaxVF(TC, UserVF, false);
5057   case CM_ScalarEpilogueNotAllowedUsePredicate:
5058     LLVM_FALLTHROUGH;
5059   case CM_ScalarEpilogueNotNeededUsePredicate:
5060     LLVM_DEBUG(
5061         dbgs() << "LV: vector predicate hint/switch found.\n"
5062                << "LV: Not allowing scalar epilogue, creating predicated "
5063                << "vector loop.\n");
5064     break;
5065   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5066     // fallthrough as a special case of OptForSize
5067   case CM_ScalarEpilogueNotAllowedOptSize:
5068     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5069       LLVM_DEBUG(
5070           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5071     else
5072       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5073                         << "count.\n");
5074 
5075     // Bail if runtime checks are required, which are not good when optimising
5076     // for size.
5077     if (runtimeChecksRequired())
5078       return FixedScalableVFPair::getNone();
5079 
5080     break;
5081   }
5082 
5083   // The only loops we can vectorize without a scalar epilogue, are loops with
5084   // a bottom-test and a single exiting block. We'd have to handle the fact
5085   // that not every instruction executes on the last iteration.  This will
5086   // require a lane mask which varies through the vector loop body.  (TODO)
5087   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
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 computeFeasibleMaxVF(TC, UserVF, false);
5095     }
5096     return FixedScalableVFPair::getNone();
5097   }
5098 
5099   // Now try the tail folding
5100 
5101   // Invalidate interleave groups that require an epilogue if we can't mask
5102   // the interleave-group.
5103   if (!useMaskedInterleavedAccesses(TTI)) {
5104     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5105            "No decisions should have been taken at this point");
5106     // Note: There is no need to invalidate any cost modeling decisions here, as
5107     // non where taken so far.
5108     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5109   }
5110 
5111   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5112   // Avoid tail folding if the trip count is known to be a multiple of any VF
5113   // we chose.
5114   // FIXME: The condition below pessimises the case for fixed-width vectors,
5115   // when scalable VFs are also candidates for vectorization.
5116   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5117     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5118     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5119            "MaxFixedVF must be a power of 2");
5120     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5121                                    : MaxFixedVF.getFixedValue();
5122     ScalarEvolution *SE = PSE.getSE();
5123     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5124     const SCEV *ExitCount = SE->getAddExpr(
5125         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5126     const SCEV *Rem = SE->getURemExpr(
5127         SE->applyLoopGuards(ExitCount, TheLoop),
5128         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5129     if (Rem->isZero()) {
5130       // Accept MaxFixedVF if we do not have a tail.
5131       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5132       return MaxFactors;
5133     }
5134   }
5135 
5136   // If we don't know the precise trip count, or if the trip count that we
5137   // found modulo the vectorization factor is not zero, try to fold the tail
5138   // by masking.
5139   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5140   if (Legal->prepareToFoldTailByMasking()) {
5141     FoldTailByMasking = true;
5142     return MaxFactors;
5143   }
5144 
5145   // If there was a tail-folding hint/switch, but we can't fold the tail by
5146   // masking, fallback to a vectorization with a scalar epilogue.
5147   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5148     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5149                          "scalar epilogue instead.\n");
5150     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5151     return MaxFactors;
5152   }
5153 
5154   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5155     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5156     return FixedScalableVFPair::getNone();
5157   }
5158 
5159   if (TC == 0) {
5160     reportVectorizationFailure(
5161         "Unable to calculate the loop count due to complex control flow",
5162         "unable to calculate the loop count due to complex control flow",
5163         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5164     return FixedScalableVFPair::getNone();
5165   }
5166 
5167   reportVectorizationFailure(
5168       "Cannot optimize for size and vectorize at the same time.",
5169       "cannot optimize for size and vectorize at the same time. "
5170       "Enable vectorization of this loop with '#pragma clang loop "
5171       "vectorize(enable)' when compiling with -Os/-Oz",
5172       "NoTailLoopWithOptForSize", ORE, TheLoop);
5173   return FixedScalableVFPair::getNone();
5174 }
5175 
5176 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5177     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5178     const ElementCount &MaxSafeVF, bool FoldTailByMasking) {
5179   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5180   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5181       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5182                            : TargetTransformInfo::RGK_FixedWidthVector);
5183 
5184   // Convenience function to return the minimum of two ElementCounts.
5185   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5186     assert((LHS.isScalable() == RHS.isScalable()) &&
5187            "Scalable flags must match");
5188     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5189   };
5190 
5191   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5192   // Note that both WidestRegister and WidestType may not be a powers of 2.
5193   auto MaxVectorElementCount = ElementCount::get(
5194       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5195       ComputeScalableMaxVF);
5196   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5197   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5198                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5199 
5200   if (!MaxVectorElementCount) {
5201     LLVM_DEBUG(dbgs() << "LV: The target has no "
5202                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5203                       << " vector registers.\n");
5204     return ElementCount::getFixed(1);
5205   }
5206 
5207   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5208   if (ConstTripCount &&
5209       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5210       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5211     // If loop trip count (TC) is known at compile time there is no point in
5212     // choosing VF greater than TC (as done in the loop below). Select maximum
5213     // power of two which doesn't exceed TC.
5214     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5215     // when the TC is less than or equal to the known number of lanes.
5216     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5217     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5218                          "exceeding the constant trip count: "
5219                       << ClampedConstTripCount << "\n");
5220     return ElementCount::getFixed(ClampedConstTripCount);
5221   }
5222 
5223   ElementCount MaxVF = MaxVectorElementCount;
5224   if (MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
5225                             TTI.shouldMaximizeVectorBandwidth())) {
5226     auto MaxVectorElementCountMaxBW = ElementCount::get(
5227         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5228         ComputeScalableMaxVF);
5229     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5230 
5231     // Collect all viable vectorization factors larger than the default MaxVF
5232     // (i.e. MaxVectorElementCount).
5233     SmallVector<ElementCount, 8> VFs;
5234     for (ElementCount VS = MaxVectorElementCount * 2;
5235          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5236       VFs.push_back(VS);
5237 
5238     // For each VF calculate its register usage.
5239     auto RUs = calculateRegisterUsage(VFs);
5240 
5241     // Select the largest VF which doesn't require more registers than existing
5242     // ones.
5243     for (int i = RUs.size() - 1; i >= 0; --i) {
5244       bool Selected = true;
5245       for (auto &pair : RUs[i].MaxLocalUsers) {
5246         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5247         if (pair.second > TargetNumRegisters)
5248           Selected = false;
5249       }
5250       if (Selected) {
5251         MaxVF = VFs[i];
5252         break;
5253       }
5254     }
5255     if (ElementCount MinVF =
5256             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5257       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5258         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5259                           << ") with target's minimum: " << MinVF << '\n');
5260         MaxVF = MinVF;
5261       }
5262     }
5263 
5264     // Invalidate any widening decisions we might have made, in case the loop
5265     // requires prediction (decided later), but we have already made some
5266     // load/store widening decisions.
5267     invalidateCostModelingDecisions();
5268   }
5269   return MaxVF;
5270 }
5271 
5272 Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
5273   if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5274     auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
5275     auto Min = Attr.getVScaleRangeMin();
5276     auto Max = Attr.getVScaleRangeMax();
5277     if (Max && Min == Max)
5278       return Max;
5279   }
5280 
5281   return TTI.getVScaleForTuning();
5282 }
5283 
5284 bool LoopVectorizationCostModel::isMoreProfitable(
5285     const VectorizationFactor &A, const VectorizationFactor &B) const {
5286   InstructionCost CostA = A.Cost;
5287   InstructionCost CostB = B.Cost;
5288 
5289   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5290 
5291   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5292       MaxTripCount) {
5293     // If we are folding the tail and the trip count is a known (possibly small)
5294     // constant, the trip count will be rounded up to an integer number of
5295     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5296     // which we compare directly. When not folding the tail, the total cost will
5297     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5298     // approximated with the per-lane cost below instead of using the tripcount
5299     // as here.
5300     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5301     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5302     return RTCostA < RTCostB;
5303   }
5304 
5305   // Improve estimate for the vector width if it is scalable.
5306   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5307   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5308   if (Optional<unsigned> VScale = getVScaleForTuning()) {
5309     if (A.Width.isScalable())
5310       EstimatedWidthA *= VScale.getValue();
5311     if (B.Width.isScalable())
5312       EstimatedWidthB *= VScale.getValue();
5313   }
5314 
5315   // Assume vscale may be larger than 1 (or the value being tuned for),
5316   // so that scalable vectorization is slightly favorable over fixed-width
5317   // vectorization.
5318   if (A.Width.isScalable() && !B.Width.isScalable())
5319     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5320 
5321   // To avoid the need for FP division:
5322   //      (CostA / A.Width) < (CostB / B.Width)
5323   // <=>  (CostA * B.Width) < (CostB * A.Width)
5324   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5325 }
5326 
5327 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5328     const ElementCountSet &VFCandidates) {
5329   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5330   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5331   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5332   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5333          "Expected Scalar VF to be a candidate");
5334 
5335   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5336   VectorizationFactor ChosenFactor = ScalarCost;
5337 
5338   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5339   if (ForceVectorization && VFCandidates.size() > 1) {
5340     // Ignore scalar width, because the user explicitly wants vectorization.
5341     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5342     // evaluation.
5343     ChosenFactor.Cost = InstructionCost::getMax();
5344   }
5345 
5346   SmallVector<InstructionVFPair> InvalidCosts;
5347   for (const auto &i : VFCandidates) {
5348     // The cost for scalar VF=1 is already calculated, so ignore it.
5349     if (i.isScalar())
5350       continue;
5351 
5352     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5353     VectorizationFactor Candidate(i, C.first);
5354 
5355 #ifndef NDEBUG
5356     unsigned AssumedMinimumVscale = 1;
5357     if (Optional<unsigned> VScale = getVScaleForTuning())
5358       AssumedMinimumVscale = VScale.getValue();
5359     unsigned Width =
5360         Candidate.Width.isScalable()
5361             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5362             : Candidate.Width.getFixedValue();
5363     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5364                       << " costs: " << (Candidate.Cost / Width));
5365     if (i.isScalable())
5366       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5367                         << AssumedMinimumVscale << ")");
5368     LLVM_DEBUG(dbgs() << ".\n");
5369 #endif
5370 
5371     if (!C.second && !ForceVectorization) {
5372       LLVM_DEBUG(
5373           dbgs() << "LV: Not considering vector loop of width " << i
5374                  << " because it will not generate any vector instructions.\n");
5375       continue;
5376     }
5377 
5378     // If profitable add it to ProfitableVF list.
5379     if (isMoreProfitable(Candidate, ScalarCost))
5380       ProfitableVFs.push_back(Candidate);
5381 
5382     if (isMoreProfitable(Candidate, ChosenFactor))
5383       ChosenFactor = Candidate;
5384   }
5385 
5386   // Emit a report of VFs with invalid costs in the loop.
5387   if (!InvalidCosts.empty()) {
5388     // Group the remarks per instruction, keeping the instruction order from
5389     // InvalidCosts.
5390     std::map<Instruction *, unsigned> Numbering;
5391     unsigned I = 0;
5392     for (auto &Pair : InvalidCosts)
5393       if (!Numbering.count(Pair.first))
5394         Numbering[Pair.first] = I++;
5395 
5396     // Sort the list, first on instruction(number) then on VF.
5397     llvm::sort(InvalidCosts,
5398                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5399                  if (Numbering[A.first] != Numbering[B.first])
5400                    return Numbering[A.first] < Numbering[B.first];
5401                  ElementCountComparator ECC;
5402                  return ECC(A.second, B.second);
5403                });
5404 
5405     // For a list of ordered instruction-vf pairs:
5406     //   [(load, vf1), (load, vf2), (store, vf1)]
5407     // Group the instructions together to emit separate remarks for:
5408     //   load  (vf1, vf2)
5409     //   store (vf1)
5410     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5411     auto Subset = ArrayRef<InstructionVFPair>();
5412     do {
5413       if (Subset.empty())
5414         Subset = Tail.take_front(1);
5415 
5416       Instruction *I = Subset.front().first;
5417 
5418       // If the next instruction is different, or if there are no other pairs,
5419       // emit a remark for the collated subset. e.g.
5420       //   [(load, vf1), (load, vf2))]
5421       // to emit:
5422       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5423       if (Subset == Tail || Tail[Subset.size()].first != I) {
5424         std::string OutString;
5425         raw_string_ostream OS(OutString);
5426         assert(!Subset.empty() && "Unexpected empty range");
5427         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5428         for (auto &Pair : Subset)
5429           OS << (Pair.second == Subset.front().second ? "" : ", ")
5430              << Pair.second;
5431         OS << "):";
5432         if (auto *CI = dyn_cast<CallInst>(I))
5433           OS << " call to " << CI->getCalledFunction()->getName();
5434         else
5435           OS << " " << I->getOpcodeName();
5436         OS.flush();
5437         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5438         Tail = Tail.drop_front(Subset.size());
5439         Subset = {};
5440       } else
5441         // Grow the subset by one element
5442         Subset = Tail.take_front(Subset.size() + 1);
5443     } while (!Tail.empty());
5444   }
5445 
5446   if (!EnableCondStoresVectorization && NumPredStores) {
5447     reportVectorizationFailure("There are conditional stores.",
5448         "store that is conditionally executed prevents vectorization",
5449         "ConditionalStore", ORE, TheLoop);
5450     ChosenFactor = ScalarCost;
5451   }
5452 
5453   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5454                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
5455              << "LV: Vectorization seems to be not beneficial, "
5456              << "but was forced by a user.\n");
5457   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5458   return ChosenFactor;
5459 }
5460 
5461 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5462     const Loop &L, ElementCount VF) const {
5463   // Cross iteration phis such as reductions need special handling and are
5464   // currently unsupported.
5465   if (any_of(L.getHeader()->phis(),
5466              [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
5467     return false;
5468 
5469   // Phis with uses outside of the loop require special handling and are
5470   // currently unsupported.
5471   for (auto &Entry : Legal->getInductionVars()) {
5472     // Look for uses of the value of the induction at the last iteration.
5473     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5474     for (User *U : PostInc->users())
5475       if (!L.contains(cast<Instruction>(U)))
5476         return false;
5477     // Look for uses of penultimate value of the induction.
5478     for (User *U : Entry.first->users())
5479       if (!L.contains(cast<Instruction>(U)))
5480         return false;
5481   }
5482 
5483   // Induction variables that are widened require special handling that is
5484   // currently not supported.
5485   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5486         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5487                  this->isProfitableToScalarize(Entry.first, VF));
5488       }))
5489     return false;
5490 
5491   // Epilogue vectorization code has not been auditted to ensure it handles
5492   // non-latch exits properly.  It may be fine, but it needs auditted and
5493   // tested.
5494   if (L.getExitingBlock() != L.getLoopLatch())
5495     return false;
5496 
5497   return true;
5498 }
5499 
5500 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5501     const ElementCount VF) const {
5502   // FIXME: We need a much better cost-model to take different parameters such
5503   // as register pressure, code size increase and cost of extra branches into
5504   // account. For now we apply a very crude heuristic and only consider loops
5505   // with vectorization factors larger than a certain value.
5506   // We also consider epilogue vectorization unprofitable for targets that don't
5507   // consider interleaving beneficial (eg. MVE).
5508   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5509     return false;
5510   // FIXME: We should consider changing the threshold for scalable
5511   // vectors to take VScaleForTuning into account.
5512   if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
5513     return true;
5514   return false;
5515 }
5516 
5517 VectorizationFactor
5518 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5519     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5520   VectorizationFactor Result = VectorizationFactor::Disabled();
5521   if (!EnableEpilogueVectorization) {
5522     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5523     return Result;
5524   }
5525 
5526   if (!isScalarEpilogueAllowed()) {
5527     LLVM_DEBUG(
5528         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5529                   "allowed.\n";);
5530     return Result;
5531   }
5532 
5533   // Not really a cost consideration, but check for unsupported cases here to
5534   // simplify the logic.
5535   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5536     LLVM_DEBUG(
5537         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5538                   "not a supported candidate.\n";);
5539     return Result;
5540   }
5541 
5542   if (EpilogueVectorizationForceVF > 1) {
5543     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5544     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5545     if (LVP.hasPlanWithVF(ForcedEC))
5546       return {ForcedEC, 0};
5547     else {
5548       LLVM_DEBUG(
5549           dbgs()
5550               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5551       return Result;
5552     }
5553   }
5554 
5555   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5556       TheLoop->getHeader()->getParent()->hasMinSize()) {
5557     LLVM_DEBUG(
5558         dbgs()
5559             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5560     return Result;
5561   }
5562 
5563   if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
5564     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5565                          "this loop\n");
5566     return Result;
5567   }
5568 
5569   // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
5570   // the main loop handles 8 lanes per iteration. We could still benefit from
5571   // vectorizing the epilogue loop with VF=4.
5572   ElementCount EstimatedRuntimeVF = MainLoopVF;
5573   if (MainLoopVF.isScalable()) {
5574     EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5575     if (Optional<unsigned> VScale = getVScaleForTuning())
5576       EstimatedRuntimeVF *= VScale.getValue();
5577   }
5578 
5579   for (auto &NextVF : ProfitableVFs)
5580     if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
5581           ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
5582          ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
5583         (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
5584         LVP.hasPlanWithVF(NextVF.Width))
5585       Result = NextVF;
5586 
5587   if (Result != VectorizationFactor::Disabled())
5588     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5589                       << Result.Width << "\n";);
5590   return Result;
5591 }
5592 
5593 std::pair<unsigned, unsigned>
5594 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5595   unsigned MinWidth = -1U;
5596   unsigned MaxWidth = 8;
5597   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5598   // For in-loop reductions, no element types are added to ElementTypesInLoop
5599   // if there are no loads/stores in the loop. In this case, check through the
5600   // reduction variables to determine the maximum width.
5601   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5602     // Reset MaxWidth so that we can find the smallest type used by recurrences
5603     // in the loop.
5604     MaxWidth = -1U;
5605     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5606       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5607       // When finding the min width used by the recurrence we need to account
5608       // for casts on the input operands of the recurrence.
5609       MaxWidth = std::min<unsigned>(
5610           MaxWidth, std::min<unsigned>(
5611                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5612                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5613     }
5614   } else {
5615     for (Type *T : ElementTypesInLoop) {
5616       MinWidth = std::min<unsigned>(
5617           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5618       MaxWidth = std::max<unsigned>(
5619           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5620     }
5621   }
5622   return {MinWidth, MaxWidth};
5623 }
5624 
5625 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5626   ElementTypesInLoop.clear();
5627   // For each block.
5628   for (BasicBlock *BB : TheLoop->blocks()) {
5629     // For each instruction in the loop.
5630     for (Instruction &I : BB->instructionsWithoutDebug()) {
5631       Type *T = I.getType();
5632 
5633       // Skip ignored values.
5634       if (ValuesToIgnore.count(&I))
5635         continue;
5636 
5637       // Only examine Loads, Stores and PHINodes.
5638       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5639         continue;
5640 
5641       // Examine PHI nodes that are reduction variables. Update the type to
5642       // account for the recurrence type.
5643       if (auto *PN = dyn_cast<PHINode>(&I)) {
5644         if (!Legal->isReductionVariable(PN))
5645           continue;
5646         const RecurrenceDescriptor &RdxDesc =
5647             Legal->getReductionVars().find(PN)->second;
5648         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
5649             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
5650                                       RdxDesc.getRecurrenceType(),
5651                                       TargetTransformInfo::ReductionFlags()))
5652           continue;
5653         T = RdxDesc.getRecurrenceType();
5654       }
5655 
5656       // Examine the stored values.
5657       if (auto *ST = dyn_cast<StoreInst>(&I))
5658         T = ST->getValueOperand()->getType();
5659 
5660       assert(T->isSized() &&
5661              "Expected the load/store/recurrence type to be sized");
5662 
5663       ElementTypesInLoop.insert(T);
5664     }
5665   }
5666 }
5667 
5668 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5669                                                            unsigned LoopCost) {
5670   // -- The interleave heuristics --
5671   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5672   // There are many micro-architectural considerations that we can't predict
5673   // at this level. For example, frontend pressure (on decode or fetch) due to
5674   // code size, or the number and capabilities of the execution ports.
5675   //
5676   // We use the following heuristics to select the interleave count:
5677   // 1. If the code has reductions, then we interleave to break the cross
5678   // iteration dependency.
5679   // 2. If the loop is really small, then we interleave to reduce the loop
5680   // overhead.
5681   // 3. We don't interleave if we think that we will spill registers to memory
5682   // due to the increased register pressure.
5683 
5684   if (!isScalarEpilogueAllowed())
5685     return 1;
5686 
5687   // We used the distance for the interleave count.
5688   if (Legal->getMaxSafeDepDistBytes() != -1U)
5689     return 1;
5690 
5691   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5692   const bool HasReductions = !Legal->getReductionVars().empty();
5693   // Do not interleave loops with a relatively small known or estimated trip
5694   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5695   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5696   // because with the above conditions interleaving can expose ILP and break
5697   // cross iteration dependences for reductions.
5698   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5699       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5700     return 1;
5701 
5702   // If we did not calculate the cost for VF (because the user selected the VF)
5703   // then we calculate the cost of VF here.
5704   if (LoopCost == 0) {
5705     InstructionCost C = expectedCost(VF).first;
5706     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
5707     LoopCost = *C.getValue();
5708 
5709     // Loop body is free and there is no need for interleaving.
5710     if (LoopCost == 0)
5711       return 1;
5712   }
5713 
5714   RegisterUsage R = calculateRegisterUsage({VF})[0];
5715   // We divide by these constants so assume that we have at least one
5716   // instruction that uses at least one register.
5717   for (auto& pair : R.MaxLocalUsers) {
5718     pair.second = std::max(pair.second, 1U);
5719   }
5720 
5721   // We calculate the interleave count using the following formula.
5722   // Subtract the number of loop invariants from the number of available
5723   // registers. These registers are used by all of the interleaved instances.
5724   // Next, divide the remaining registers by the number of registers that is
5725   // required by the loop, in order to estimate how many parallel instances
5726   // fit without causing spills. All of this is rounded down if necessary to be
5727   // a power of two. We want power of two interleave count to simplify any
5728   // addressing operations or alignment considerations.
5729   // We also want power of two interleave counts to ensure that the induction
5730   // variable of the vector loop wraps to zero, when tail is folded by masking;
5731   // this currently happens when OptForSize, in which case IC is set to 1 above.
5732   unsigned IC = UINT_MAX;
5733 
5734   for (auto& pair : R.MaxLocalUsers) {
5735     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5736     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5737                       << " registers of "
5738                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5739     if (VF.isScalar()) {
5740       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5741         TargetNumRegisters = ForceTargetNumScalarRegs;
5742     } else {
5743       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5744         TargetNumRegisters = ForceTargetNumVectorRegs;
5745     }
5746     unsigned MaxLocalUsers = pair.second;
5747     unsigned LoopInvariantRegs = 0;
5748     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5749       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5750 
5751     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5752     // Don't count the induction variable as interleaved.
5753     if (EnableIndVarRegisterHeur) {
5754       TmpIC =
5755           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5756                         std::max(1U, (MaxLocalUsers - 1)));
5757     }
5758 
5759     IC = std::min(IC, TmpIC);
5760   }
5761 
5762   // Clamp the interleave ranges to reasonable counts.
5763   unsigned MaxInterleaveCount =
5764       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5765 
5766   // Check if the user has overridden the max.
5767   if (VF.isScalar()) {
5768     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5769       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5770   } else {
5771     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5772       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5773   }
5774 
5775   // If trip count is known or estimated compile time constant, limit the
5776   // interleave count to be less than the trip count divided by VF, provided it
5777   // is at least 1.
5778   //
5779   // For scalable vectors we can't know if interleaving is beneficial. It may
5780   // not be beneficial for small loops if none of the lanes in the second vector
5781   // iterations is enabled. However, for larger loops, there is likely to be a
5782   // similar benefit as for fixed-width vectors. For now, we choose to leave
5783   // the InterleaveCount as if vscale is '1', although if some information about
5784   // the vector is known (e.g. min vector size), we can make a better decision.
5785   if (BestKnownTC) {
5786     MaxInterleaveCount =
5787         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5788     // Make sure MaxInterleaveCount is greater than 0.
5789     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5790   }
5791 
5792   assert(MaxInterleaveCount > 0 &&
5793          "Maximum interleave count must be greater than 0");
5794 
5795   // Clamp the calculated IC to be between the 1 and the max interleave count
5796   // that the target and trip count allows.
5797   if (IC > MaxInterleaveCount)
5798     IC = MaxInterleaveCount;
5799   else
5800     // Make sure IC is greater than 0.
5801     IC = std::max(1u, IC);
5802 
5803   assert(IC > 0 && "Interleave count must be greater than 0.");
5804 
5805   // Interleave if we vectorized this loop and there is a reduction that could
5806   // benefit from interleaving.
5807   if (VF.isVector() && HasReductions) {
5808     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5809     return IC;
5810   }
5811 
5812   // For any scalar loop that either requires runtime checks or predication we
5813   // are better off leaving this to the unroller. Note that if we've already
5814   // vectorized the loop we will have done the runtime check and so interleaving
5815   // won't require further checks.
5816   bool ScalarInterleavingRequiresPredication =
5817       (VF.isScalar() && any_of(TheLoop->blocks(), [this](BasicBlock *BB) {
5818          return Legal->blockNeedsPredication(BB);
5819        }));
5820   bool ScalarInterleavingRequiresRuntimePointerCheck =
5821       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5822 
5823   // We want to interleave small loops in order to reduce the loop overhead and
5824   // potentially expose ILP opportunities.
5825   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5826                     << "LV: IC is " << IC << '\n'
5827                     << "LV: VF is " << VF << '\n');
5828   const bool AggressivelyInterleaveReductions =
5829       TTI.enableAggressiveInterleaving(HasReductions);
5830   if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5831       !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
5832     // We assume that the cost overhead is 1 and we use the cost model
5833     // to estimate the cost of the loop and interleave until the cost of the
5834     // loop overhead is about 5% of the cost of the loop.
5835     unsigned SmallIC =
5836         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5837 
5838     // Interleave until store/load ports (estimated by max interleave count) are
5839     // saturated.
5840     unsigned NumStores = Legal->getNumStores();
5841     unsigned NumLoads = Legal->getNumLoads();
5842     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5843     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5844 
5845     // There is little point in interleaving for reductions containing selects
5846     // and compares when VF=1 since it may just create more overhead than it's
5847     // worth for loops with small trip counts. This is because we still have to
5848     // do the final reduction after the loop.
5849     bool HasSelectCmpReductions =
5850         HasReductions &&
5851         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5852           const RecurrenceDescriptor &RdxDesc = Reduction.second;
5853           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
5854               RdxDesc.getRecurrenceKind());
5855         });
5856     if (HasSelectCmpReductions) {
5857       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
5858       return 1;
5859     }
5860 
5861     // If we have a scalar reduction (vector reductions are already dealt with
5862     // by this point), we can increase the critical path length if the loop
5863     // we're interleaving is inside another loop. For tree-wise reductions
5864     // set the limit to 2, and for ordered reductions it's best to disable
5865     // interleaving entirely.
5866     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5867       bool HasOrderedReductions =
5868           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5869             const RecurrenceDescriptor &RdxDesc = Reduction.second;
5870             return RdxDesc.isOrdered();
5871           });
5872       if (HasOrderedReductions) {
5873         LLVM_DEBUG(
5874             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
5875         return 1;
5876       }
5877 
5878       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5879       SmallIC = std::min(SmallIC, F);
5880       StoresIC = std::min(StoresIC, F);
5881       LoadsIC = std::min(LoadsIC, F);
5882     }
5883 
5884     if (EnableLoadStoreRuntimeInterleave &&
5885         std::max(StoresIC, LoadsIC) > SmallIC) {
5886       LLVM_DEBUG(
5887           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5888       return std::max(StoresIC, LoadsIC);
5889     }
5890 
5891     // If there are scalar reductions and TTI has enabled aggressive
5892     // interleaving for reductions, we will interleave to expose ILP.
5893     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5894         AggressivelyInterleaveReductions) {
5895       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5896       // Interleave no less than SmallIC but not as aggressive as the normal IC
5897       // to satisfy the rare situation when resources are too limited.
5898       return std::max(IC / 2, SmallIC);
5899     } else {
5900       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5901       return SmallIC;
5902     }
5903   }
5904 
5905   // Interleave if this is a large loop (small loops are already dealt with by
5906   // this point) that could benefit from interleaving.
5907   if (AggressivelyInterleaveReductions) {
5908     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5909     return IC;
5910   }
5911 
5912   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5913   return 1;
5914 }
5915 
5916 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5917 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5918   // This function calculates the register usage by measuring the highest number
5919   // of values that are alive at a single location. Obviously, this is a very
5920   // rough estimation. We scan the loop in a topological order in order and
5921   // assign a number to each instruction. We use RPO to ensure that defs are
5922   // met before their users. We assume that each instruction that has in-loop
5923   // users starts an interval. We record every time that an in-loop value is
5924   // used, so we have a list of the first and last occurrences of each
5925   // instruction. Next, we transpose this data structure into a multi map that
5926   // holds the list of intervals that *end* at a specific location. This multi
5927   // map allows us to perform a linear search. We scan the instructions linearly
5928   // and record each time that a new interval starts, by placing it in a set.
5929   // If we find this value in the multi-map then we remove it from the set.
5930   // The max register usage is the maximum size of the set.
5931   // We also search for instructions that are defined outside the loop, but are
5932   // used inside the loop. We need this number separately from the max-interval
5933   // usage number because when we unroll, loop-invariant values do not take
5934   // more register.
5935   LoopBlocksDFS DFS(TheLoop);
5936   DFS.perform(LI);
5937 
5938   RegisterUsage RU;
5939 
5940   // Each 'key' in the map opens a new interval. The values
5941   // of the map are the index of the 'last seen' usage of the
5942   // instruction that is the key.
5943   using IntervalMap = DenseMap<Instruction *, unsigned>;
5944 
5945   // Maps instruction to its index.
5946   SmallVector<Instruction *, 64> IdxToInstr;
5947   // Marks the end of each interval.
5948   IntervalMap EndPoint;
5949   // Saves the list of instruction indices that are used in the loop.
5950   SmallPtrSet<Instruction *, 8> Ends;
5951   // Saves the list of values that are used in the loop but are
5952   // defined outside the loop, such as arguments and constants.
5953   SmallPtrSet<Value *, 8> LoopInvariants;
5954 
5955   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5956     for (Instruction &I : BB->instructionsWithoutDebug()) {
5957       IdxToInstr.push_back(&I);
5958 
5959       // Save the end location of each USE.
5960       for (Value *U : I.operands()) {
5961         auto *Instr = dyn_cast<Instruction>(U);
5962 
5963         // Ignore non-instruction values such as arguments, constants, etc.
5964         if (!Instr)
5965           continue;
5966 
5967         // If this instruction is outside the loop then record it and continue.
5968         if (!TheLoop->contains(Instr)) {
5969           LoopInvariants.insert(Instr);
5970           continue;
5971         }
5972 
5973         // Overwrite previous end points.
5974         EndPoint[Instr] = IdxToInstr.size();
5975         Ends.insert(Instr);
5976       }
5977     }
5978   }
5979 
5980   // Saves the list of intervals that end with the index in 'key'.
5981   using InstrList = SmallVector<Instruction *, 2>;
5982   DenseMap<unsigned, InstrList> TransposeEnds;
5983 
5984   // Transpose the EndPoints to a list of values that end at each index.
5985   for (auto &Interval : EndPoint)
5986     TransposeEnds[Interval.second].push_back(Interval.first);
5987 
5988   SmallPtrSet<Instruction *, 8> OpenIntervals;
5989   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5990   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5991 
5992   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5993 
5994   // A lambda that gets the register usage for the given type and VF.
5995   const auto &TTICapture = TTI;
5996   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
5997     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
5998       return 0;
5999     InstructionCost::CostType RegUsage =
6000         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6001     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6002            "Nonsensical values for register usage.");
6003     return RegUsage;
6004   };
6005 
6006   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6007     Instruction *I = IdxToInstr[i];
6008 
6009     // Remove all of the instructions that end at this location.
6010     InstrList &List = TransposeEnds[i];
6011     for (Instruction *ToRemove : List)
6012       OpenIntervals.erase(ToRemove);
6013 
6014     // Ignore instructions that are never used within the loop.
6015     if (!Ends.count(I))
6016       continue;
6017 
6018     // Skip ignored values.
6019     if (ValuesToIgnore.count(I))
6020       continue;
6021 
6022     // For each VF find the maximum usage of registers.
6023     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6024       // Count the number of live intervals.
6025       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6026 
6027       if (VFs[j].isScalar()) {
6028         for (auto Inst : OpenIntervals) {
6029           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6030           if (RegUsage.find(ClassID) == RegUsage.end())
6031             RegUsage[ClassID] = 1;
6032           else
6033             RegUsage[ClassID] += 1;
6034         }
6035       } else {
6036         collectUniformsAndScalars(VFs[j]);
6037         for (auto Inst : OpenIntervals) {
6038           // Skip ignored values for VF > 1.
6039           if (VecValuesToIgnore.count(Inst))
6040             continue;
6041           if (isScalarAfterVectorization(Inst, VFs[j])) {
6042             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6043             if (RegUsage.find(ClassID) == RegUsage.end())
6044               RegUsage[ClassID] = 1;
6045             else
6046               RegUsage[ClassID] += 1;
6047           } else {
6048             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6049             if (RegUsage.find(ClassID) == RegUsage.end())
6050               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6051             else
6052               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6053           }
6054         }
6055       }
6056 
6057       for (auto& pair : RegUsage) {
6058         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6059           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6060         else
6061           MaxUsages[j][pair.first] = pair.second;
6062       }
6063     }
6064 
6065     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6066                       << OpenIntervals.size() << '\n');
6067 
6068     // Add the current instruction to the list of open intervals.
6069     OpenIntervals.insert(I);
6070   }
6071 
6072   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6073     SmallMapVector<unsigned, unsigned, 4> Invariant;
6074 
6075     for (auto Inst : LoopInvariants) {
6076       unsigned Usage =
6077           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6078       unsigned ClassID =
6079           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6080       if (Invariant.find(ClassID) == Invariant.end())
6081         Invariant[ClassID] = Usage;
6082       else
6083         Invariant[ClassID] += Usage;
6084     }
6085 
6086     LLVM_DEBUG({
6087       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6088       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6089              << " item\n";
6090       for (const auto &pair : MaxUsages[i]) {
6091         dbgs() << "LV(REG): RegisterClass: "
6092                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6093                << " registers\n";
6094       }
6095       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6096              << " item\n";
6097       for (const auto &pair : Invariant) {
6098         dbgs() << "LV(REG): RegisterClass: "
6099                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6100                << " registers\n";
6101       }
6102     });
6103 
6104     RU.LoopInvariantRegs = Invariant;
6105     RU.MaxLocalUsers = MaxUsages[i];
6106     RUs[i] = RU;
6107   }
6108 
6109   return RUs;
6110 }
6111 
6112 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
6113                                                            ElementCount VF) {
6114   // TODO: Cost model for emulated masked load/store is completely
6115   // broken. This hack guides the cost model to use an artificially
6116   // high enough value to practically disable vectorization with such
6117   // operations, except where previously deployed legality hack allowed
6118   // using very low cost values. This is to avoid regressions coming simply
6119   // from moving "masked load/store" check from legality to cost model.
6120   // Masked Load/Gather emulation was previously never allowed.
6121   // Limited number of Masked Store/Scatter emulation was allowed.
6122   assert(isPredicatedInst(I, VF) && "Expecting a scalar emulated instruction");
6123   return isa<LoadInst>(I) ||
6124          (isa<StoreInst>(I) &&
6125           NumPredStores > NumberOfStoresToPredicate);
6126 }
6127 
6128 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6129   // If we aren't vectorizing the loop, or if we've already collected the
6130   // instructions to scalarize, there's nothing to do. Collection may already
6131   // have occurred if we have a user-selected VF and are now computing the
6132   // expected cost for interleaving.
6133   if (VF.isScalar() || VF.isZero() ||
6134       InstsToScalarize.find(VF) != InstsToScalarize.end())
6135     return;
6136 
6137   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6138   // not profitable to scalarize any instructions, the presence of VF in the
6139   // map will indicate that we've analyzed it already.
6140   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6141 
6142   // Find all the instructions that are scalar with predication in the loop and
6143   // determine if it would be better to not if-convert the blocks they are in.
6144   // If so, we also record the instructions to scalarize.
6145   for (BasicBlock *BB : TheLoop->blocks()) {
6146     if (!blockNeedsPredicationForAnyReason(BB))
6147       continue;
6148     for (Instruction &I : *BB)
6149       if (isScalarWithPredication(&I, VF)) {
6150         ScalarCostsTy ScalarCosts;
6151         // Do not apply discount if scalable, because that would lead to
6152         // invalid scalarization costs.
6153         // Do not apply discount logic if hacked cost is needed
6154         // for emulated masked memrefs.
6155         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
6156             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6157           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6158         // Remember that BB will remain after vectorization.
6159         PredicatedBBsAfterVectorization.insert(BB);
6160       }
6161   }
6162 }
6163 
6164 int LoopVectorizationCostModel::computePredInstDiscount(
6165     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6166   assert(!isUniformAfterVectorization(PredInst, VF) &&
6167          "Instruction marked uniform-after-vectorization will be predicated");
6168 
6169   // Initialize the discount to zero, meaning that the scalar version and the
6170   // vector version cost the same.
6171   InstructionCost Discount = 0;
6172 
6173   // Holds instructions to analyze. The instructions we visit are mapped in
6174   // ScalarCosts. Those instructions are the ones that would be scalarized if
6175   // we find that the scalar version costs less.
6176   SmallVector<Instruction *, 8> Worklist;
6177 
6178   // Returns true if the given instruction can be scalarized.
6179   auto canBeScalarized = [&](Instruction *I) -> bool {
6180     // We only attempt to scalarize instructions forming a single-use chain
6181     // from the original predicated block that would otherwise be vectorized.
6182     // Although not strictly necessary, we give up on instructions we know will
6183     // already be scalar to avoid traversing chains that are unlikely to be
6184     // beneficial.
6185     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6186         isScalarAfterVectorization(I, VF))
6187       return false;
6188 
6189     // If the instruction is scalar with predication, it will be analyzed
6190     // separately. We ignore it within the context of PredInst.
6191     if (isScalarWithPredication(I, VF))
6192       return false;
6193 
6194     // If any of the instruction's operands are uniform after vectorization,
6195     // the instruction cannot be scalarized. This prevents, for example, a
6196     // masked load from being scalarized.
6197     //
6198     // We assume we will only emit a value for lane zero of an instruction
6199     // marked uniform after vectorization, rather than VF identical values.
6200     // Thus, if we scalarize an instruction that uses a uniform, we would
6201     // create uses of values corresponding to the lanes we aren't emitting code
6202     // for. This behavior can be changed by allowing getScalarValue to clone
6203     // the lane zero values for uniforms rather than asserting.
6204     for (Use &U : I->operands())
6205       if (auto *J = dyn_cast<Instruction>(U.get()))
6206         if (isUniformAfterVectorization(J, VF))
6207           return false;
6208 
6209     // Otherwise, we can scalarize the instruction.
6210     return true;
6211   };
6212 
6213   // Compute the expected cost discount from scalarizing the entire expression
6214   // feeding the predicated instruction. We currently only consider expressions
6215   // that are single-use instruction chains.
6216   Worklist.push_back(PredInst);
6217   while (!Worklist.empty()) {
6218     Instruction *I = Worklist.pop_back_val();
6219 
6220     // If we've already analyzed the instruction, there's nothing to do.
6221     if (ScalarCosts.find(I) != ScalarCosts.end())
6222       continue;
6223 
6224     // Compute the cost of the vector instruction. Note that this cost already
6225     // includes the scalarization overhead of the predicated instruction.
6226     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6227 
6228     // Compute the cost of the scalarized instruction. This cost is the cost of
6229     // the instruction as if it wasn't if-converted and instead remained in the
6230     // predicated block. We will scale this cost by block probability after
6231     // computing the scalarization overhead.
6232     InstructionCost ScalarCost =
6233         VF.getFixedValue() *
6234         getInstructionCost(I, ElementCount::getFixed(1)).first;
6235 
6236     // Compute the scalarization overhead of needed insertelement instructions
6237     // and phi nodes.
6238     if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
6239       ScalarCost += TTI.getScalarizationOverhead(
6240           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6241           APInt::getAllOnes(VF.getFixedValue()), true, false);
6242       ScalarCost +=
6243           VF.getFixedValue() *
6244           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6245     }
6246 
6247     // Compute the scalarization overhead of needed extractelement
6248     // instructions. For each of the instruction's operands, if the operand can
6249     // be scalarized, add it to the worklist; otherwise, account for the
6250     // overhead.
6251     for (Use &U : I->operands())
6252       if (auto *J = dyn_cast<Instruction>(U.get())) {
6253         assert(VectorType::isValidElementType(J->getType()) &&
6254                "Instruction has non-scalar type");
6255         if (canBeScalarized(J))
6256           Worklist.push_back(J);
6257         else if (needsExtract(J, VF)) {
6258           ScalarCost += TTI.getScalarizationOverhead(
6259               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6260               APInt::getAllOnes(VF.getFixedValue()), false, true);
6261         }
6262       }
6263 
6264     // Scale the total scalar cost by block probability.
6265     ScalarCost /= getReciprocalPredBlockProb();
6266 
6267     // Compute the discount. A non-negative discount means the vector version
6268     // of the instruction costs more, and scalarizing would be beneficial.
6269     Discount += VectorCost - ScalarCost;
6270     ScalarCosts[I] = ScalarCost;
6271   }
6272 
6273   return *Discount.getValue();
6274 }
6275 
6276 LoopVectorizationCostModel::VectorizationCostTy
6277 LoopVectorizationCostModel::expectedCost(
6278     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6279   VectorizationCostTy Cost;
6280 
6281   // For each block.
6282   for (BasicBlock *BB : TheLoop->blocks()) {
6283     VectorizationCostTy BlockCost;
6284 
6285     // For each instruction in the old loop.
6286     for (Instruction &I : BB->instructionsWithoutDebug()) {
6287       // Skip ignored values.
6288       if (ValuesToIgnore.count(&I) ||
6289           (VF.isVector() && VecValuesToIgnore.count(&I)))
6290         continue;
6291 
6292       VectorizationCostTy C = getInstructionCost(&I, VF);
6293 
6294       // Check if we should override the cost.
6295       if (C.first.isValid() &&
6296           ForceTargetInstructionCost.getNumOccurrences() > 0)
6297         C.first = InstructionCost(ForceTargetInstructionCost);
6298 
6299       // Keep a list of instructions with invalid costs.
6300       if (Invalid && !C.first.isValid())
6301         Invalid->emplace_back(&I, VF);
6302 
6303       BlockCost.first += C.first;
6304       BlockCost.second |= C.second;
6305       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6306                         << " for VF " << VF << " For instruction: " << I
6307                         << '\n');
6308     }
6309 
6310     // If we are vectorizing a predicated block, it will have been
6311     // if-converted. This means that the block's instructions (aside from
6312     // stores and instructions that may divide by zero) will now be
6313     // unconditionally executed. For the scalar case, we may not always execute
6314     // the predicated block, if it is an if-else block. Thus, scale the block's
6315     // cost by the probability of executing it. blockNeedsPredication from
6316     // Legal is used so as to not include all blocks in tail folded loops.
6317     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6318       BlockCost.first /= getReciprocalPredBlockProb();
6319 
6320     Cost.first += BlockCost.first;
6321     Cost.second |= BlockCost.second;
6322   }
6323 
6324   return Cost;
6325 }
6326 
6327 /// Gets Address Access SCEV after verifying that the access pattern
6328 /// is loop invariant except the induction variable dependence.
6329 ///
6330 /// This SCEV can be sent to the Target in order to estimate the address
6331 /// calculation cost.
6332 static const SCEV *getAddressAccessSCEV(
6333               Value *Ptr,
6334               LoopVectorizationLegality *Legal,
6335               PredicatedScalarEvolution &PSE,
6336               const Loop *TheLoop) {
6337 
6338   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6339   if (!Gep)
6340     return nullptr;
6341 
6342   // We are looking for a gep with all loop invariant indices except for one
6343   // which should be an induction variable.
6344   auto SE = PSE.getSE();
6345   unsigned NumOperands = Gep->getNumOperands();
6346   for (unsigned i = 1; i < NumOperands; ++i) {
6347     Value *Opd = Gep->getOperand(i);
6348     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6349         !Legal->isInductionVariable(Opd))
6350       return nullptr;
6351   }
6352 
6353   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6354   return PSE.getSCEV(Ptr);
6355 }
6356 
6357 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6358   return Legal->hasStride(I->getOperand(0)) ||
6359          Legal->hasStride(I->getOperand(1));
6360 }
6361 
6362 InstructionCost
6363 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6364                                                         ElementCount VF) {
6365   assert(VF.isVector() &&
6366          "Scalarization cost of instruction implies vectorization.");
6367   if (VF.isScalable())
6368     return InstructionCost::getInvalid();
6369 
6370   Type *ValTy = getLoadStoreType(I);
6371   auto SE = PSE.getSE();
6372 
6373   unsigned AS = getLoadStoreAddressSpace(I);
6374   Value *Ptr = getLoadStorePointerOperand(I);
6375   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6376   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6377   //       that it is being called from this specific place.
6378 
6379   // Figure out whether the access is strided and get the stride value
6380   // if it's known in compile time
6381   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6382 
6383   // Get the cost of the scalar memory instruction and address computation.
6384   InstructionCost Cost =
6385       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6386 
6387   // Don't pass *I here, since it is scalar but will actually be part of a
6388   // vectorized loop where the user of it is a vectorized instruction.
6389   const Align Alignment = getLoadStoreAlignment(I);
6390   Cost += VF.getKnownMinValue() *
6391           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6392                               AS, TTI::TCK_RecipThroughput);
6393 
6394   // Get the overhead of the extractelement and insertelement instructions
6395   // we might create due to scalarization.
6396   Cost += getScalarizationOverhead(I, VF);
6397 
6398   // If we have a predicated load/store, it will need extra i1 extracts and
6399   // conditional branches, but may not be executed for each vector lane. Scale
6400   // the cost by the probability of executing the predicated block.
6401   if (isPredicatedInst(I, VF)) {
6402     Cost /= getReciprocalPredBlockProb();
6403 
6404     // Add the cost of an i1 extract and a branch
6405     auto *Vec_i1Ty =
6406         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6407     Cost += TTI.getScalarizationOverhead(
6408         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6409         /*Insert=*/false, /*Extract=*/true);
6410     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6411 
6412     if (useEmulatedMaskMemRefHack(I, VF))
6413       // Artificially setting to a high enough value to practically disable
6414       // vectorization with such operations.
6415       Cost = 3000000;
6416   }
6417 
6418   return Cost;
6419 }
6420 
6421 InstructionCost
6422 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6423                                                     ElementCount VF) {
6424   Type *ValTy = getLoadStoreType(I);
6425   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6426   Value *Ptr = getLoadStorePointerOperand(I);
6427   unsigned AS = getLoadStoreAddressSpace(I);
6428   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6429   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6430 
6431   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6432          "Stride should be 1 or -1 for consecutive memory access");
6433   const Align Alignment = getLoadStoreAlignment(I);
6434   InstructionCost Cost = 0;
6435   if (Legal->isMaskRequired(I))
6436     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6437                                       CostKind);
6438   else
6439     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6440                                 CostKind, I);
6441 
6442   bool Reverse = ConsecutiveStride < 0;
6443   if (Reverse)
6444     Cost +=
6445         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6446   return Cost;
6447 }
6448 
6449 InstructionCost
6450 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6451                                                 ElementCount VF) {
6452   assert(Legal->isUniformMemOp(*I));
6453 
6454   Type *ValTy = getLoadStoreType(I);
6455   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6456   const Align Alignment = getLoadStoreAlignment(I);
6457   unsigned AS = getLoadStoreAddressSpace(I);
6458   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6459   if (isa<LoadInst>(I)) {
6460     return TTI.getAddressComputationCost(ValTy) +
6461            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6462                                CostKind) +
6463            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6464   }
6465   StoreInst *SI = cast<StoreInst>(I);
6466 
6467   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6468   return TTI.getAddressComputationCost(ValTy) +
6469          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6470                              CostKind) +
6471          (isLoopInvariantStoreValue
6472               ? 0
6473               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6474                                        VF.getKnownMinValue() - 1));
6475 }
6476 
6477 InstructionCost
6478 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6479                                                  ElementCount VF) {
6480   Type *ValTy = getLoadStoreType(I);
6481   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6482   const Align Alignment = getLoadStoreAlignment(I);
6483   const Value *Ptr = getLoadStorePointerOperand(I);
6484 
6485   return TTI.getAddressComputationCost(VectorTy) +
6486          TTI.getGatherScatterOpCost(
6487              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6488              TargetTransformInfo::TCK_RecipThroughput, I);
6489 }
6490 
6491 InstructionCost
6492 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6493                                                    ElementCount VF) {
6494   // TODO: Once we have support for interleaving with scalable vectors
6495   // we can calculate the cost properly here.
6496   if (VF.isScalable())
6497     return InstructionCost::getInvalid();
6498 
6499   Type *ValTy = getLoadStoreType(I);
6500   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6501   unsigned AS = getLoadStoreAddressSpace(I);
6502 
6503   auto Group = getInterleavedAccessGroup(I);
6504   assert(Group && "Fail to get an interleaved access group.");
6505 
6506   unsigned InterleaveFactor = Group->getFactor();
6507   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6508 
6509   // Holds the indices of existing members in the interleaved group.
6510   SmallVector<unsigned, 4> Indices;
6511   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6512     if (Group->getMember(IF))
6513       Indices.push_back(IF);
6514 
6515   // Calculate the cost of the whole interleaved group.
6516   bool UseMaskForGaps =
6517       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6518       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6519   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6520       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6521       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6522 
6523   if (Group->isReverse()) {
6524     // TODO: Add support for reversed masked interleaved access.
6525     assert(!Legal->isMaskRequired(I) &&
6526            "Reverse masked interleaved access not supported.");
6527     Cost +=
6528         Group->getNumMembers() *
6529         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6530   }
6531   return Cost;
6532 }
6533 
6534 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6535     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6536   using namespace llvm::PatternMatch;
6537   // Early exit for no inloop reductions
6538   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6539     return None;
6540   auto *VectorTy = cast<VectorType>(Ty);
6541 
6542   // We are looking for a pattern of, and finding the minimal acceptable cost:
6543   //  reduce(mul(ext(A), ext(B))) or
6544   //  reduce(mul(A, B)) or
6545   //  reduce(ext(A)) or
6546   //  reduce(A).
6547   // The basic idea is that we walk down the tree to do that, finding the root
6548   // reduction instruction in InLoopReductionImmediateChains. From there we find
6549   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6550   // of the components. If the reduction cost is lower then we return it for the
6551   // reduction instruction and 0 for the other instructions in the pattern. If
6552   // it is not we return an invalid cost specifying the orignal cost method
6553   // should be used.
6554   Instruction *RetI = I;
6555   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6556     if (!RetI->hasOneUser())
6557       return None;
6558     RetI = RetI->user_back();
6559   }
6560   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6561       RetI->user_back()->getOpcode() == Instruction::Add) {
6562     if (!RetI->hasOneUser())
6563       return None;
6564     RetI = RetI->user_back();
6565   }
6566 
6567   // Test if the found instruction is a reduction, and if not return an invalid
6568   // cost specifying the parent to use the original cost modelling.
6569   if (!InLoopReductionImmediateChains.count(RetI))
6570     return None;
6571 
6572   // Find the reduction this chain is a part of and calculate the basic cost of
6573   // the reduction on its own.
6574   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6575   Instruction *ReductionPhi = LastChain;
6576   while (!isa<PHINode>(ReductionPhi))
6577     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6578 
6579   const RecurrenceDescriptor &RdxDesc =
6580       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6581 
6582   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6583       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6584 
6585   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6586   // normal fmul instruction to the cost of the fadd reduction.
6587   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6588     BaseCost +=
6589         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6590 
6591   // If we're using ordered reductions then we can just return the base cost
6592   // here, since getArithmeticReductionCost calculates the full ordered
6593   // reduction cost when FP reassociation is not allowed.
6594   if (useOrderedReductions(RdxDesc))
6595     return BaseCost;
6596 
6597   // Get the operand that was not the reduction chain and match it to one of the
6598   // patterns, returning the better cost if it is found.
6599   Instruction *RedOp = RetI->getOperand(1) == LastChain
6600                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6601                            : dyn_cast<Instruction>(RetI->getOperand(1));
6602 
6603   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6604 
6605   Instruction *Op0, *Op1;
6606   if (RedOp &&
6607       match(RedOp,
6608             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6609       match(Op0, m_ZExtOrSExt(m_Value())) &&
6610       Op0->getOpcode() == Op1->getOpcode() &&
6611       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6612       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6613       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6614 
6615     // Matched reduce(ext(mul(ext(A), ext(B)))
6616     // Note that the extend opcodes need to all match, or if A==B they will have
6617     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6618     // which is equally fine.
6619     bool IsUnsigned = isa<ZExtInst>(Op0);
6620     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6621     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6622 
6623     InstructionCost ExtCost =
6624         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6625                              TTI::CastContextHint::None, CostKind, Op0);
6626     InstructionCost MulCost =
6627         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6628     InstructionCost Ext2Cost =
6629         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6630                              TTI::CastContextHint::None, CostKind, RedOp);
6631 
6632     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6633         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6634         CostKind);
6635 
6636     if (RedCost.isValid() &&
6637         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6638       return I == RetI ? RedCost : 0;
6639   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
6640              !TheLoop->isLoopInvariant(RedOp)) {
6641     // Matched reduce(ext(A))
6642     bool IsUnsigned = isa<ZExtInst>(RedOp);
6643     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6644     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6645         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6646         CostKind);
6647 
6648     InstructionCost ExtCost =
6649         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6650                              TTI::CastContextHint::None, CostKind, RedOp);
6651     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6652       return I == RetI ? RedCost : 0;
6653   } else if (RedOp &&
6654              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
6655     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
6656         Op0->getOpcode() == Op1->getOpcode() &&
6657         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6658       bool IsUnsigned = isa<ZExtInst>(Op0);
6659       Type *Op0Ty = Op0->getOperand(0)->getType();
6660       Type *Op1Ty = Op1->getOperand(0)->getType();
6661       Type *LargestOpTy =
6662           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
6663                                                                     : Op0Ty;
6664       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
6665 
6666       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
6667       // different sizes. We take the largest type as the ext to reduce, and add
6668       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
6669       InstructionCost ExtCost0 = TTI.getCastInstrCost(
6670           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
6671           TTI::CastContextHint::None, CostKind, Op0);
6672       InstructionCost ExtCost1 = TTI.getCastInstrCost(
6673           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
6674           TTI::CastContextHint::None, CostKind, Op1);
6675       InstructionCost MulCost =
6676           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6677 
6678       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6679           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6680           CostKind);
6681       InstructionCost ExtraExtCost = 0;
6682       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6683         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6684         ExtraExtCost = TTI.getCastInstrCost(
6685             ExtraExtOp->getOpcode(), ExtType,
6686             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
6687             TTI::CastContextHint::None, CostKind, ExtraExtOp);
6688       }
6689 
6690       if (RedCost.isValid() &&
6691           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6692         return I == RetI ? RedCost : 0;
6693     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
6694       // Matched reduce(mul())
6695       InstructionCost MulCost =
6696           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6697 
6698       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6699           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6700           CostKind);
6701 
6702       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6703         return I == RetI ? RedCost : 0;
6704     }
6705   }
6706 
6707   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
6708 }
6709 
6710 InstructionCost
6711 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6712                                                      ElementCount VF) {
6713   // Calculate scalar cost only. Vectorization cost should be ready at this
6714   // moment.
6715   if (VF.isScalar()) {
6716     Type *ValTy = getLoadStoreType(I);
6717     const Align Alignment = getLoadStoreAlignment(I);
6718     unsigned AS = getLoadStoreAddressSpace(I);
6719 
6720     return TTI.getAddressComputationCost(ValTy) +
6721            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6722                                TTI::TCK_RecipThroughput, I);
6723   }
6724   return getWideningCost(I, VF);
6725 }
6726 
6727 LoopVectorizationCostModel::VectorizationCostTy
6728 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6729                                                ElementCount VF) {
6730   // If we know that this instruction will remain uniform, check the cost of
6731   // the scalar version.
6732   if (isUniformAfterVectorization(I, VF))
6733     VF = ElementCount::getFixed(1);
6734 
6735   if (VF.isVector() && isProfitableToScalarize(I, VF))
6736     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6737 
6738   // Forced scalars do not have any scalarization overhead.
6739   auto ForcedScalar = ForcedScalars.find(VF);
6740   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6741     auto InstSet = ForcedScalar->second;
6742     if (InstSet.count(I))
6743       return VectorizationCostTy(
6744           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6745            VF.getKnownMinValue()),
6746           false);
6747   }
6748 
6749   Type *VectorTy;
6750   InstructionCost C = getInstructionCost(I, VF, VectorTy);
6751 
6752   bool TypeNotScalarized = false;
6753   if (VF.isVector() && VectorTy->isVectorTy()) {
6754     unsigned NumParts = TTI.getNumberOfParts(VectorTy);
6755     if (NumParts)
6756       TypeNotScalarized = NumParts < VF.getKnownMinValue();
6757     else
6758       C = InstructionCost::getInvalid();
6759   }
6760   return VectorizationCostTy(C, TypeNotScalarized);
6761 }
6762 
6763 InstructionCost
6764 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6765                                                      ElementCount VF) const {
6766 
6767   // There is no mechanism yet to create a scalable scalarization loop,
6768   // so this is currently Invalid.
6769   if (VF.isScalable())
6770     return InstructionCost::getInvalid();
6771 
6772   if (VF.isScalar())
6773     return 0;
6774 
6775   InstructionCost Cost = 0;
6776   Type *RetTy = ToVectorTy(I->getType(), VF);
6777   if (!RetTy->isVoidTy() &&
6778       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6779     Cost += TTI.getScalarizationOverhead(
6780         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
6781         false);
6782 
6783   // Some targets keep addresses scalar.
6784   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6785     return Cost;
6786 
6787   // Some targets support efficient element stores.
6788   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6789     return Cost;
6790 
6791   // Collect operands to consider.
6792   CallInst *CI = dyn_cast<CallInst>(I);
6793   Instruction::op_range Ops = CI ? CI->args() : I->operands();
6794 
6795   // Skip operands that do not require extraction/scalarization and do not incur
6796   // any overhead.
6797   SmallVector<Type *> Tys;
6798   for (auto *V : filterExtractingOperands(Ops, VF))
6799     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
6800   return Cost + TTI.getOperandsScalarizationOverhead(
6801                     filterExtractingOperands(Ops, VF), Tys);
6802 }
6803 
6804 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6805   if (VF.isScalar())
6806     return;
6807   NumPredStores = 0;
6808   for (BasicBlock *BB : TheLoop->blocks()) {
6809     // For each instruction in the old loop.
6810     for (Instruction &I : *BB) {
6811       Value *Ptr =  getLoadStorePointerOperand(&I);
6812       if (!Ptr)
6813         continue;
6814 
6815       // TODO: We should generate better code and update the cost model for
6816       // predicated uniform stores. Today they are treated as any other
6817       // predicated store (see added test cases in
6818       // invariant-store-vectorization.ll).
6819       if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
6820         NumPredStores++;
6821 
6822       if (Legal->isUniformMemOp(I)) {
6823         // TODO: Avoid replicating loads and stores instead of
6824         // relying on instcombine to remove them.
6825         // Load: Scalar load + broadcast
6826         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6827         InstructionCost Cost;
6828         if (isa<StoreInst>(&I) && VF.isScalable() &&
6829             isLegalGatherOrScatter(&I, VF)) {
6830           Cost = getGatherScatterCost(&I, VF);
6831           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
6832         } else {
6833           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
6834                  "Cannot yet scalarize uniform stores");
6835           Cost = getUniformMemOpCost(&I, VF);
6836           setWideningDecision(&I, VF, CM_Scalarize, Cost);
6837         }
6838         continue;
6839       }
6840 
6841       // We assume that widening is the best solution when possible.
6842       if (memoryInstructionCanBeWidened(&I, VF)) {
6843         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
6844         int ConsecutiveStride = Legal->isConsecutivePtr(
6845             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
6846         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6847                "Expected consecutive stride.");
6848         InstWidening Decision =
6849             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6850         setWideningDecision(&I, VF, Decision, Cost);
6851         continue;
6852       }
6853 
6854       // Choose between Interleaving, Gather/Scatter or Scalarization.
6855       InstructionCost InterleaveCost = InstructionCost::getInvalid();
6856       unsigned NumAccesses = 1;
6857       if (isAccessInterleaved(&I)) {
6858         auto Group = getInterleavedAccessGroup(&I);
6859         assert(Group && "Fail to get an interleaved access group.");
6860 
6861         // Make one decision for the whole group.
6862         if (getWideningDecision(&I, VF) != CM_Unknown)
6863           continue;
6864 
6865         NumAccesses = Group->getNumMembers();
6866         if (interleavedAccessCanBeWidened(&I, VF))
6867           InterleaveCost = getInterleaveGroupCost(&I, VF);
6868       }
6869 
6870       InstructionCost GatherScatterCost =
6871           isLegalGatherOrScatter(&I, VF)
6872               ? getGatherScatterCost(&I, VF) * NumAccesses
6873               : InstructionCost::getInvalid();
6874 
6875       InstructionCost ScalarizationCost =
6876           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6877 
6878       // Choose better solution for the current VF,
6879       // write down this decision and use it during vectorization.
6880       InstructionCost Cost;
6881       InstWidening Decision;
6882       if (InterleaveCost <= GatherScatterCost &&
6883           InterleaveCost < ScalarizationCost) {
6884         Decision = CM_Interleave;
6885         Cost = InterleaveCost;
6886       } else if (GatherScatterCost < ScalarizationCost) {
6887         Decision = CM_GatherScatter;
6888         Cost = GatherScatterCost;
6889       } else {
6890         Decision = CM_Scalarize;
6891         Cost = ScalarizationCost;
6892       }
6893       // If the instructions belongs to an interleave group, the whole group
6894       // receives the same decision. The whole group receives the cost, but
6895       // the cost will actually be assigned to one instruction.
6896       if (auto Group = getInterleavedAccessGroup(&I))
6897         setWideningDecision(Group, VF, Decision, Cost);
6898       else
6899         setWideningDecision(&I, VF, Decision, Cost);
6900     }
6901   }
6902 
6903   // Make sure that any load of address and any other address computation
6904   // remains scalar unless there is gather/scatter support. This avoids
6905   // inevitable extracts into address registers, and also has the benefit of
6906   // activating LSR more, since that pass can't optimize vectorized
6907   // addresses.
6908   if (TTI.prefersVectorizedAddressing())
6909     return;
6910 
6911   // Start with all scalar pointer uses.
6912   SmallPtrSet<Instruction *, 8> AddrDefs;
6913   for (BasicBlock *BB : TheLoop->blocks())
6914     for (Instruction &I : *BB) {
6915       Instruction *PtrDef =
6916         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6917       if (PtrDef && TheLoop->contains(PtrDef) &&
6918           getWideningDecision(&I, VF) != CM_GatherScatter)
6919         AddrDefs.insert(PtrDef);
6920     }
6921 
6922   // Add all instructions used to generate the addresses.
6923   SmallVector<Instruction *, 4> Worklist;
6924   append_range(Worklist, AddrDefs);
6925   while (!Worklist.empty()) {
6926     Instruction *I = Worklist.pop_back_val();
6927     for (auto &Op : I->operands())
6928       if (auto *InstOp = dyn_cast<Instruction>(Op))
6929         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6930             AddrDefs.insert(InstOp).second)
6931           Worklist.push_back(InstOp);
6932   }
6933 
6934   for (auto *I : AddrDefs) {
6935     if (isa<LoadInst>(I)) {
6936       // Setting the desired widening decision should ideally be handled in
6937       // by cost functions, but since this involves the task of finding out
6938       // if the loaded register is involved in an address computation, it is
6939       // instead changed here when we know this is the case.
6940       InstWidening Decision = getWideningDecision(I, VF);
6941       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6942         // Scalarize a widened load of address.
6943         setWideningDecision(
6944             I, VF, CM_Scalarize,
6945             (VF.getKnownMinValue() *
6946              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6947       else if (auto Group = getInterleavedAccessGroup(I)) {
6948         // Scalarize an interleave group of address loads.
6949         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6950           if (Instruction *Member = Group->getMember(I))
6951             setWideningDecision(
6952                 Member, VF, CM_Scalarize,
6953                 (VF.getKnownMinValue() *
6954                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6955         }
6956       }
6957     } else
6958       // Make sure I gets scalarized and a cost estimate without
6959       // scalarization overhead.
6960       ForcedScalars[VF].insert(I);
6961   }
6962 }
6963 
6964 InstructionCost
6965 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
6966                                                Type *&VectorTy) {
6967   Type *RetTy = I->getType();
6968   if (canTruncateToMinimalBitwidth(I, VF))
6969     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6970   auto SE = PSE.getSE();
6971   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6972 
6973   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
6974                                                 ElementCount VF) -> bool {
6975     if (VF.isScalar())
6976       return true;
6977 
6978     auto Scalarized = InstsToScalarize.find(VF);
6979     assert(Scalarized != InstsToScalarize.end() &&
6980            "VF not yet analyzed for scalarization profitability");
6981     return !Scalarized->second.count(I) &&
6982            llvm::all_of(I->users(), [&](User *U) {
6983              auto *UI = cast<Instruction>(U);
6984              return !Scalarized->second.count(UI);
6985            });
6986   };
6987   (void) hasSingleCopyAfterVectorization;
6988 
6989   if (isScalarAfterVectorization(I, VF)) {
6990     // With the exception of GEPs and PHIs, after scalarization there should
6991     // only be one copy of the instruction generated in the loop. This is
6992     // because the VF is either 1, or any instructions that need scalarizing
6993     // have already been dealt with by the the time we get here. As a result,
6994     // it means we don't have to multiply the instruction cost by VF.
6995     assert(I->getOpcode() == Instruction::GetElementPtr ||
6996            I->getOpcode() == Instruction::PHI ||
6997            (I->getOpcode() == Instruction::BitCast &&
6998             I->getType()->isPointerTy()) ||
6999            hasSingleCopyAfterVectorization(I, VF));
7000     VectorTy = RetTy;
7001   } else
7002     VectorTy = ToVectorTy(RetTy, VF);
7003 
7004   // TODO: We need to estimate the cost of intrinsic calls.
7005   switch (I->getOpcode()) {
7006   case Instruction::GetElementPtr:
7007     // We mark this instruction as zero-cost because the cost of GEPs in
7008     // vectorized code depends on whether the corresponding memory instruction
7009     // is scalarized or not. Therefore, we handle GEPs with the memory
7010     // instruction cost.
7011     return 0;
7012   case Instruction::Br: {
7013     // In cases of scalarized and predicated instructions, there will be VF
7014     // predicated blocks in the vectorized loop. Each branch around these
7015     // blocks requires also an extract of its vector compare i1 element.
7016     bool ScalarPredicatedBB = false;
7017     BranchInst *BI = cast<BranchInst>(I);
7018     if (VF.isVector() && BI->isConditional() &&
7019         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7020          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7021       ScalarPredicatedBB = true;
7022 
7023     if (ScalarPredicatedBB) {
7024       // Not possible to scalarize scalable vector with predicated instructions.
7025       if (VF.isScalable())
7026         return InstructionCost::getInvalid();
7027       // Return cost for branches around scalarized and predicated blocks.
7028       auto *Vec_i1Ty =
7029           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7030       return (
7031           TTI.getScalarizationOverhead(
7032               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7033           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7034     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7035       // The back-edge branch will remain, as will all scalar branches.
7036       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7037     else
7038       // This branch will be eliminated by if-conversion.
7039       return 0;
7040     // Note: We currently assume zero cost for an unconditional branch inside
7041     // a predicated block since it will become a fall-through, although we
7042     // may decide in the future to call TTI for all branches.
7043   }
7044   case Instruction::PHI: {
7045     auto *Phi = cast<PHINode>(I);
7046 
7047     // First-order recurrences are replaced by vector shuffles inside the loop.
7048     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7049     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7050       return TTI.getShuffleCost(
7051           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7052           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7053 
7054     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7055     // converted into select instructions. We require N - 1 selects per phi
7056     // node, where N is the number of incoming values.
7057     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7058       return (Phi->getNumIncomingValues() - 1) *
7059              TTI.getCmpSelInstrCost(
7060                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7061                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7062                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7063 
7064     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7065   }
7066   case Instruction::UDiv:
7067   case Instruction::SDiv:
7068   case Instruction::URem:
7069   case Instruction::SRem:
7070     // If we have a predicated instruction, it may not be executed for each
7071     // vector lane. Get the scalarization cost and scale this amount by the
7072     // probability of executing the predicated block. If the instruction is not
7073     // predicated, we fall through to the next case.
7074     if (VF.isVector() && isScalarWithPredication(I, VF)) {
7075       InstructionCost Cost = 0;
7076 
7077       // These instructions have a non-void type, so account for the phi nodes
7078       // that we will create. This cost is likely to be zero. The phi node
7079       // cost, if any, should be scaled by the block probability because it
7080       // models a copy at the end of each predicated block.
7081       Cost += VF.getKnownMinValue() *
7082               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7083 
7084       // The cost of the non-predicated instruction.
7085       Cost += VF.getKnownMinValue() *
7086               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7087 
7088       // The cost of insertelement and extractelement instructions needed for
7089       // scalarization.
7090       Cost += getScalarizationOverhead(I, VF);
7091 
7092       // Scale the cost by the probability of executing the predicated blocks.
7093       // This assumes the predicated block for each vector lane is equally
7094       // likely.
7095       return Cost / getReciprocalPredBlockProb();
7096     }
7097     LLVM_FALLTHROUGH;
7098   case Instruction::Add:
7099   case Instruction::FAdd:
7100   case Instruction::Sub:
7101   case Instruction::FSub:
7102   case Instruction::Mul:
7103   case Instruction::FMul:
7104   case Instruction::FDiv:
7105   case Instruction::FRem:
7106   case Instruction::Shl:
7107   case Instruction::LShr:
7108   case Instruction::AShr:
7109   case Instruction::And:
7110   case Instruction::Or:
7111   case Instruction::Xor: {
7112     // Since we will replace the stride by 1 the multiplication should go away.
7113     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7114       return 0;
7115 
7116     // Detect reduction patterns
7117     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7118       return *RedCost;
7119 
7120     // Certain instructions can be cheaper to vectorize if they have a constant
7121     // second vector operand. One example of this are shifts on x86.
7122     Value *Op2 = I->getOperand(1);
7123     TargetTransformInfo::OperandValueProperties Op2VP;
7124     TargetTransformInfo::OperandValueKind Op2VK =
7125         TTI.getOperandInfo(Op2, Op2VP);
7126     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7127       Op2VK = TargetTransformInfo::OK_UniformValue;
7128 
7129     SmallVector<const Value *, 4> Operands(I->operand_values());
7130     return TTI.getArithmeticInstrCost(
7131         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7132         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7133   }
7134   case Instruction::FNeg: {
7135     return TTI.getArithmeticInstrCost(
7136         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7137         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7138         TargetTransformInfo::OP_None, I->getOperand(0), I);
7139   }
7140   case Instruction::Select: {
7141     SelectInst *SI = cast<SelectInst>(I);
7142     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7143     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7144 
7145     const Value *Op0, *Op1;
7146     using namespace llvm::PatternMatch;
7147     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7148                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7149       // select x, y, false --> x & y
7150       // select x, true, y --> x | y
7151       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7152       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7153       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7154       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7155       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7156               Op1->getType()->getScalarSizeInBits() == 1);
7157 
7158       SmallVector<const Value *, 2> Operands{Op0, Op1};
7159       return TTI.getArithmeticInstrCost(
7160           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7161           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7162     }
7163 
7164     Type *CondTy = SI->getCondition()->getType();
7165     if (!ScalarCond)
7166       CondTy = VectorType::get(CondTy, VF);
7167 
7168     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7169     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7170       Pred = Cmp->getPredicate();
7171     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7172                                   CostKind, I);
7173   }
7174   case Instruction::ICmp:
7175   case Instruction::FCmp: {
7176     Type *ValTy = I->getOperand(0)->getType();
7177     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7178     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7179       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7180     VectorTy = ToVectorTy(ValTy, VF);
7181     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7182                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7183                                   I);
7184   }
7185   case Instruction::Store:
7186   case Instruction::Load: {
7187     ElementCount Width = VF;
7188     if (Width.isVector()) {
7189       InstWidening Decision = getWideningDecision(I, Width);
7190       assert(Decision != CM_Unknown &&
7191              "CM decision should be taken at this point");
7192       if (Decision == CM_Scalarize)
7193         Width = ElementCount::getFixed(1);
7194     }
7195     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7196     return getMemoryInstructionCost(I, VF);
7197   }
7198   case Instruction::BitCast:
7199     if (I->getType()->isPointerTy())
7200       return 0;
7201     LLVM_FALLTHROUGH;
7202   case Instruction::ZExt:
7203   case Instruction::SExt:
7204   case Instruction::FPToUI:
7205   case Instruction::FPToSI:
7206   case Instruction::FPExt:
7207   case Instruction::PtrToInt:
7208   case Instruction::IntToPtr:
7209   case Instruction::SIToFP:
7210   case Instruction::UIToFP:
7211   case Instruction::Trunc:
7212   case Instruction::FPTrunc: {
7213     // Computes the CastContextHint from a Load/Store instruction.
7214     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7215       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7216              "Expected a load or a store!");
7217 
7218       if (VF.isScalar() || !TheLoop->contains(I))
7219         return TTI::CastContextHint::Normal;
7220 
7221       switch (getWideningDecision(I, VF)) {
7222       case LoopVectorizationCostModel::CM_GatherScatter:
7223         return TTI::CastContextHint::GatherScatter;
7224       case LoopVectorizationCostModel::CM_Interleave:
7225         return TTI::CastContextHint::Interleave;
7226       case LoopVectorizationCostModel::CM_Scalarize:
7227       case LoopVectorizationCostModel::CM_Widen:
7228         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7229                                         : TTI::CastContextHint::Normal;
7230       case LoopVectorizationCostModel::CM_Widen_Reverse:
7231         return TTI::CastContextHint::Reversed;
7232       case LoopVectorizationCostModel::CM_Unknown:
7233         llvm_unreachable("Instr did not go through cost modelling?");
7234       }
7235 
7236       llvm_unreachable("Unhandled case!");
7237     };
7238 
7239     unsigned Opcode = I->getOpcode();
7240     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7241     // For Trunc, the context is the only user, which must be a StoreInst.
7242     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7243       if (I->hasOneUse())
7244         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7245           CCH = ComputeCCH(Store);
7246     }
7247     // For Z/Sext, the context is the operand, which must be a LoadInst.
7248     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7249              Opcode == Instruction::FPExt) {
7250       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7251         CCH = ComputeCCH(Load);
7252     }
7253 
7254     // We optimize the truncation of induction variables having constant
7255     // integer steps. The cost of these truncations is the same as the scalar
7256     // operation.
7257     if (isOptimizableIVTruncate(I, VF)) {
7258       auto *Trunc = cast<TruncInst>(I);
7259       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7260                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7261     }
7262 
7263     // Detect reduction patterns
7264     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7265       return *RedCost;
7266 
7267     Type *SrcScalarTy = I->getOperand(0)->getType();
7268     Type *SrcVecTy =
7269         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7270     if (canTruncateToMinimalBitwidth(I, VF)) {
7271       // This cast is going to be shrunk. This may remove the cast or it might
7272       // turn it into slightly different cast. For example, if MinBW == 16,
7273       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7274       //
7275       // Calculate the modified src and dest types.
7276       Type *MinVecTy = VectorTy;
7277       if (Opcode == Instruction::Trunc) {
7278         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7279         VectorTy =
7280             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7281       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7282         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7283         VectorTy =
7284             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7285       }
7286     }
7287 
7288     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7289   }
7290   case Instruction::Call: {
7291     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7292       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7293         return *RedCost;
7294     bool NeedToScalarize;
7295     CallInst *CI = cast<CallInst>(I);
7296     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7297     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7298       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7299       return std::min(CallCost, IntrinsicCost);
7300     }
7301     return CallCost;
7302   }
7303   case Instruction::ExtractValue:
7304     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7305   case Instruction::Alloca:
7306     // We cannot easily widen alloca to a scalable alloca, as
7307     // the result would need to be a vector of pointers.
7308     if (VF.isScalable())
7309       return InstructionCost::getInvalid();
7310     LLVM_FALLTHROUGH;
7311   default:
7312     // This opcode is unknown. Assume that it is the same as 'mul'.
7313     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7314   } // end of switch.
7315 }
7316 
7317 char LoopVectorize::ID = 0;
7318 
7319 static const char lv_name[] = "Loop Vectorization";
7320 
7321 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7322 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7323 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7324 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7325 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7326 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7327 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7328 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7329 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7330 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7331 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7332 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7333 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7334 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7335 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7336 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7337 
7338 namespace llvm {
7339 
7340 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7341 
7342 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7343                               bool VectorizeOnlyWhenForced) {
7344   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7345 }
7346 
7347 } // end namespace llvm
7348 
7349 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7350   // Check if the pointer operand of a load or store instruction is
7351   // consecutive.
7352   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7353     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7354   return false;
7355 }
7356 
7357 void LoopVectorizationCostModel::collectValuesToIgnore() {
7358   // Ignore ephemeral values.
7359   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7360 
7361   // Find all stores to invariant variables. Since they are going to sink
7362   // outside the loop we do not need calculate cost for them.
7363   for (BasicBlock *BB : TheLoop->blocks())
7364     for (Instruction &I : *BB) {
7365       StoreInst *SI;
7366       if ((SI = dyn_cast<StoreInst>(&I)) &&
7367           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
7368         ValuesToIgnore.insert(&I);
7369     }
7370 
7371   // Ignore type-promoting instructions we identified during reduction
7372   // detection.
7373   for (auto &Reduction : Legal->getReductionVars()) {
7374     const RecurrenceDescriptor &RedDes = Reduction.second;
7375     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7376     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7377   }
7378   // Ignore type-casting instructions we identified during induction
7379   // detection.
7380   for (auto &Induction : Legal->getInductionVars()) {
7381     const InductionDescriptor &IndDes = Induction.second;
7382     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7383     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7384   }
7385 }
7386 
7387 void LoopVectorizationCostModel::collectInLoopReductions() {
7388   for (auto &Reduction : Legal->getReductionVars()) {
7389     PHINode *Phi = Reduction.first;
7390     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7391 
7392     // We don't collect reductions that are type promoted (yet).
7393     if (RdxDesc.getRecurrenceType() != Phi->getType())
7394       continue;
7395 
7396     // If the target would prefer this reduction to happen "in-loop", then we
7397     // want to record it as such.
7398     unsigned Opcode = RdxDesc.getOpcode();
7399     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7400         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7401                                    TargetTransformInfo::ReductionFlags()))
7402       continue;
7403 
7404     // Check that we can correctly put the reductions into the loop, by
7405     // finding the chain of operations that leads from the phi to the loop
7406     // exit value.
7407     SmallVector<Instruction *, 4> ReductionOperations =
7408         RdxDesc.getReductionOpChain(Phi, TheLoop);
7409     bool InLoop = !ReductionOperations.empty();
7410     if (InLoop) {
7411       InLoopReductionChains[Phi] = ReductionOperations;
7412       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7413       Instruction *LastChain = Phi;
7414       for (auto *I : ReductionOperations) {
7415         InLoopReductionImmediateChains[I] = LastChain;
7416         LastChain = I;
7417       }
7418     }
7419     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7420                       << " reduction for phi: " << *Phi << "\n");
7421   }
7422 }
7423 
7424 // TODO: we could return a pair of values that specify the max VF and
7425 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7426 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7427 // doesn't have a cost model that can choose which plan to execute if
7428 // more than one is generated.
7429 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7430                                  LoopVectorizationCostModel &CM) {
7431   unsigned WidestType;
7432   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7433   return WidestVectorRegBits / WidestType;
7434 }
7435 
7436 VectorizationFactor
7437 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7438   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7439   ElementCount VF = UserVF;
7440   // Outer loop handling: They may require CFG and instruction level
7441   // transformations before even evaluating whether vectorization is profitable.
7442   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7443   // the vectorization pipeline.
7444   if (!OrigLoop->isInnermost()) {
7445     // If the user doesn't provide a vectorization factor, determine a
7446     // reasonable one.
7447     if (UserVF.isZero()) {
7448       VF = ElementCount::getFixed(determineVPlanVF(
7449           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7450               .getFixedSize(),
7451           CM));
7452       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7453 
7454       // Make sure we have a VF > 1 for stress testing.
7455       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7456         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7457                           << "overriding computed VF.\n");
7458         VF = ElementCount::getFixed(4);
7459       }
7460     }
7461     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7462     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7463            "VF needs to be a power of two");
7464     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7465                       << "VF " << VF << " to build VPlans.\n");
7466     buildVPlans(VF, VF);
7467 
7468     // For VPlan build stress testing, we bail out after VPlan construction.
7469     if (VPlanBuildStressTest)
7470       return VectorizationFactor::Disabled();
7471 
7472     return {VF, 0 /*Cost*/};
7473   }
7474 
7475   LLVM_DEBUG(
7476       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7477                 "VPlan-native path.\n");
7478   return VectorizationFactor::Disabled();
7479 }
7480 
7481 Optional<VectorizationFactor>
7482 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7483   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7484   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7485   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7486     return None;
7487 
7488   // Invalidate interleave groups if all blocks of loop will be predicated.
7489   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7490       !useMaskedInterleavedAccesses(*TTI)) {
7491     LLVM_DEBUG(
7492         dbgs()
7493         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7494            "which requires masked-interleaved support.\n");
7495     if (CM.InterleaveInfo.invalidateGroups())
7496       // Invalidating interleave groups also requires invalidating all decisions
7497       // based on them, which includes widening decisions and uniform and scalar
7498       // values.
7499       CM.invalidateCostModelingDecisions();
7500   }
7501 
7502   ElementCount MaxUserVF =
7503       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7504   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7505   if (!UserVF.isZero() && UserVFIsLegal) {
7506     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7507            "VF needs to be a power of two");
7508     // Collect the instructions (and their associated costs) that will be more
7509     // profitable to scalarize.
7510     if (CM.selectUserVectorizationFactor(UserVF)) {
7511       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7512       CM.collectInLoopReductions();
7513       buildVPlansWithVPRecipes(UserVF, UserVF);
7514       LLVM_DEBUG(printPlans(dbgs()));
7515       return {{UserVF, 0}};
7516     } else
7517       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7518                               "InvalidCost", ORE, OrigLoop);
7519   }
7520 
7521   // Populate the set of Vectorization Factor Candidates.
7522   ElementCountSet VFCandidates;
7523   for (auto VF = ElementCount::getFixed(1);
7524        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7525     VFCandidates.insert(VF);
7526   for (auto VF = ElementCount::getScalable(1);
7527        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7528     VFCandidates.insert(VF);
7529 
7530   for (const auto &VF : VFCandidates) {
7531     // Collect Uniform and Scalar instructions after vectorization with VF.
7532     CM.collectUniformsAndScalars(VF);
7533 
7534     // Collect the instructions (and their associated costs) that will be more
7535     // profitable to scalarize.
7536     if (VF.isVector())
7537       CM.collectInstsToScalarize(VF);
7538   }
7539 
7540   CM.collectInLoopReductions();
7541   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7542   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7543 
7544   LLVM_DEBUG(printPlans(dbgs()));
7545   if (!MaxFactors.hasVector())
7546     return VectorizationFactor::Disabled();
7547 
7548   // Select the optimal vectorization factor.
7549   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
7550 
7551   // Check if it is profitable to vectorize with runtime checks.
7552   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7553   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
7554     bool PragmaThresholdReached =
7555         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7556     bool ThresholdReached =
7557         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
7558     if ((ThresholdReached && !Hints.allowReordering()) ||
7559         PragmaThresholdReached) {
7560       ORE->emit([&]() {
7561         return OptimizationRemarkAnalysisAliasing(
7562                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
7563                    OrigLoop->getHeader())
7564                << "loop not vectorized: cannot prove it is safe to reorder "
7565                   "memory operations";
7566       });
7567       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7568       Hints.emitRemarkWithHints();
7569       return VectorizationFactor::Disabled();
7570     }
7571   }
7572   return SelectedVF;
7573 }
7574 
7575 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7576   assert(count_if(VPlans,
7577                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7578              1 &&
7579          "Best VF has not a single VPlan.");
7580 
7581   for (const VPlanPtr &Plan : VPlans) {
7582     if (Plan->hasVF(VF))
7583       return *Plan.get();
7584   }
7585   llvm_unreachable("No plan found!");
7586 }
7587 
7588 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7589   SmallVector<Metadata *, 4> MDs;
7590   // Reserve first location for self reference to the LoopID metadata node.
7591   MDs.push_back(nullptr);
7592   bool IsUnrollMetadata = false;
7593   MDNode *LoopID = L->getLoopID();
7594   if (LoopID) {
7595     // First find existing loop unrolling disable metadata.
7596     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7597       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7598       if (MD) {
7599         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7600         IsUnrollMetadata =
7601             S && S->getString().startswith("llvm.loop.unroll.disable");
7602       }
7603       MDs.push_back(LoopID->getOperand(i));
7604     }
7605   }
7606 
7607   if (!IsUnrollMetadata) {
7608     // Add runtime unroll disable metadata.
7609     LLVMContext &Context = L->getHeader()->getContext();
7610     SmallVector<Metadata *, 1> DisableOperands;
7611     DisableOperands.push_back(
7612         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7613     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7614     MDs.push_back(DisableNode);
7615     MDNode *NewLoopID = MDNode::get(Context, MDs);
7616     // Set operand 0 to refer to the loop id itself.
7617     NewLoopID->replaceOperandWith(0, NewLoopID);
7618     L->setLoopID(NewLoopID);
7619   }
7620 }
7621 
7622 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7623                                            VPlan &BestVPlan,
7624                                            InnerLoopVectorizer &ILV,
7625                                            DominatorTree *DT) {
7626   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7627                     << '\n');
7628 
7629   // Perform the actual loop transformation.
7630 
7631   // 1. Set up the skeleton for vectorization, including vector pre-header and
7632   // middle block. The vector loop is created during VPlan execution.
7633   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7634   Value *CanonicalIVStartValue;
7635   std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
7636       ILV.createVectorizedLoopSkeleton();
7637   ILV.collectPoisonGeneratingRecipes(State);
7638 
7639   ILV.printDebugTracesAtStart();
7640 
7641   //===------------------------------------------------===//
7642   //
7643   // Notice: any optimization or new instruction that go
7644   // into the code below should also be implemented in
7645   // the cost-model.
7646   //
7647   //===------------------------------------------------===//
7648 
7649   // 2. Copy and widen instructions from the old loop into the new loop.
7650   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
7651                              ILV.getOrCreateVectorTripCount(nullptr),
7652                              CanonicalIVStartValue, State);
7653   BestVPlan.execute(&State);
7654 
7655   // Keep all loop hints from the original loop on the vector loop (we'll
7656   // replace the vectorizer-specific hints below).
7657   MDNode *OrigLoopID = OrigLoop->getLoopID();
7658 
7659   Optional<MDNode *> VectorizedLoopID =
7660       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7661                                       LLVMLoopVectorizeFollowupVectorized});
7662 
7663   VPBasicBlock *HeaderVPBB =
7664       BestVPlan.getVectorLoopRegion()->getEntryBasicBlock();
7665   Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
7666   if (VectorizedLoopID.hasValue())
7667     L->setLoopID(VectorizedLoopID.getValue());
7668   else {
7669     // Keep all loop hints from the original loop on the vector loop (we'll
7670     // replace the vectorizer-specific hints below).
7671     if (MDNode *LID = OrigLoop->getLoopID())
7672       L->setLoopID(LID);
7673 
7674     LoopVectorizeHints Hints(L, true, *ORE);
7675     Hints.setAlreadyVectorized();
7676   }
7677   // Disable runtime unrolling when vectorizing the epilogue loop.
7678   if (CanonicalIVStartValue)
7679     AddRuntimeUnrollDisableMetaData(L);
7680 
7681   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7682   //    predication, updating analyses.
7683   ILV.fixVectorizedLoop(State, BestVPlan);
7684 
7685   ILV.printDebugTracesAtEnd();
7686 }
7687 
7688 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7689 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7690   for (const auto &Plan : VPlans)
7691     if (PrintVPlansInDotFormat)
7692       Plan->printDOT(O);
7693     else
7694       Plan->print(O);
7695 }
7696 #endif
7697 
7698 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7699     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7700 
7701   // We create new control-flow for the vectorized loop, so the original exit
7702   // conditions will be dead after vectorization if it's only used by the
7703   // terminator
7704   SmallVector<BasicBlock*> ExitingBlocks;
7705   OrigLoop->getExitingBlocks(ExitingBlocks);
7706   for (auto *BB : ExitingBlocks) {
7707     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
7708     if (!Cmp || !Cmp->hasOneUse())
7709       continue;
7710 
7711     // TODO: we should introduce a getUniqueExitingBlocks on Loop
7712     if (!DeadInstructions.insert(Cmp).second)
7713       continue;
7714 
7715     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7716     // TODO: can recurse through operands in general
7717     for (Value *Op : Cmp->operands()) {
7718       if (isa<TruncInst>(Op) && Op->hasOneUse())
7719           DeadInstructions.insert(cast<Instruction>(Op));
7720     }
7721   }
7722 
7723   // We create new "steps" for induction variable updates to which the original
7724   // induction variables map. An original update instruction will be dead if
7725   // all its users except the induction variable are dead.
7726   auto *Latch = OrigLoop->getLoopLatch();
7727   for (auto &Induction : Legal->getInductionVars()) {
7728     PHINode *Ind = Induction.first;
7729     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7730 
7731     // If the tail is to be folded by masking, the primary induction variable,
7732     // if exists, isn't dead: it will be used for masking. Don't kill it.
7733     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
7734       continue;
7735 
7736     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7737           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7738         }))
7739       DeadInstructions.insert(IndUpdate);
7740   }
7741 }
7742 
7743 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7744 
7745 //===--------------------------------------------------------------------===//
7746 // EpilogueVectorizerMainLoop
7747 //===--------------------------------------------------------------------===//
7748 
7749 /// This function is partially responsible for generating the control flow
7750 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7751 std::pair<BasicBlock *, Value *>
7752 EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7753   MDNode *OrigLoopID = OrigLoop->getLoopID();
7754 
7755   // Workaround!  Compute the trip count of the original loop and cache it
7756   // before we start modifying the CFG.  This code has a systemic problem
7757   // wherein it tries to run analysis over partially constructed IR; this is
7758   // wrong, and not simply for SCEV.  The trip count of the original loop
7759   // simply happens to be prone to hitting this in practice.  In theory, we
7760   // can hit the same issue for any SCEV, or ValueTracking query done during
7761   // mutation.  See PR49900.
7762   getOrCreateTripCount(OrigLoop->getLoopPreheader());
7763   createVectorLoopSkeleton("");
7764 
7765   // Generate the code to check the minimum iteration count of the vector
7766   // epilogue (see below).
7767   EPI.EpilogueIterationCountCheck =
7768       emitIterationCountCheck(LoopScalarPreHeader, true);
7769   EPI.EpilogueIterationCountCheck->setName("iter.check");
7770 
7771   // Generate the code to check any assumptions that we've made for SCEV
7772   // expressions.
7773   EPI.SCEVSafetyCheck = emitSCEVChecks(LoopScalarPreHeader);
7774 
7775   // Generate the code that checks at runtime if arrays overlap. We put the
7776   // checks into a separate block to make the more common case of few elements
7777   // faster.
7778   EPI.MemSafetyCheck = emitMemRuntimeChecks(LoopScalarPreHeader);
7779 
7780   // Generate the iteration count check for the main loop, *after* the check
7781   // for the epilogue loop, so that the path-length is shorter for the case
7782   // that goes directly through the vector epilogue. The longer-path length for
7783   // the main loop is compensated for, by the gain from vectorizing the larger
7784   // trip count. Note: the branch will get updated later on when we vectorize
7785   // the epilogue.
7786   EPI.MainLoopIterationCountCheck =
7787       emitIterationCountCheck(LoopScalarPreHeader, false);
7788 
7789   // Generate the induction variable.
7790   EPI.VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
7791 
7792   // Skip induction resume value creation here because they will be created in
7793   // the second pass. If we created them here, they wouldn't be used anyway,
7794   // because the vplan in the second pass still contains the inductions from the
7795   // original loop.
7796 
7797   return {completeLoopSkeleton(OrigLoopID), nullptr};
7798 }
7799 
7800 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7801   LLVM_DEBUG({
7802     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7803            << "Main Loop VF:" << EPI.MainLoopVF
7804            << ", Main Loop UF:" << EPI.MainLoopUF
7805            << ", Epilogue Loop VF:" << EPI.EpilogueVF
7806            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7807   });
7808 }
7809 
7810 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7811   DEBUG_WITH_TYPE(VerboseDebug, {
7812     dbgs() << "intermediate fn:\n"
7813            << *OrigLoop->getHeader()->getParent() << "\n";
7814   });
7815 }
7816 
7817 BasicBlock *
7818 EpilogueVectorizerMainLoop::emitIterationCountCheck(BasicBlock *Bypass,
7819                                                     bool ForEpilogue) {
7820   assert(Bypass && "Expected valid bypass basic block.");
7821   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
7822   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
7823   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
7824   // Reuse existing vector loop preheader for TC checks.
7825   // Note that new preheader block is generated for vector loop.
7826   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7827   IRBuilder<> Builder(TCCheckBlock->getTerminator());
7828 
7829   // Generate code to check if the loop's trip count is less than VF * UF of the
7830   // main vector loop.
7831   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
7832       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7833 
7834   Value *CheckMinIters = Builder.CreateICmp(
7835       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
7836       "min.iters.check");
7837 
7838   if (!ForEpilogue)
7839     TCCheckBlock->setName("vector.main.loop.iter.check");
7840 
7841   // Create new preheader for vector loop.
7842   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7843                                    DT, LI, nullptr, "vector.ph");
7844 
7845   if (ForEpilogue) {
7846     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
7847                                  DT->getNode(Bypass)->getIDom()) &&
7848            "TC check is expected to dominate Bypass");
7849 
7850     // Update dominator for Bypass & LoopExit.
7851     DT->changeImmediateDominator(Bypass, TCCheckBlock);
7852     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7853       // For loops with multiple exits, there's no edge from the middle block
7854       // to exit blocks (as the epilogue must run) and thus no need to update
7855       // the immediate dominator of the exit blocks.
7856       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
7857 
7858     LoopBypassBlocks.push_back(TCCheckBlock);
7859 
7860     // Save the trip count so we don't have to regenerate it in the
7861     // vec.epilog.iter.check. This is safe to do because the trip count
7862     // generated here dominates the vector epilog iter check.
7863     EPI.TripCount = Count;
7864   }
7865 
7866   ReplaceInstWithInst(
7867       TCCheckBlock->getTerminator(),
7868       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7869 
7870   return TCCheckBlock;
7871 }
7872 
7873 //===--------------------------------------------------------------------===//
7874 // EpilogueVectorizerEpilogueLoop
7875 //===--------------------------------------------------------------------===//
7876 
7877 /// This function is partially responsible for generating the control flow
7878 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7879 std::pair<BasicBlock *, Value *>
7880 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
7881   MDNode *OrigLoopID = OrigLoop->getLoopID();
7882   createVectorLoopSkeleton("vec.epilog.");
7883 
7884   // Now, compare the remaining count and if there aren't enough iterations to
7885   // execute the vectorized epilogue skip to the scalar part.
7886   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
7887   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
7888   LoopVectorPreHeader =
7889       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
7890                  LI, nullptr, "vec.epilog.ph");
7891   emitMinimumVectorEpilogueIterCountCheck(LoopScalarPreHeader,
7892                                           VecEpilogueIterationCountCheck);
7893 
7894   // Adjust the control flow taking the state info from the main loop
7895   // vectorization into account.
7896   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
7897          "expected this to be saved from the previous pass.");
7898   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
7899       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7900 
7901   DT->changeImmediateDominator(LoopVectorPreHeader,
7902                                EPI.MainLoopIterationCountCheck);
7903 
7904   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
7905       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7906 
7907   if (EPI.SCEVSafetyCheck)
7908     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
7909         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7910   if (EPI.MemSafetyCheck)
7911     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
7912         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7913 
7914   DT->changeImmediateDominator(
7915       VecEpilogueIterationCountCheck,
7916       VecEpilogueIterationCountCheck->getSinglePredecessor());
7917 
7918   DT->changeImmediateDominator(LoopScalarPreHeader,
7919                                EPI.EpilogueIterationCountCheck);
7920   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7921     // If there is an epilogue which must run, there's no edge from the
7922     // middle block to exit blocks  and thus no need to update the immediate
7923     // dominator of the exit blocks.
7924     DT->changeImmediateDominator(LoopExitBlock,
7925                                  EPI.EpilogueIterationCountCheck);
7926 
7927   // Keep track of bypass blocks, as they feed start values to the induction
7928   // phis in the scalar loop preheader.
7929   if (EPI.SCEVSafetyCheck)
7930     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
7931   if (EPI.MemSafetyCheck)
7932     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
7933   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
7934 
7935   // The vec.epilog.iter.check block may contain Phi nodes from reductions which
7936   // merge control-flow from the latch block and the middle block. Update the
7937   // incoming values here and move the Phi into the preheader.
7938   SmallVector<PHINode *, 4> PhisInBlock;
7939   for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
7940     PhisInBlock.push_back(&Phi);
7941 
7942   for (PHINode *Phi : PhisInBlock) {
7943     Phi->replaceIncomingBlockWith(
7944         VecEpilogueIterationCountCheck->getSinglePredecessor(),
7945         VecEpilogueIterationCountCheck);
7946     Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7947     if (EPI.SCEVSafetyCheck)
7948       Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
7949     if (EPI.MemSafetyCheck)
7950       Phi->removeIncomingValue(EPI.MemSafetyCheck);
7951     Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
7952   }
7953 
7954   // Generate a resume induction for the vector epilogue and put it in the
7955   // vector epilogue preheader
7956   Type *IdxTy = Legal->getWidestInductionType();
7957   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
7958                                          LoopVectorPreHeader->getFirstNonPHI());
7959   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
7960   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
7961                            EPI.MainLoopIterationCountCheck);
7962 
7963   // Generate induction resume values. These variables save the new starting
7964   // indexes for the scalar loop. They are used to test if there are any tail
7965   // iterations left once the vector loop has completed.
7966   // Note that when the vectorized epilogue is skipped due to iteration count
7967   // check, then the resume value for the induction variable comes from
7968   // the trip count of the main vector loop, hence passing the AdditionalBypass
7969   // argument.
7970   createInductionResumeValues({VecEpilogueIterationCountCheck,
7971                                EPI.VectorTripCount} /* AdditionalBypass */);
7972 
7973   return {completeLoopSkeleton(OrigLoopID), EPResumeVal};
7974 }
7975 
7976 BasicBlock *
7977 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
7978     BasicBlock *Bypass, BasicBlock *Insert) {
7979 
7980   assert(EPI.TripCount &&
7981          "Expected trip count to have been safed in the first pass.");
7982   assert(
7983       (!isa<Instruction>(EPI.TripCount) ||
7984        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
7985       "saved trip count does not dominate insertion point.");
7986   Value *TC = EPI.TripCount;
7987   IRBuilder<> Builder(Insert->getTerminator());
7988   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7989 
7990   // Generate code to check if the loop's trip count is less than VF * UF of the
7991   // vector epilogue loop.
7992   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
7993       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7994 
7995   Value *CheckMinIters =
7996       Builder.CreateICmp(P, Count,
7997                          createStepForVF(Builder, Count->getType(),
7998                                          EPI.EpilogueVF, EPI.EpilogueUF),
7999                          "min.epilog.iters.check");
8000 
8001   ReplaceInstWithInst(
8002       Insert->getTerminator(),
8003       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8004 
8005   LoopBypassBlocks.push_back(Insert);
8006   return Insert;
8007 }
8008 
8009 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8010   LLVM_DEBUG({
8011     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8012            << "Epilogue Loop VF:" << EPI.EpilogueVF
8013            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8014   });
8015 }
8016 
8017 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8018   DEBUG_WITH_TYPE(VerboseDebug, {
8019     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
8020   });
8021 }
8022 
8023 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8024     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8025   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8026   bool PredicateAtRangeStart = Predicate(Range.Start);
8027 
8028   for (ElementCount TmpVF = Range.Start * 2;
8029        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8030     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8031       Range.End = TmpVF;
8032       break;
8033     }
8034 
8035   return PredicateAtRangeStart;
8036 }
8037 
8038 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8039 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8040 /// of VF's starting at a given VF and extending it as much as possible. Each
8041 /// vectorization decision can potentially shorten this sub-range during
8042 /// buildVPlan().
8043 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8044                                            ElementCount MaxVF) {
8045   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8046   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8047     VFRange SubRange = {VF, MaxVFPlusOne};
8048     VPlans.push_back(buildVPlan(SubRange));
8049     VF = SubRange.End;
8050   }
8051 }
8052 
8053 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8054                                          VPlanPtr &Plan) {
8055   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8056 
8057   // Look for cached value.
8058   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8059   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8060   if (ECEntryIt != EdgeMaskCache.end())
8061     return ECEntryIt->second;
8062 
8063   VPValue *SrcMask = createBlockInMask(Src, Plan);
8064 
8065   // The terminator has to be a branch inst!
8066   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8067   assert(BI && "Unexpected terminator found");
8068 
8069   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8070     return EdgeMaskCache[Edge] = SrcMask;
8071 
8072   // If source is an exiting block, we know the exit edge is dynamically dead
8073   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8074   // adding uses of an otherwise potentially dead instruction.
8075   if (OrigLoop->isLoopExiting(Src))
8076     return EdgeMaskCache[Edge] = SrcMask;
8077 
8078   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8079   assert(EdgeMask && "No Edge Mask found for condition");
8080 
8081   if (BI->getSuccessor(0) != Dst)
8082     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8083 
8084   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8085     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8086     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8087     // The select version does not introduce new UB if SrcMask is false and
8088     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8089     VPValue *False = Plan->getOrAddVPValue(
8090         ConstantInt::getFalse(BI->getCondition()->getType()));
8091     EdgeMask =
8092         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8093   }
8094 
8095   return EdgeMaskCache[Edge] = EdgeMask;
8096 }
8097 
8098 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8099   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8100 
8101   // Look for cached value.
8102   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8103   if (BCEntryIt != BlockMaskCache.end())
8104     return BCEntryIt->second;
8105 
8106   // All-one mask is modelled as no-mask following the convention for masked
8107   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8108   VPValue *BlockMask = nullptr;
8109 
8110   if (OrigLoop->getHeader() == BB) {
8111     if (!CM.blockNeedsPredicationForAnyReason(BB))
8112       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8113 
8114     // Introduce the early-exit compare IV <= BTC to form header block mask.
8115     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8116     // constructing the desired canonical IV in the header block as its first
8117     // non-phi instructions.
8118     assert(CM.foldTailByMasking() && "must fold the tail");
8119     VPBasicBlock *HeaderVPBB =
8120         Plan->getVectorLoopRegion()->getEntryBasicBlock();
8121     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8122     auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
8123     HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
8124 
8125     VPBuilder::InsertPointGuard Guard(Builder);
8126     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8127     if (CM.TTI.emitGetActiveLaneMask()) {
8128       VPValue *TC = Plan->getOrCreateTripCount();
8129       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC});
8130     } else {
8131       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8132       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8133     }
8134     return BlockMaskCache[BB] = BlockMask;
8135   }
8136 
8137   // This is the block mask. We OR all incoming edges.
8138   for (auto *Predecessor : predecessors(BB)) {
8139     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8140     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8141       return BlockMaskCache[BB] = EdgeMask;
8142 
8143     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8144       BlockMask = EdgeMask;
8145       continue;
8146     }
8147 
8148     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8149   }
8150 
8151   return BlockMaskCache[BB] = BlockMask;
8152 }
8153 
8154 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8155                                                 ArrayRef<VPValue *> Operands,
8156                                                 VFRange &Range,
8157                                                 VPlanPtr &Plan) {
8158   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8159          "Must be called with either a load or store");
8160 
8161   auto willWiden = [&](ElementCount VF) -> bool {
8162     if (VF.isScalar())
8163       return false;
8164     LoopVectorizationCostModel::InstWidening Decision =
8165         CM.getWideningDecision(I, VF);
8166     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8167            "CM decision should be taken at this point.");
8168     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8169       return true;
8170     if (CM.isScalarAfterVectorization(I, VF) ||
8171         CM.isProfitableToScalarize(I, VF))
8172       return false;
8173     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8174   };
8175 
8176   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8177     return nullptr;
8178 
8179   VPValue *Mask = nullptr;
8180   if (Legal->isMaskRequired(I))
8181     Mask = createBlockInMask(I->getParent(), Plan);
8182 
8183   // Determine if the pointer operand of the access is either consecutive or
8184   // reverse consecutive.
8185   LoopVectorizationCostModel::InstWidening Decision =
8186       CM.getWideningDecision(I, Range.Start);
8187   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8188   bool Consecutive =
8189       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8190 
8191   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8192     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8193                                               Consecutive, Reverse);
8194 
8195   StoreInst *Store = cast<StoreInst>(I);
8196   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8197                                             Mask, Consecutive, Reverse);
8198 }
8199 
8200 /// Creates a VPWidenIntOrFpInductionRecpipe for \p Phi. If needed, it will also
8201 /// insert a recipe to expand the step for the induction recipe.
8202 static VPWidenIntOrFpInductionRecipe *createWidenInductionRecipes(
8203     PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start,
8204     const InductionDescriptor &IndDesc, LoopVectorizationCostModel &CM,
8205     VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop, VFRange &Range) {
8206   // Returns true if an instruction \p I should be scalarized instead of
8207   // vectorized for the chosen vectorization factor.
8208   auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
8209     return CM.isScalarAfterVectorization(I, VF) ||
8210            CM.isProfitableToScalarize(I, VF);
8211   };
8212 
8213   bool NeedsScalarIV = LoopVectorizationPlanner::getDecisionAndClampRange(
8214       [&](ElementCount VF) {
8215         // Returns true if we should generate a scalar version of \p IV.
8216         if (ShouldScalarizeInstruction(PhiOrTrunc, VF))
8217           return true;
8218         auto isScalarInst = [&](User *U) -> bool {
8219           auto *I = cast<Instruction>(U);
8220           return OrigLoop.contains(I) && ShouldScalarizeInstruction(I, VF);
8221         };
8222         return any_of(PhiOrTrunc->users(), isScalarInst);
8223       },
8224       Range);
8225   bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
8226       [&](ElementCount VF) {
8227         return ShouldScalarizeInstruction(PhiOrTrunc, VF);
8228       },
8229       Range);
8230   assert(IndDesc.getStartValue() ==
8231          Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
8232   assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
8233          "step must be loop invariant");
8234 
8235   VPValue *Step =
8236       vputils::getOrCreateVPValueForSCEVExpr(Plan, IndDesc.getStep(), SE);
8237   if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8238     return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc, TruncI,
8239                                              NeedsScalarIV, !NeedsScalarIVOnly);
8240   }
8241   assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
8242   return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc,
8243                                            NeedsScalarIV, !NeedsScalarIVOnly);
8244 }
8245 
8246 VPRecipeBase *VPRecipeBuilder::tryToOptimizeInductionPHI(
8247     PHINode *Phi, ArrayRef<VPValue *> Operands, VPlan &Plan, VFRange &Range) {
8248 
8249   // Check if this is an integer or fp induction. If so, build the recipe that
8250   // produces its scalar and vector values.
8251   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
8252     return createWidenInductionRecipes(Phi, Phi, Operands[0], *II, CM, Plan,
8253                                        *PSE.getSE(), *OrigLoop, Range);
8254 
8255   // Check if this is pointer induction. If so, build the recipe for it.
8256   if (auto *II = Legal->getPointerInductionDescriptor(Phi))
8257     return new VPWidenPointerInductionRecipe(Phi, Operands[0], *II,
8258                                              *PSE.getSE());
8259   return nullptr;
8260 }
8261 
8262 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8263     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range, VPlan &Plan) {
8264   // Optimize the special case where the source is a constant integer
8265   // induction variable. Notice that we can only optimize the 'trunc' case
8266   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8267   // (c) other casts depend on pointer size.
8268 
8269   // Determine whether \p K is a truncation based on an induction variable that
8270   // can be optimized.
8271   auto isOptimizableIVTruncate =
8272       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8273     return [=](ElementCount VF) -> bool {
8274       return CM.isOptimizableIVTruncate(K, VF);
8275     };
8276   };
8277 
8278   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8279           isOptimizableIVTruncate(I), Range)) {
8280 
8281     auto *Phi = cast<PHINode>(I->getOperand(0));
8282     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8283     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8284     return createWidenInductionRecipes(Phi, I, Start, II, CM, Plan,
8285                                        *PSE.getSE(), *OrigLoop, Range);
8286   }
8287   return nullptr;
8288 }
8289 
8290 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8291                                                 ArrayRef<VPValue *> Operands,
8292                                                 VPlanPtr &Plan) {
8293   // If all incoming values are equal, the incoming VPValue can be used directly
8294   // instead of creating a new VPBlendRecipe.
8295   VPValue *FirstIncoming = Operands[0];
8296   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8297         return FirstIncoming == Inc;
8298       })) {
8299     return Operands[0];
8300   }
8301 
8302   unsigned NumIncoming = Phi->getNumIncomingValues();
8303   // For in-loop reductions, we do not need to create an additional select.
8304   VPValue *InLoopVal = nullptr;
8305   for (unsigned In = 0; In < NumIncoming; In++) {
8306     PHINode *PhiOp =
8307         dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
8308     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
8309       assert(!InLoopVal && "Found more than one in-loop reduction!");
8310       InLoopVal = Operands[In];
8311     }
8312   }
8313 
8314   assert((!InLoopVal || NumIncoming == 2) &&
8315          "Found an in-loop reduction for PHI with unexpected number of "
8316          "incoming values");
8317   if (InLoopVal)
8318     return Operands[Operands[0] == InLoopVal ? 1 : 0];
8319 
8320   // We know that all PHIs in non-header blocks are converted into selects, so
8321   // we don't have to worry about the insertion order and we can just use the
8322   // builder. At this point we generate the predication tree. There may be
8323   // duplications since this is a simple recursive scan, but future
8324   // optimizations will clean it up.
8325   SmallVector<VPValue *, 2> OperandsWithMask;
8326 
8327   for (unsigned In = 0; In < NumIncoming; In++) {
8328     VPValue *EdgeMask =
8329       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8330     assert((EdgeMask || NumIncoming == 1) &&
8331            "Multiple predecessors with one having a full mask");
8332     OperandsWithMask.push_back(Operands[In]);
8333     if (EdgeMask)
8334       OperandsWithMask.push_back(EdgeMask);
8335   }
8336   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8337 }
8338 
8339 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8340                                                    ArrayRef<VPValue *> Operands,
8341                                                    VFRange &Range) const {
8342 
8343   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8344       [this, CI](ElementCount VF) {
8345         return CM.isScalarWithPredication(CI, VF);
8346       },
8347       Range);
8348 
8349   if (IsPredicated)
8350     return nullptr;
8351 
8352   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8353   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8354              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8355              ID == Intrinsic::pseudoprobe ||
8356              ID == Intrinsic::experimental_noalias_scope_decl))
8357     return nullptr;
8358 
8359   auto willWiden = [&](ElementCount VF) -> bool {
8360     if (VF.isScalar())
8361        return false;
8362     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8363     // The following case may be scalarized depending on the VF.
8364     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8365     // version of the instruction.
8366     // Is it beneficial to perform intrinsic call compared to lib call?
8367     bool NeedToScalarize = false;
8368     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8369     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8370     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8371     return UseVectorIntrinsic || !NeedToScalarize;
8372   };
8373 
8374   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8375     return nullptr;
8376 
8377   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8378   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8379 }
8380 
8381 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8382   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8383          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8384   // Instruction should be widened, unless it is scalar after vectorization,
8385   // scalarization is profitable or it is predicated.
8386   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8387     return CM.isScalarAfterVectorization(I, VF) ||
8388            CM.isProfitableToScalarize(I, VF) ||
8389            CM.isScalarWithPredication(I, VF);
8390   };
8391   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8392                                                              Range);
8393 }
8394 
8395 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8396                                            ArrayRef<VPValue *> Operands) const {
8397   auto IsVectorizableOpcode = [](unsigned Opcode) {
8398     switch (Opcode) {
8399     case Instruction::Add:
8400     case Instruction::And:
8401     case Instruction::AShr:
8402     case Instruction::BitCast:
8403     case Instruction::FAdd:
8404     case Instruction::FCmp:
8405     case Instruction::FDiv:
8406     case Instruction::FMul:
8407     case Instruction::FNeg:
8408     case Instruction::FPExt:
8409     case Instruction::FPToSI:
8410     case Instruction::FPToUI:
8411     case Instruction::FPTrunc:
8412     case Instruction::FRem:
8413     case Instruction::FSub:
8414     case Instruction::ICmp:
8415     case Instruction::IntToPtr:
8416     case Instruction::LShr:
8417     case Instruction::Mul:
8418     case Instruction::Or:
8419     case Instruction::PtrToInt:
8420     case Instruction::SDiv:
8421     case Instruction::Select:
8422     case Instruction::SExt:
8423     case Instruction::Shl:
8424     case Instruction::SIToFP:
8425     case Instruction::SRem:
8426     case Instruction::Sub:
8427     case Instruction::Trunc:
8428     case Instruction::UDiv:
8429     case Instruction::UIToFP:
8430     case Instruction::URem:
8431     case Instruction::Xor:
8432     case Instruction::ZExt:
8433       return true;
8434     }
8435     return false;
8436   };
8437 
8438   if (!IsVectorizableOpcode(I->getOpcode()))
8439     return nullptr;
8440 
8441   // Success: widen this instruction.
8442   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8443 }
8444 
8445 void VPRecipeBuilder::fixHeaderPhis() {
8446   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8447   for (VPHeaderPHIRecipe *R : PhisToFix) {
8448     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8449     VPRecipeBase *IncR =
8450         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8451     R->addOperand(IncR->getVPSingleValue());
8452   }
8453 }
8454 
8455 VPBasicBlock *VPRecipeBuilder::handleReplication(
8456     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8457     VPlanPtr &Plan) {
8458   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8459       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8460       Range);
8461 
8462   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8463       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF, IsUniform); },
8464       Range);
8465 
8466   // Even if the instruction is not marked as uniform, there are certain
8467   // intrinsic calls that can be effectively treated as such, so we check for
8468   // them here. Conservatively, we only do this for scalable vectors, since
8469   // for fixed-width VFs we can always fall back on full scalarization.
8470   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8471     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8472     case Intrinsic::assume:
8473     case Intrinsic::lifetime_start:
8474     case Intrinsic::lifetime_end:
8475       // For scalable vectors if one of the operands is variant then we still
8476       // want to mark as uniform, which will generate one instruction for just
8477       // the first lane of the vector. We can't scalarize the call in the same
8478       // way as for fixed-width vectors because we don't know how many lanes
8479       // there are.
8480       //
8481       // The reasons for doing it this way for scalable vectors are:
8482       //   1. For the assume intrinsic generating the instruction for the first
8483       //      lane is still be better than not generating any at all. For
8484       //      example, the input may be a splat across all lanes.
8485       //   2. For the lifetime start/end intrinsics the pointer operand only
8486       //      does anything useful when the input comes from a stack object,
8487       //      which suggests it should always be uniform. For non-stack objects
8488       //      the effect is to poison the object, which still allows us to
8489       //      remove the call.
8490       IsUniform = true;
8491       break;
8492     default:
8493       break;
8494     }
8495   }
8496 
8497   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8498                                        IsUniform, IsPredicated);
8499   setRecipe(I, Recipe);
8500   Plan->addVPValue(I, Recipe);
8501 
8502   // Find if I uses a predicated instruction. If so, it will use its scalar
8503   // value. Avoid hoisting the insert-element which packs the scalar value into
8504   // a vector value, as that happens iff all users use the vector value.
8505   for (VPValue *Op : Recipe->operands()) {
8506     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8507     if (!PredR)
8508       continue;
8509     auto *RepR =
8510         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8511     assert(RepR->isPredicated() &&
8512            "expected Replicate recipe to be predicated");
8513     RepR->setAlsoPack(false);
8514   }
8515 
8516   // Finalize the recipe for Instr, first if it is not predicated.
8517   if (!IsPredicated) {
8518     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8519     VPBB->appendRecipe(Recipe);
8520     return VPBB;
8521   }
8522   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8523 
8524   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8525   assert(SingleSucc && "VPBB must have a single successor when handling "
8526                        "predicated replication.");
8527   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8528   // Record predicated instructions for above packing optimizations.
8529   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8530   VPBlockUtils::insertBlockAfter(Region, VPBB);
8531   auto *RegSucc = new VPBasicBlock();
8532   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8533   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8534   return RegSucc;
8535 }
8536 
8537 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8538                                                       VPRecipeBase *PredRecipe,
8539                                                       VPlanPtr &Plan) {
8540   // Instructions marked for predication are replicated and placed under an
8541   // if-then construct to prevent side-effects.
8542 
8543   // Generate recipes to compute the block mask for this region.
8544   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8545 
8546   // Build the triangular if-then region.
8547   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8548   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8549   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8550   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8551   auto *PHIRecipe = Instr->getType()->isVoidTy()
8552                         ? nullptr
8553                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8554   if (PHIRecipe) {
8555     Plan->removeVPValueFor(Instr);
8556     Plan->addVPValue(Instr, PHIRecipe);
8557   }
8558   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8559   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8560   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8561 
8562   // Note: first set Entry as region entry and then connect successors starting
8563   // from it in order, to propagate the "parent" of each VPBasicBlock.
8564   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8565   VPBlockUtils::connectBlocks(Pred, Exit);
8566 
8567   return Region;
8568 }
8569 
8570 VPRecipeOrVPValueTy
8571 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8572                                         ArrayRef<VPValue *> Operands,
8573                                         VFRange &Range, VPlanPtr &Plan) {
8574   // First, check for specific widening recipes that deal with calls, memory
8575   // operations, inductions and Phi nodes.
8576   if (auto *CI = dyn_cast<CallInst>(Instr))
8577     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8578 
8579   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8580     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8581 
8582   VPRecipeBase *Recipe;
8583   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8584     if (Phi->getParent() != OrigLoop->getHeader())
8585       return tryToBlend(Phi, Operands, Plan);
8586     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, *Plan, Range)))
8587       return toVPRecipeResult(Recipe);
8588 
8589     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8590     assert((Legal->isReductionVariable(Phi) ||
8591             Legal->isFirstOrderRecurrence(Phi)) &&
8592            "can only widen reductions and first-order recurrences here");
8593     VPValue *StartV = Operands[0];
8594     if (Legal->isReductionVariable(Phi)) {
8595       const RecurrenceDescriptor &RdxDesc =
8596           Legal->getReductionVars().find(Phi)->second;
8597       assert(RdxDesc.getRecurrenceStartValue() ==
8598              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8599       PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8600                                            CM.isInLoopReduction(Phi),
8601                                            CM.useOrderedReductions(RdxDesc));
8602     } else {
8603       PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8604     }
8605 
8606       // Record the incoming value from the backedge, so we can add the incoming
8607       // value from the backedge after all recipes have been created.
8608       recordRecipeOf(cast<Instruction>(
8609           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8610       PhisToFix.push_back(PhiRecipe);
8611       return toVPRecipeResult(PhiRecipe);
8612   }
8613 
8614   if (isa<TruncInst>(Instr) &&
8615       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8616                                                Range, *Plan)))
8617     return toVPRecipeResult(Recipe);
8618 
8619   if (!shouldWiden(Instr, Range))
8620     return nullptr;
8621 
8622   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8623     return toVPRecipeResult(new VPWidenGEPRecipe(
8624         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8625 
8626   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8627     bool InvariantCond =
8628         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8629     return toVPRecipeResult(new VPWidenSelectRecipe(
8630         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8631   }
8632 
8633   return toVPRecipeResult(tryToWiden(Instr, Operands));
8634 }
8635 
8636 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8637                                                         ElementCount MaxVF) {
8638   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8639 
8640   // Collect instructions from the original loop that will become trivially dead
8641   // in the vectorized loop. We don't need to vectorize these instructions. For
8642   // example, original induction update instructions can become dead because we
8643   // separately emit induction "steps" when generating code for the new loop.
8644   // Similarly, we create a new latch condition when setting up the structure
8645   // of the new loop, so the old one can become dead.
8646   SmallPtrSet<Instruction *, 4> DeadInstructions;
8647   collectTriviallyDeadInstructions(DeadInstructions);
8648 
8649   // Add assume instructions we need to drop to DeadInstructions, to prevent
8650   // them from being added to the VPlan.
8651   // TODO: We only need to drop assumes in blocks that get flattend. If the
8652   // control flow is preserved, we should keep them.
8653   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8654   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8655 
8656   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8657   // Dead instructions do not need sinking. Remove them from SinkAfter.
8658   for (Instruction *I : DeadInstructions)
8659     SinkAfter.erase(I);
8660 
8661   // Cannot sink instructions after dead instructions (there won't be any
8662   // recipes for them). Instead, find the first non-dead previous instruction.
8663   for (auto &P : Legal->getSinkAfter()) {
8664     Instruction *SinkTarget = P.second;
8665     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8666     (void)FirstInst;
8667     while (DeadInstructions.contains(SinkTarget)) {
8668       assert(
8669           SinkTarget != FirstInst &&
8670           "Must find a live instruction (at least the one feeding the "
8671           "first-order recurrence PHI) before reaching beginning of the block");
8672       SinkTarget = SinkTarget->getPrevNode();
8673       assert(SinkTarget != P.first &&
8674              "sink source equals target, no sinking required");
8675     }
8676     P.second = SinkTarget;
8677   }
8678 
8679   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8680   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8681     VFRange SubRange = {VF, MaxVFPlusOne};
8682     VPlans.push_back(
8683         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8684     VF = SubRange.End;
8685   }
8686 }
8687 
8688 // Add a VPCanonicalIVPHIRecipe starting at 0 to the header, a
8689 // CanonicalIVIncrement{NUW} VPInstruction to increment it by VF * UF and a
8690 // BranchOnCount VPInstruction to the latch.
8691 static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
8692                                   bool HasNUW, bool IsVPlanNative) {
8693   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8694   auto *StartV = Plan.getOrAddVPValue(StartIdx);
8695 
8696   auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
8697   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
8698   VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
8699   Header->insert(CanonicalIVPHI, Header->begin());
8700 
8701   auto *CanonicalIVIncrement =
8702       new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
8703                                : VPInstruction::CanonicalIVIncrement,
8704                         {CanonicalIVPHI}, DL);
8705   CanonicalIVPHI->addOperand(CanonicalIVIncrement);
8706 
8707   VPBasicBlock *EB = TopRegion->getExitBasicBlock();
8708   if (IsVPlanNative)
8709     EB->setCondBit(nullptr);
8710   EB->appendRecipe(CanonicalIVIncrement);
8711 
8712   auto *BranchOnCount =
8713       new VPInstruction(VPInstruction::BranchOnCount,
8714                         {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
8715   EB->appendRecipe(BranchOnCount);
8716 }
8717 
8718 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8719     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8720     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8721 
8722   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8723 
8724   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8725 
8726   // ---------------------------------------------------------------------------
8727   // Pre-construction: record ingredients whose recipes we'll need to further
8728   // process after constructing the initial VPlan.
8729   // ---------------------------------------------------------------------------
8730 
8731   // Mark instructions we'll need to sink later and their targets as
8732   // ingredients whose recipe we'll need to record.
8733   for (auto &Entry : SinkAfter) {
8734     RecipeBuilder.recordRecipeOf(Entry.first);
8735     RecipeBuilder.recordRecipeOf(Entry.second);
8736   }
8737   for (auto &Reduction : CM.getInLoopReductionChains()) {
8738     PHINode *Phi = Reduction.first;
8739     RecurKind Kind =
8740         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8741     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8742 
8743     RecipeBuilder.recordRecipeOf(Phi);
8744     for (auto &R : ReductionOperations) {
8745       RecipeBuilder.recordRecipeOf(R);
8746       // For min/max reductions, where we have a pair of icmp/select, we also
8747       // need to record the ICmp recipe, so it can be removed later.
8748       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
8749              "Only min/max recurrences allowed for inloop reductions");
8750       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8751         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8752     }
8753   }
8754 
8755   // For each interleave group which is relevant for this (possibly trimmed)
8756   // Range, add it to the set of groups to be later applied to the VPlan and add
8757   // placeholders for its members' Recipes which we'll be replacing with a
8758   // single VPInterleaveRecipe.
8759   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8760     auto applyIG = [IG, this](ElementCount VF) -> bool {
8761       return (VF.isVector() && // Query is illegal for VF == 1
8762               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8763                   LoopVectorizationCostModel::CM_Interleave);
8764     };
8765     if (!getDecisionAndClampRange(applyIG, Range))
8766       continue;
8767     InterleaveGroups.insert(IG);
8768     for (unsigned i = 0; i < IG->getFactor(); i++)
8769       if (Instruction *Member = IG->getMember(i))
8770         RecipeBuilder.recordRecipeOf(Member);
8771   };
8772 
8773   // ---------------------------------------------------------------------------
8774   // Build initial VPlan: Scan the body of the loop in a topological order to
8775   // visit each basic block after having visited its predecessor basic blocks.
8776   // ---------------------------------------------------------------------------
8777 
8778   // Create initial VPlan skeleton, starting with a block for the pre-header,
8779   // followed by a region for the vector loop, followed by the middle block. The
8780   // skeleton vector loop region contains a header and latch block.
8781   VPBasicBlock *Preheader = new VPBasicBlock("vector.ph");
8782   auto Plan = std::make_unique<VPlan>(Preheader);
8783 
8784   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
8785   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
8786   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
8787   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
8788   VPBlockUtils::insertBlockAfter(TopRegion, Preheader);
8789   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
8790   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
8791 
8792   Instruction *DLInst =
8793       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
8794   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
8795                         DLInst ? DLInst->getDebugLoc() : DebugLoc(),
8796                         !CM.foldTailByMasking(), false);
8797 
8798   // Scan the body of the loop in a topological order to visit each basic block
8799   // after having visited its predecessor basic blocks.
8800   LoopBlocksDFS DFS(OrigLoop);
8801   DFS.perform(LI);
8802 
8803   VPBasicBlock *VPBB = HeaderVPBB;
8804   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
8805   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8806     // Relevant instructions from basic block BB will be grouped into VPRecipe
8807     // ingredients and fill a new VPBasicBlock.
8808     unsigned VPBBsForBB = 0;
8809     if (VPBB != HeaderVPBB)
8810       VPBB->setName(BB->getName());
8811     Builder.setInsertPoint(VPBB);
8812 
8813     // Introduce each ingredient into VPlan.
8814     // TODO: Model and preserve debug intrinsics in VPlan.
8815     for (Instruction &I : BB->instructionsWithoutDebug()) {
8816       Instruction *Instr = &I;
8817 
8818       // First filter out irrelevant instructions, to ensure no recipes are
8819       // built for them.
8820       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8821         continue;
8822 
8823       SmallVector<VPValue *, 4> Operands;
8824       auto *Phi = dyn_cast<PHINode>(Instr);
8825       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8826         Operands.push_back(Plan->getOrAddVPValue(
8827             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8828       } else {
8829         auto OpRange = Plan->mapToVPValues(Instr->operands());
8830         Operands = {OpRange.begin(), OpRange.end()};
8831       }
8832       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8833               Instr, Operands, Range, Plan)) {
8834         // If Instr can be simplified to an existing VPValue, use it.
8835         if (RecipeOrValue.is<VPValue *>()) {
8836           auto *VPV = RecipeOrValue.get<VPValue *>();
8837           Plan->addVPValue(Instr, VPV);
8838           // If the re-used value is a recipe, register the recipe for the
8839           // instruction, in case the recipe for Instr needs to be recorded.
8840           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
8841             RecipeBuilder.setRecipe(Instr, R);
8842           continue;
8843         }
8844         // Otherwise, add the new recipe.
8845         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8846         for (auto *Def : Recipe->definedValues()) {
8847           auto *UV = Def->getUnderlyingValue();
8848           Plan->addVPValue(UV, Def);
8849         }
8850 
8851         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
8852             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
8853           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
8854           // of the header block. That can happen for truncates of induction
8855           // variables. Those recipes are moved to the phi section of the header
8856           // block after applying SinkAfter, which relies on the original
8857           // position of the trunc.
8858           assert(isa<TruncInst>(Instr));
8859           InductionsToMove.push_back(
8860               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
8861         }
8862         RecipeBuilder.setRecipe(Instr, Recipe);
8863         VPBB->appendRecipe(Recipe);
8864         continue;
8865       }
8866 
8867       // Invariant stores inside loop will be deleted and a single store
8868       // with the final reduction value will be added to the exit block
8869       StoreInst *SI;
8870       if ((SI = dyn_cast<StoreInst>(&I)) &&
8871           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
8872         continue;
8873 
8874       // Otherwise, if all widening options failed, Instruction is to be
8875       // replicated. This may create a successor for VPBB.
8876       VPBasicBlock *NextVPBB =
8877           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8878       if (NextVPBB != VPBB) {
8879         VPBB = NextVPBB;
8880         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8881                                     : "");
8882       }
8883     }
8884 
8885     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
8886     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
8887   }
8888 
8889   HeaderVPBB->setName("vector.body");
8890 
8891   // Fold the last, empty block into its predecessor.
8892   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
8893   assert(VPBB && "expected to fold last (empty) block");
8894   // After here, VPBB should not be used.
8895   VPBB = nullptr;
8896 
8897   assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8898          !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8899          "entry block must be set to a VPRegionBlock having a non-empty entry "
8900          "VPBasicBlock");
8901   RecipeBuilder.fixHeaderPhis();
8902 
8903   // ---------------------------------------------------------------------------
8904   // Transform initial VPlan: Apply previously taken decisions, in order, to
8905   // bring the VPlan to its final state.
8906   // ---------------------------------------------------------------------------
8907 
8908   // Apply Sink-After legal constraints.
8909   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
8910     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
8911     if (Region && Region->isReplicator()) {
8912       assert(Region->getNumSuccessors() == 1 &&
8913              Region->getNumPredecessors() == 1 && "Expected SESE region!");
8914       assert(R->getParent()->size() == 1 &&
8915              "A recipe in an original replicator region must be the only "
8916              "recipe in its block");
8917       return Region;
8918     }
8919     return nullptr;
8920   };
8921   for (auto &Entry : SinkAfter) {
8922     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8923     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8924 
8925     auto *TargetRegion = GetReplicateRegion(Target);
8926     auto *SinkRegion = GetReplicateRegion(Sink);
8927     if (!SinkRegion) {
8928       // If the sink source is not a replicate region, sink the recipe directly.
8929       if (TargetRegion) {
8930         // The target is in a replication region, make sure to move Sink to
8931         // the block after it, not into the replication region itself.
8932         VPBasicBlock *NextBlock =
8933             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
8934         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8935       } else
8936         Sink->moveAfter(Target);
8937       continue;
8938     }
8939 
8940     // The sink source is in a replicate region. Unhook the region from the CFG.
8941     auto *SinkPred = SinkRegion->getSinglePredecessor();
8942     auto *SinkSucc = SinkRegion->getSingleSuccessor();
8943     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
8944     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
8945     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
8946 
8947     if (TargetRegion) {
8948       // The target recipe is also in a replicate region, move the sink region
8949       // after the target region.
8950       auto *TargetSucc = TargetRegion->getSingleSuccessor();
8951       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
8952       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
8953       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
8954     } else {
8955       // The sink source is in a replicate region, we need to move the whole
8956       // replicate region, which should only contain a single recipe in the
8957       // main block.
8958       auto *SplitBlock =
8959           Target->getParent()->splitAt(std::next(Target->getIterator()));
8960 
8961       auto *SplitPred = SplitBlock->getSinglePredecessor();
8962 
8963       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
8964       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
8965       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
8966     }
8967   }
8968 
8969   VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
8970   VPlanTransforms::removeRedundantInductionCasts(*Plan);
8971 
8972   // Now that sink-after is done, move induction recipes for optimized truncates
8973   // to the phi section of the header block.
8974   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
8975     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8976 
8977   // Adjust the recipes for any inloop reductions.
8978   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExit()), Plan,
8979                              RecipeBuilder, Range.Start);
8980 
8981   // Introduce a recipe to combine the incoming and previous values of a
8982   // first-order recurrence.
8983   for (VPRecipeBase &R :
8984        Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8985     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
8986     if (!RecurPhi)
8987       continue;
8988 
8989     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
8990     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
8991     auto *Region = GetReplicateRegion(PrevRecipe);
8992     if (Region)
8993       InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
8994     if (Region || PrevRecipe->isPhi())
8995       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
8996     else
8997       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
8998 
8999     auto *RecurSplice = cast<VPInstruction>(
9000         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
9001                              {RecurPhi, RecurPhi->getBackedgeValue()}));
9002 
9003     RecurPhi->replaceAllUsesWith(RecurSplice);
9004     // Set the first operand of RecurSplice to RecurPhi again, after replacing
9005     // all users.
9006     RecurSplice->setOperand(0, RecurPhi);
9007   }
9008 
9009   // Interleave memory: for each Interleave Group we marked earlier as relevant
9010   // for this VPlan, replace the Recipes widening its memory instructions with a
9011   // single VPInterleaveRecipe at its insertion point.
9012   for (auto IG : InterleaveGroups) {
9013     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9014         RecipeBuilder.getRecipe(IG->getInsertPos()));
9015     SmallVector<VPValue *, 4> StoredValues;
9016     for (unsigned i = 0; i < IG->getFactor(); ++i)
9017       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9018         auto *StoreR =
9019             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9020         StoredValues.push_back(StoreR->getStoredValue());
9021       }
9022 
9023     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9024                                         Recipe->getMask());
9025     VPIG->insertBefore(Recipe);
9026     unsigned J = 0;
9027     for (unsigned i = 0; i < IG->getFactor(); ++i)
9028       if (Instruction *Member = IG->getMember(i)) {
9029         if (!Member->getType()->isVoidTy()) {
9030           VPValue *OriginalV = Plan->getVPValue(Member);
9031           Plan->removeVPValueFor(Member);
9032           Plan->addVPValue(Member, VPIG->getVPValue(J));
9033           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9034           J++;
9035         }
9036         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9037       }
9038   }
9039 
9040   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9041   // in ways that accessing values using original IR values is incorrect.
9042   Plan->disableValue2VPValue();
9043 
9044   VPlanTransforms::optimizeInductions(*Plan, *PSE.getSE());
9045   VPlanTransforms::sinkScalarOperands(*Plan);
9046   VPlanTransforms::mergeReplicateRegions(*Plan);
9047   VPlanTransforms::removeDeadRecipes(*Plan, *OrigLoop);
9048   VPlanTransforms::removeRedundantExpandSCEVRecipes(*Plan);
9049 
9050   std::string PlanName;
9051   raw_string_ostream RSO(PlanName);
9052   ElementCount VF = Range.Start;
9053   Plan->addVF(VF);
9054   RSO << "Initial VPlan for VF={" << VF;
9055   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9056     Plan->addVF(VF);
9057     RSO << "," << VF;
9058   }
9059   RSO << "},UF>=1";
9060   RSO.flush();
9061   Plan->setName(PlanName);
9062 
9063   // Fold Exit block into its predecessor if possible.
9064   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9065   // VPBasicBlock as exit.
9066   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExit());
9067 
9068   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9069   return Plan;
9070 }
9071 
9072 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9073   // Outer loop handling: They may require CFG and instruction level
9074   // transformations before even evaluating whether vectorization is profitable.
9075   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9076   // the vectorization pipeline.
9077   assert(!OrigLoop->isInnermost());
9078   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9079 
9080   // Create new empty VPlan
9081   auto Plan = std::make_unique<VPlan>();
9082 
9083   // Build hierarchical CFG
9084   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9085   HCFGBuilder.buildHierarchicalCFG();
9086 
9087   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9088        VF *= 2)
9089     Plan->addVF(VF);
9090 
9091   if (EnableVPlanPredication) {
9092     VPlanPredicator VPP(*Plan);
9093     VPP.predicate();
9094 
9095     // Avoid running transformation to recipes until masked code generation in
9096     // VPlan-native path is in place.
9097     return Plan;
9098   }
9099 
9100   SmallPtrSet<Instruction *, 1> DeadInstructions;
9101   VPlanTransforms::VPInstructionsToVPRecipes(
9102       OrigLoop, Plan,
9103       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9104       DeadInstructions, *PSE.getSE());
9105 
9106   // Update plan to be compatible with the inner loop vectorizer for
9107   // code-generation.
9108   VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
9109   VPBasicBlock *Preheader = LoopRegion->getEntryBasicBlock();
9110   VPBasicBlock *Exit = LoopRegion->getExitBasicBlock();
9111   VPBlockBase *Latch = Exit->getSinglePredecessor();
9112   VPBlockBase *Header = Preheader->getSingleSuccessor();
9113 
9114   // 1. Move preheader block out of main vector loop.
9115   Preheader->setParent(LoopRegion->getParent());
9116   VPBlockUtils::disconnectBlocks(Preheader, Header);
9117   VPBlockUtils::connectBlocks(Preheader, LoopRegion);
9118   Plan->setEntry(Preheader);
9119 
9120   // 2. Disconnect backedge and exit block.
9121   VPBlockUtils::disconnectBlocks(Latch, Header);
9122   VPBlockUtils::disconnectBlocks(Latch, Exit);
9123 
9124   // 3. Update entry and exit of main vector loop region.
9125   LoopRegion->setEntry(Header);
9126   LoopRegion->setExit(Latch);
9127 
9128   // 4. Remove exit block.
9129   delete Exit;
9130 
9131   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
9132                         true, true);
9133   return Plan;
9134 }
9135 
9136 // Adjust the recipes for reductions. For in-loop reductions the chain of
9137 // instructions leading from the loop exit instr to the phi need to be converted
9138 // to reductions, with one operand being vector and the other being the scalar
9139 // reduction chain. For other reductions, a select is introduced between the phi
9140 // and live-out recipes when folding the tail.
9141 void LoopVectorizationPlanner::adjustRecipesForReductions(
9142     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9143     ElementCount MinVF) {
9144   for (auto &Reduction : CM.getInLoopReductionChains()) {
9145     PHINode *Phi = Reduction.first;
9146     const RecurrenceDescriptor &RdxDesc =
9147         Legal->getReductionVars().find(Phi)->second;
9148     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9149 
9150     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9151       continue;
9152 
9153     // ReductionOperations are orders top-down from the phi's use to the
9154     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9155     // which of the two operands will remain scalar and which will be reduced.
9156     // For minmax the chain will be the select instructions.
9157     Instruction *Chain = Phi;
9158     for (Instruction *R : ReductionOperations) {
9159       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9160       RecurKind Kind = RdxDesc.getRecurrenceKind();
9161 
9162       VPValue *ChainOp = Plan->getVPValue(Chain);
9163       unsigned FirstOpId;
9164       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9165              "Only min/max recurrences allowed for inloop reductions");
9166       // Recognize a call to the llvm.fmuladd intrinsic.
9167       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9168       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9169              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9170       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9171         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9172                "Expected to replace a VPWidenSelectSC");
9173         FirstOpId = 1;
9174       } else {
9175         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9176                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9177                "Expected to replace a VPWidenSC");
9178         FirstOpId = 0;
9179       }
9180       unsigned VecOpId =
9181           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9182       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9183 
9184       auto *CondOp = CM.blockNeedsPredicationForAnyReason(R->getParent())
9185                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9186                          : nullptr;
9187 
9188       if (IsFMulAdd) {
9189         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9190         // need to create an fmul recipe to use as the vector operand for the
9191         // fadd reduction.
9192         VPInstruction *FMulRecipe = new VPInstruction(
9193             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9194         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9195         WidenRecipe->getParent()->insert(FMulRecipe,
9196                                          WidenRecipe->getIterator());
9197         VecOp = FMulRecipe;
9198       }
9199       VPReductionRecipe *RedRecipe =
9200           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9201       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9202       Plan->removeVPValueFor(R);
9203       Plan->addVPValue(R, RedRecipe);
9204       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9205       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9206       WidenRecipe->eraseFromParent();
9207 
9208       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9209         VPRecipeBase *CompareRecipe =
9210             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9211         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9212                "Expected to replace a VPWidenSC");
9213         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9214                "Expected no remaining users");
9215         CompareRecipe->eraseFromParent();
9216       }
9217       Chain = R;
9218     }
9219   }
9220 
9221   // If tail is folded by masking, introduce selects between the phi
9222   // and the live-out instruction of each reduction, at the beginning of the
9223   // dedicated latch block.
9224   if (CM.foldTailByMasking()) {
9225     Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
9226     for (VPRecipeBase &R :
9227          Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9228       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9229       if (!PhiR || PhiR->isInLoop())
9230         continue;
9231       VPValue *Cond =
9232           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9233       VPValue *Red = PhiR->getBackedgeValue();
9234       assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
9235              "reduction recipe must be defined before latch");
9236       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9237     }
9238   }
9239 }
9240 
9241 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9242 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9243                                VPSlotTracker &SlotTracker) const {
9244   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9245   IG->getInsertPos()->printAsOperand(O, false);
9246   O << ", ";
9247   getAddr()->printAsOperand(O, SlotTracker);
9248   VPValue *Mask = getMask();
9249   if (Mask) {
9250     O << ", ";
9251     Mask->printAsOperand(O, SlotTracker);
9252   }
9253 
9254   unsigned OpIdx = 0;
9255   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9256     if (!IG->getMember(i))
9257       continue;
9258     if (getNumStoreOperands() > 0) {
9259       O << "\n" << Indent << "  store ";
9260       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9261       O << " to index " << i;
9262     } else {
9263       O << "\n" << Indent << "  ";
9264       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9265       O << " = load from index " << i;
9266     }
9267     ++OpIdx;
9268   }
9269 }
9270 #endif
9271 
9272 void VPWidenCallRecipe::execute(VPTransformState &State) {
9273   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9274                                   *this, State);
9275 }
9276 
9277 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9278   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9279   State.ILV->setDebugLocFromInst(&I);
9280 
9281   // The condition can be loop invariant  but still defined inside the
9282   // loop. This means that we can't just use the original 'cond' value.
9283   // We have to take the 'vectorized' value and pick the first lane.
9284   // Instcombine will make this a no-op.
9285   auto *InvarCond =
9286       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9287 
9288   for (unsigned Part = 0; Part < State.UF; ++Part) {
9289     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9290     Value *Op0 = State.get(getOperand(1), Part);
9291     Value *Op1 = State.get(getOperand(2), Part);
9292     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9293     State.set(this, Sel, Part);
9294     State.ILV->addMetadata(Sel, &I);
9295   }
9296 }
9297 
9298 void VPWidenRecipe::execute(VPTransformState &State) {
9299   auto &I = *cast<Instruction>(getUnderlyingValue());
9300   auto &Builder = State.Builder;
9301   switch (I.getOpcode()) {
9302   case Instruction::Call:
9303   case Instruction::Br:
9304   case Instruction::PHI:
9305   case Instruction::GetElementPtr:
9306   case Instruction::Select:
9307     llvm_unreachable("This instruction is handled by a different recipe.");
9308   case Instruction::UDiv:
9309   case Instruction::SDiv:
9310   case Instruction::SRem:
9311   case Instruction::URem:
9312   case Instruction::Add:
9313   case Instruction::FAdd:
9314   case Instruction::Sub:
9315   case Instruction::FSub:
9316   case Instruction::FNeg:
9317   case Instruction::Mul:
9318   case Instruction::FMul:
9319   case Instruction::FDiv:
9320   case Instruction::FRem:
9321   case Instruction::Shl:
9322   case Instruction::LShr:
9323   case Instruction::AShr:
9324   case Instruction::And:
9325   case Instruction::Or:
9326   case Instruction::Xor: {
9327     // Just widen unops and binops.
9328     State.ILV->setDebugLocFromInst(&I);
9329 
9330     for (unsigned Part = 0; Part < State.UF; ++Part) {
9331       SmallVector<Value *, 2> Ops;
9332       for (VPValue *VPOp : operands())
9333         Ops.push_back(State.get(VPOp, Part));
9334 
9335       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9336 
9337       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9338         VecOp->copyIRFlags(&I);
9339 
9340         // If the instruction is vectorized and was in a basic block that needed
9341         // predication, we can't propagate poison-generating flags (nuw/nsw,
9342         // exact, etc.). The control flow has been linearized and the
9343         // instruction is no longer guarded by the predicate, which could make
9344         // the flag properties to no longer hold.
9345         if (State.MayGeneratePoisonRecipes.contains(this))
9346           VecOp->dropPoisonGeneratingFlags();
9347       }
9348 
9349       // Use this vector value for all users of the original instruction.
9350       State.set(this, V, Part);
9351       State.ILV->addMetadata(V, &I);
9352     }
9353 
9354     break;
9355   }
9356   case Instruction::ICmp:
9357   case Instruction::FCmp: {
9358     // Widen compares. Generate vector compares.
9359     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9360     auto *Cmp = cast<CmpInst>(&I);
9361     State.ILV->setDebugLocFromInst(Cmp);
9362     for (unsigned Part = 0; Part < State.UF; ++Part) {
9363       Value *A = State.get(getOperand(0), Part);
9364       Value *B = State.get(getOperand(1), Part);
9365       Value *C = nullptr;
9366       if (FCmp) {
9367         // Propagate fast math flags.
9368         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9369         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9370         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9371       } else {
9372         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9373       }
9374       State.set(this, C, Part);
9375       State.ILV->addMetadata(C, &I);
9376     }
9377 
9378     break;
9379   }
9380 
9381   case Instruction::ZExt:
9382   case Instruction::SExt:
9383   case Instruction::FPToUI:
9384   case Instruction::FPToSI:
9385   case Instruction::FPExt:
9386   case Instruction::PtrToInt:
9387   case Instruction::IntToPtr:
9388   case Instruction::SIToFP:
9389   case Instruction::UIToFP:
9390   case Instruction::Trunc:
9391   case Instruction::FPTrunc:
9392   case Instruction::BitCast: {
9393     auto *CI = cast<CastInst>(&I);
9394     State.ILV->setDebugLocFromInst(CI);
9395 
9396     /// Vectorize casts.
9397     Type *DestTy = (State.VF.isScalar())
9398                        ? CI->getType()
9399                        : VectorType::get(CI->getType(), State.VF);
9400 
9401     for (unsigned Part = 0; Part < State.UF; ++Part) {
9402       Value *A = State.get(getOperand(0), Part);
9403       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9404       State.set(this, Cast, Part);
9405       State.ILV->addMetadata(Cast, &I);
9406     }
9407     break;
9408   }
9409   default:
9410     // This instruction is not vectorized by simple widening.
9411     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9412     llvm_unreachable("Unhandled instruction!");
9413   } // end of switch.
9414 }
9415 
9416 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9417   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9418   // Construct a vector GEP by widening the operands of the scalar GEP as
9419   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9420   // results in a vector of pointers when at least one operand of the GEP
9421   // is vector-typed. Thus, to keep the representation compact, we only use
9422   // vector-typed operands for loop-varying values.
9423 
9424   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9425     // If we are vectorizing, but the GEP has only loop-invariant operands,
9426     // the GEP we build (by only using vector-typed operands for
9427     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9428     // produce a vector of pointers, we need to either arbitrarily pick an
9429     // operand to broadcast, or broadcast a clone of the original GEP.
9430     // Here, we broadcast a clone of the original.
9431     //
9432     // TODO: If at some point we decide to scalarize instructions having
9433     //       loop-invariant operands, this special case will no longer be
9434     //       required. We would add the scalarization decision to
9435     //       collectLoopScalars() and teach getVectorValue() to broadcast
9436     //       the lane-zero scalar value.
9437     auto *Clone = State.Builder.Insert(GEP->clone());
9438     for (unsigned Part = 0; Part < State.UF; ++Part) {
9439       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9440       State.set(this, EntryPart, Part);
9441       State.ILV->addMetadata(EntryPart, GEP);
9442     }
9443   } else {
9444     // If the GEP has at least one loop-varying operand, we are sure to
9445     // produce a vector of pointers. But if we are only unrolling, we want
9446     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9447     // produce with the code below will be scalar (if VF == 1) or vector
9448     // (otherwise). Note that for the unroll-only case, we still maintain
9449     // values in the vector mapping with initVector, as we do for other
9450     // instructions.
9451     for (unsigned Part = 0; Part < State.UF; ++Part) {
9452       // The pointer operand of the new GEP. If it's loop-invariant, we
9453       // won't broadcast it.
9454       auto *Ptr = IsPtrLoopInvariant
9455                       ? State.get(getOperand(0), VPIteration(0, 0))
9456                       : State.get(getOperand(0), Part);
9457 
9458       // Collect all the indices for the new GEP. If any index is
9459       // loop-invariant, we won't broadcast it.
9460       SmallVector<Value *, 4> Indices;
9461       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9462         VPValue *Operand = getOperand(I);
9463         if (IsIndexLoopInvariant[I - 1])
9464           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9465         else
9466           Indices.push_back(State.get(Operand, Part));
9467       }
9468 
9469       // If the GEP instruction is vectorized and was in a basic block that
9470       // needed predication, we can't propagate the poison-generating 'inbounds'
9471       // flag. The control flow has been linearized and the GEP is no longer
9472       // guarded by the predicate, which could make the 'inbounds' properties to
9473       // no longer hold.
9474       bool IsInBounds =
9475           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9476 
9477       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9478       // but it should be a vector, otherwise.
9479       auto *NewGEP = State.Builder.CreateGEP(GEP->getSourceElementType(), Ptr,
9480                                              Indices, "", IsInBounds);
9481       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9482              "NewGEP is not a pointer vector");
9483       State.set(this, NewGEP, Part);
9484       State.ILV->addMetadata(NewGEP, GEP);
9485     }
9486   }
9487 }
9488 
9489 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9490   assert(!State.Instance && "Int or FP induction being replicated.");
9491 
9492   Value *Start = getStartValue()->getLiveInIRValue();
9493   const InductionDescriptor &ID = getInductionDescriptor();
9494   TruncInst *Trunc = getTruncInst();
9495   IRBuilderBase &Builder = State.Builder;
9496   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
9497   assert(State.VF.isVector() && "must have vector VF");
9498 
9499   // The value from the original loop to which we are mapping the new induction
9500   // variable.
9501   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
9502 
9503   // Fast-math-flags propagate from the original induction instruction.
9504   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9505   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
9506     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
9507 
9508   // Now do the actual transformations, and start with fetching the step value.
9509   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9510 
9511   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
9512          "Expected either an induction phi-node or a truncate of it!");
9513 
9514   // Construct the initial value of the vector IV in the vector loop preheader
9515   auto CurrIP = Builder.saveIP();
9516   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9517   Builder.SetInsertPoint(VectorPH->getTerminator());
9518   if (isa<TruncInst>(EntryVal)) {
9519     assert(Start->getType()->isIntegerTy() &&
9520            "Truncation requires an integer type");
9521     auto *TruncType = cast<IntegerType>(EntryVal->getType());
9522     Step = Builder.CreateTrunc(Step, TruncType);
9523     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
9524   }
9525 
9526   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
9527   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
9528   Value *SteppedStart = getStepVector(
9529       SplatStart, Zero, Step, ID.getInductionOpcode(), State.VF, State.Builder);
9530 
9531   // We create vector phi nodes for both integer and floating-point induction
9532   // variables. Here, we determine the kind of arithmetic we will perform.
9533   Instruction::BinaryOps AddOp;
9534   Instruction::BinaryOps MulOp;
9535   if (Step->getType()->isIntegerTy()) {
9536     AddOp = Instruction::Add;
9537     MulOp = Instruction::Mul;
9538   } else {
9539     AddOp = ID.getInductionOpcode();
9540     MulOp = Instruction::FMul;
9541   }
9542 
9543   // Multiply the vectorization factor by the step using integer or
9544   // floating-point arithmetic as appropriate.
9545   Type *StepType = Step->getType();
9546   Value *RuntimeVF;
9547   if (Step->getType()->isFloatingPointTy())
9548     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
9549   else
9550     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
9551   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
9552 
9553   // Create a vector splat to use in the induction update.
9554   //
9555   // FIXME: If the step is non-constant, we create the vector splat with
9556   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
9557   //        handle a constant vector splat.
9558   Value *SplatVF = isa<Constant>(Mul)
9559                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
9560                        : Builder.CreateVectorSplat(State.VF, Mul);
9561   Builder.restoreIP(CurrIP);
9562 
9563   // We may need to add the step a number of times, depending on the unroll
9564   // factor. The last of those goes into the PHI.
9565   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
9566                                     &*State.CFG.PrevBB->getFirstInsertionPt());
9567   VecInd->setDebugLoc(EntryVal->getDebugLoc());
9568   Instruction *LastInduction = VecInd;
9569   for (unsigned Part = 0; Part < State.UF; ++Part) {
9570     State.set(this, LastInduction, Part);
9571 
9572     if (isa<TruncInst>(EntryVal))
9573       State.ILV->addMetadata(LastInduction, EntryVal);
9574 
9575     LastInduction = cast<Instruction>(
9576         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
9577     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
9578   }
9579 
9580   LastInduction->setName("vec.ind.next");
9581   VecInd->addIncoming(SteppedStart, VectorPH);
9582   // Add induction update using an incorrect block temporarily. The phi node
9583   // will be fixed after VPlan execution. Note that at this point the latch
9584   // block cannot be used, as it does not exist yet.
9585   // TODO: Model increment value in VPlan, by turning the recipe into a
9586   // multi-def and a subclass of VPHeaderPHIRecipe.
9587   VecInd->addIncoming(LastInduction, VectorPH);
9588 }
9589 
9590 void VPWidenPointerInductionRecipe::execute(VPTransformState &State) {
9591   assert(IndDesc.getKind() == InductionDescriptor::IK_PtrInduction &&
9592          "Not a pointer induction according to InductionDescriptor!");
9593   assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
9594          "Unexpected type.");
9595 
9596   auto *IVR = getParent()->getPlan()->getCanonicalIV();
9597   PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
9598 
9599   if (all_of(users(), [this](const VPUser *U) {
9600         return cast<VPRecipeBase>(U)->usesScalars(this);
9601       })) {
9602     // This is the normalized GEP that starts counting at zero.
9603     Value *PtrInd = State.Builder.CreateSExtOrTrunc(
9604         CanonicalIV, IndDesc.getStep()->getType());
9605     // Determine the number of scalars we need to generate for each unroll
9606     // iteration. If the instruction is uniform, we only need to generate the
9607     // first lane. Otherwise, we generate all VF values.
9608     bool IsUniform = vputils::onlyFirstLaneUsed(this);
9609     assert((IsUniform || !State.VF.isScalable()) &&
9610            "Cannot scalarize a scalable VF");
9611     unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
9612 
9613     for (unsigned Part = 0; Part < State.UF; ++Part) {
9614       Value *PartStart =
9615           createStepForVF(State.Builder, PtrInd->getType(), State.VF, Part);
9616 
9617       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
9618         Value *Idx = State.Builder.CreateAdd(
9619             PartStart, ConstantInt::get(PtrInd->getType(), Lane));
9620         Value *GlobalIdx = State.Builder.CreateAdd(PtrInd, Idx);
9621 
9622         Value *Step = CreateStepValue(IndDesc.getStep(), SE,
9623                                       State.CFG.PrevBB->getTerminator());
9624         Value *SclrGep = emitTransformedIndex(
9625             State.Builder, GlobalIdx, IndDesc.getStartValue(), Step, IndDesc);
9626         SclrGep->setName("next.gep");
9627         State.set(this, SclrGep, VPIteration(Part, Lane));
9628       }
9629     }
9630     return;
9631   }
9632 
9633   assert(isa<SCEVConstant>(IndDesc.getStep()) &&
9634          "Induction step not a SCEV constant!");
9635   Type *PhiType = IndDesc.getStep()->getType();
9636 
9637   // Build a pointer phi
9638   Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
9639   Type *ScStValueType = ScalarStartValue->getType();
9640   PHINode *NewPointerPhi =
9641       PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
9642 
9643   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9644   NewPointerPhi->addIncoming(ScalarStartValue, VectorPH);
9645 
9646   // A pointer induction, performed by using a gep
9647   const DataLayout &DL = NewPointerPhi->getModule()->getDataLayout();
9648   Instruction *InductionLoc = &*State.Builder.GetInsertPoint();
9649 
9650   const SCEV *ScalarStep = IndDesc.getStep();
9651   SCEVExpander Exp(SE, DL, "induction");
9652   Value *ScalarStepValue = Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
9653   Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
9654   Value *NumUnrolledElems =
9655       State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
9656   Value *InductionGEP = GetElementPtrInst::Create(
9657       IndDesc.getElementType(), NewPointerPhi,
9658       State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
9659       InductionLoc);
9660   // Add induction update using an incorrect block temporarily. The phi node
9661   // will be fixed after VPlan execution. Note that at this point the latch
9662   // block cannot be used, as it does not exist yet.
9663   // TODO: Model increment value in VPlan, by turning the recipe into a
9664   // multi-def and a subclass of VPHeaderPHIRecipe.
9665   NewPointerPhi->addIncoming(InductionGEP, VectorPH);
9666 
9667   // Create UF many actual address geps that use the pointer
9668   // phi as base and a vectorized version of the step value
9669   // (<step*0, ..., step*N>) as offset.
9670   for (unsigned Part = 0; Part < State.UF; ++Part) {
9671     Type *VecPhiType = VectorType::get(PhiType, State.VF);
9672     Value *StartOffsetScalar =
9673         State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
9674     Value *StartOffset =
9675         State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
9676     // Create a vector of consecutive numbers from zero to VF.
9677     StartOffset = State.Builder.CreateAdd(
9678         StartOffset, State.Builder.CreateStepVector(VecPhiType));
9679 
9680     Value *GEP = State.Builder.CreateGEP(
9681         IndDesc.getElementType(), NewPointerPhi,
9682         State.Builder.CreateMul(
9683             StartOffset,
9684             State.Builder.CreateVectorSplat(State.VF, ScalarStepValue),
9685             "vector.gep"));
9686     State.set(this, GEP, Part);
9687   }
9688 }
9689 
9690 void VPScalarIVStepsRecipe::execute(VPTransformState &State) {
9691   assert(!State.Instance && "VPScalarIVStepsRecipe being replicated.");
9692 
9693   // Fast-math-flags propagate from the original induction instruction.
9694   IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9695   if (IndDesc.getInductionBinOp() &&
9696       isa<FPMathOperator>(IndDesc.getInductionBinOp()))
9697     State.Builder.setFastMathFlags(
9698         IndDesc.getInductionBinOp()->getFastMathFlags());
9699 
9700   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9701   auto CreateScalarIV = [&](Value *&Step) -> Value * {
9702     Value *ScalarIV = State.get(getCanonicalIV(), VPIteration(0, 0));
9703     auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
9704     if (!isCanonical() || CanonicalIV->getType() != Ty) {
9705       ScalarIV =
9706           Ty->isIntegerTy()
9707               ? State.Builder.CreateSExtOrTrunc(ScalarIV, Ty)
9708               : State.Builder.CreateCast(Instruction::SIToFP, ScalarIV, Ty);
9709       ScalarIV = emitTransformedIndex(State.Builder, ScalarIV,
9710                                       getStartValue()->getLiveInIRValue(), Step,
9711                                       IndDesc);
9712       ScalarIV->setName("offset.idx");
9713     }
9714     if (TruncToTy) {
9715       assert(Step->getType()->isIntegerTy() &&
9716              "Truncation requires an integer step");
9717       ScalarIV = State.Builder.CreateTrunc(ScalarIV, TruncToTy);
9718       Step = State.Builder.CreateTrunc(Step, TruncToTy);
9719     }
9720     return ScalarIV;
9721   };
9722 
9723   Value *ScalarIV = CreateScalarIV(Step);
9724   if (State.VF.isVector()) {
9725     buildScalarSteps(ScalarIV, Step, IndDesc, this, State);
9726     return;
9727   }
9728 
9729   for (unsigned Part = 0; Part < State.UF; ++Part) {
9730     assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
9731     Value *EntryPart;
9732     if (Step->getType()->isFloatingPointTy()) {
9733       Value *StartIdx =
9734           getRuntimeVFAsFloat(State.Builder, Step->getType(), State.VF * Part);
9735       // Floating-point operations inherit FMF via the builder's flags.
9736       Value *MulOp = State.Builder.CreateFMul(StartIdx, Step);
9737       EntryPart = State.Builder.CreateBinOp(IndDesc.getInductionOpcode(),
9738                                             ScalarIV, MulOp);
9739     } else {
9740       Value *StartIdx =
9741           getRuntimeVF(State.Builder, Step->getType(), State.VF * Part);
9742       EntryPart = State.Builder.CreateAdd(
9743           ScalarIV, State.Builder.CreateMul(StartIdx, Step), "induction");
9744     }
9745     State.set(this, EntryPart, Part);
9746   }
9747 }
9748 
9749 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9750   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9751                                  State);
9752 }
9753 
9754 void VPBlendRecipe::execute(VPTransformState &State) {
9755   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9756   // We know that all PHIs in non-header blocks are converted into
9757   // selects, so we don't have to worry about the insertion order and we
9758   // can just use the builder.
9759   // At this point we generate the predication tree. There may be
9760   // duplications since this is a simple recursive scan, but future
9761   // optimizations will clean it up.
9762 
9763   unsigned NumIncoming = getNumIncomingValues();
9764 
9765   // Generate a sequence of selects of the form:
9766   // SELECT(Mask3, In3,
9767   //        SELECT(Mask2, In2,
9768   //               SELECT(Mask1, In1,
9769   //                      In0)))
9770   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9771   // are essentially undef are taken from In0.
9772   InnerLoopVectorizer::VectorParts Entry(State.UF);
9773   for (unsigned In = 0; In < NumIncoming; ++In) {
9774     for (unsigned Part = 0; Part < State.UF; ++Part) {
9775       // We might have single edge PHIs (blocks) - use an identity
9776       // 'select' for the first PHI operand.
9777       Value *In0 = State.get(getIncomingValue(In), Part);
9778       if (In == 0)
9779         Entry[Part] = In0; // Initialize with the first incoming value.
9780       else {
9781         // Select between the current value and the previous incoming edge
9782         // based on the incoming mask.
9783         Value *Cond = State.get(getMask(In), Part);
9784         Entry[Part] =
9785             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9786       }
9787     }
9788   }
9789   for (unsigned Part = 0; Part < State.UF; ++Part)
9790     State.set(this, Entry[Part], Part);
9791 }
9792 
9793 void VPInterleaveRecipe::execute(VPTransformState &State) {
9794   assert(!State.Instance && "Interleave group being replicated.");
9795   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9796                                       getStoredValues(), getMask());
9797 }
9798 
9799 void VPReductionRecipe::execute(VPTransformState &State) {
9800   assert(!State.Instance && "Reduction being replicated.");
9801   Value *PrevInChain = State.get(getChainOp(), 0);
9802   RecurKind Kind = RdxDesc->getRecurrenceKind();
9803   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9804   // Propagate the fast-math flags carried by the underlying instruction.
9805   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9806   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9807   for (unsigned Part = 0; Part < State.UF; ++Part) {
9808     Value *NewVecOp = State.get(getVecOp(), Part);
9809     if (VPValue *Cond = getCondOp()) {
9810       Value *NewCond = State.get(Cond, Part);
9811       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9812       Value *Iden = RdxDesc->getRecurrenceIdentity(
9813           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9814       Value *IdenVec =
9815           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9816       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9817       NewVecOp = Select;
9818     }
9819     Value *NewRed;
9820     Value *NextInChain;
9821     if (IsOrdered) {
9822       if (State.VF.isVector())
9823         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9824                                         PrevInChain);
9825       else
9826         NewRed = State.Builder.CreateBinOp(
9827             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9828             NewVecOp);
9829       PrevInChain = NewRed;
9830     } else {
9831       PrevInChain = State.get(getChainOp(), Part);
9832       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9833     }
9834     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9835       NextInChain =
9836           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9837                          NewRed, PrevInChain);
9838     } else if (IsOrdered)
9839       NextInChain = NewRed;
9840     else
9841       NextInChain = State.Builder.CreateBinOp(
9842           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9843           PrevInChain);
9844     State.set(this, NextInChain, Part);
9845   }
9846 }
9847 
9848 void VPReplicateRecipe::execute(VPTransformState &State) {
9849   if (State.Instance) { // Generate a single instance.
9850     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9851     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9852                                     IsPredicated, State);
9853     // Insert scalar instance packing it into a vector.
9854     if (AlsoPack && State.VF.isVector()) {
9855       // If we're constructing lane 0, initialize to start from poison.
9856       if (State.Instance->Lane.isFirstLane()) {
9857         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9858         Value *Poison = PoisonValue::get(
9859             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9860         State.set(this, Poison, State.Instance->Part);
9861       }
9862       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9863     }
9864     return;
9865   }
9866 
9867   // Generate scalar instances for all VF lanes of all UF parts, unless the
9868   // instruction is uniform inwhich case generate only the first lane for each
9869   // of the UF parts.
9870   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9871   assert((!State.VF.isScalable() || IsUniform) &&
9872          "Can't scalarize a scalable vector");
9873   for (unsigned Part = 0; Part < State.UF; ++Part)
9874     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9875       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9876                                       VPIteration(Part, Lane), IsPredicated,
9877                                       State);
9878 }
9879 
9880 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9881   assert(State.Instance && "Branch on Mask works only on single instance.");
9882 
9883   unsigned Part = State.Instance->Part;
9884   unsigned Lane = State.Instance->Lane.getKnownLane();
9885 
9886   Value *ConditionBit = nullptr;
9887   VPValue *BlockInMask = getMask();
9888   if (BlockInMask) {
9889     ConditionBit = State.get(BlockInMask, Part);
9890     if (ConditionBit->getType()->isVectorTy())
9891       ConditionBit = State.Builder.CreateExtractElement(
9892           ConditionBit, State.Builder.getInt32(Lane));
9893   } else // Block in mask is all-one.
9894     ConditionBit = State.Builder.getTrue();
9895 
9896   // Replace the temporary unreachable terminator with a new conditional branch,
9897   // whose two destinations will be set later when they are created.
9898   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9899   assert(isa<UnreachableInst>(CurrentTerminator) &&
9900          "Expected to replace unreachable terminator with conditional branch.");
9901   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9902   CondBr->setSuccessor(0, nullptr);
9903   ReplaceInstWithInst(CurrentTerminator, CondBr);
9904 }
9905 
9906 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9907   assert(State.Instance && "Predicated instruction PHI works per instance.");
9908   Instruction *ScalarPredInst =
9909       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9910   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9911   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9912   assert(PredicatingBB && "Predicated block has no single predecessor.");
9913   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9914          "operand must be VPReplicateRecipe");
9915 
9916   // By current pack/unpack logic we need to generate only a single phi node: if
9917   // a vector value for the predicated instruction exists at this point it means
9918   // the instruction has vector users only, and a phi for the vector value is
9919   // needed. In this case the recipe of the predicated instruction is marked to
9920   // also do that packing, thereby "hoisting" the insert-element sequence.
9921   // Otherwise, a phi node for the scalar value is needed.
9922   unsigned Part = State.Instance->Part;
9923   if (State.hasVectorValue(getOperand(0), Part)) {
9924     Value *VectorValue = State.get(getOperand(0), Part);
9925     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9926     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9927     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9928     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9929     if (State.hasVectorValue(this, Part))
9930       State.reset(this, VPhi, Part);
9931     else
9932       State.set(this, VPhi, Part);
9933     // NOTE: Currently we need to update the value of the operand, so the next
9934     // predicated iteration inserts its generated value in the correct vector.
9935     State.reset(getOperand(0), VPhi, Part);
9936   } else {
9937     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9938     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9939     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9940                      PredicatingBB);
9941     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9942     if (State.hasScalarValue(this, *State.Instance))
9943       State.reset(this, Phi, *State.Instance);
9944     else
9945       State.set(this, Phi, *State.Instance);
9946     // NOTE: Currently we need to update the value of the operand, so the next
9947     // predicated iteration inserts its generated value in the correct vector.
9948     State.reset(getOperand(0), Phi, *State.Instance);
9949   }
9950 }
9951 
9952 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9953   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9954 
9955   // Attempt to issue a wide load.
9956   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9957   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9958 
9959   assert((LI || SI) && "Invalid Load/Store instruction");
9960   assert((!SI || StoredValue) && "No stored value provided for widened store");
9961   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9962 
9963   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9964 
9965   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9966   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9967   bool CreateGatherScatter = !Consecutive;
9968 
9969   auto &Builder = State.Builder;
9970   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9971   bool isMaskRequired = getMask();
9972   if (isMaskRequired)
9973     for (unsigned Part = 0; Part < State.UF; ++Part)
9974       BlockInMaskParts[Part] = State.get(getMask(), Part);
9975 
9976   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9977     // Calculate the pointer for the specific unroll-part.
9978     GetElementPtrInst *PartPtr = nullptr;
9979 
9980     bool InBounds = false;
9981     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9982       InBounds = gep->isInBounds();
9983     if (Reverse) {
9984       // If the address is consecutive but reversed, then the
9985       // wide store needs to start at the last vector element.
9986       // RunTimeVF =  VScale * VF.getKnownMinValue()
9987       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9988       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9989       // NumElt = -Part * RunTimeVF
9990       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9991       // LastLane = 1 - RunTimeVF
9992       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9993       PartPtr =
9994           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9995       PartPtr->setIsInBounds(InBounds);
9996       PartPtr = cast<GetElementPtrInst>(
9997           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9998       PartPtr->setIsInBounds(InBounds);
9999       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
10000         BlockInMaskParts[Part] =
10001             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
10002     } else {
10003       Value *Increment =
10004           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
10005       PartPtr = cast<GetElementPtrInst>(
10006           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
10007       PartPtr->setIsInBounds(InBounds);
10008     }
10009 
10010     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
10011     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
10012   };
10013 
10014   // Handle Stores:
10015   if (SI) {
10016     State.ILV->setDebugLocFromInst(SI);
10017 
10018     for (unsigned Part = 0; Part < State.UF; ++Part) {
10019       Instruction *NewSI = nullptr;
10020       Value *StoredVal = State.get(StoredValue, Part);
10021       if (CreateGatherScatter) {
10022         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10023         Value *VectorGep = State.get(getAddr(), Part);
10024         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
10025                                             MaskPart);
10026       } else {
10027         if (Reverse) {
10028           // If we store to reverse consecutive memory locations, then we need
10029           // to reverse the order of elements in the stored value.
10030           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
10031           // We don't want to update the value in the map as it might be used in
10032           // another expression. So don't call resetVectorValue(StoredVal).
10033         }
10034         auto *VecPtr =
10035             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10036         if (isMaskRequired)
10037           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
10038                                             BlockInMaskParts[Part]);
10039         else
10040           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
10041       }
10042       State.ILV->addMetadata(NewSI, SI);
10043     }
10044     return;
10045   }
10046 
10047   // Handle loads.
10048   assert(LI && "Must have a load instruction");
10049   State.ILV->setDebugLocFromInst(LI);
10050   for (unsigned Part = 0; Part < State.UF; ++Part) {
10051     Value *NewLI;
10052     if (CreateGatherScatter) {
10053       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10054       Value *VectorGep = State.get(getAddr(), Part);
10055       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
10056                                          nullptr, "wide.masked.gather");
10057       State.ILV->addMetadata(NewLI, LI);
10058     } else {
10059       auto *VecPtr =
10060           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10061       if (isMaskRequired)
10062         NewLI = Builder.CreateMaskedLoad(
10063             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
10064             PoisonValue::get(DataTy), "wide.masked.load");
10065       else
10066         NewLI =
10067             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
10068 
10069       // Add metadata to the load, but setVectorValue to the reverse shuffle.
10070       State.ILV->addMetadata(NewLI, LI);
10071       if (Reverse)
10072         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
10073     }
10074 
10075     State.set(this, NewLI, Part);
10076   }
10077 }
10078 
10079 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10080 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10081 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10082 // for predication.
10083 static ScalarEpilogueLowering getScalarEpilogueLowering(
10084     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10085     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10086     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10087     LoopVectorizationLegality &LVL) {
10088   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10089   // don't look at hints or options, and don't request a scalar epilogue.
10090   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10091   // LoopAccessInfo (due to code dependency and not being able to reliably get
10092   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10093   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10094   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10095   // back to the old way and vectorize with versioning when forced. See D81345.)
10096   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10097                                                       PGSOQueryType::IRPass) &&
10098                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10099     return CM_ScalarEpilogueNotAllowedOptSize;
10100 
10101   // 2) If set, obey the directives
10102   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10103     switch (PreferPredicateOverEpilogue) {
10104     case PreferPredicateTy::ScalarEpilogue:
10105       return CM_ScalarEpilogueAllowed;
10106     case PreferPredicateTy::PredicateElseScalarEpilogue:
10107       return CM_ScalarEpilogueNotNeededUsePredicate;
10108     case PreferPredicateTy::PredicateOrDontVectorize:
10109       return CM_ScalarEpilogueNotAllowedUsePredicate;
10110     };
10111   }
10112 
10113   // 3) If set, obey the hints
10114   switch (Hints.getPredicate()) {
10115   case LoopVectorizeHints::FK_Enabled:
10116     return CM_ScalarEpilogueNotNeededUsePredicate;
10117   case LoopVectorizeHints::FK_Disabled:
10118     return CM_ScalarEpilogueAllowed;
10119   };
10120 
10121   // 4) if the TTI hook indicates this is profitable, request predication.
10122   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10123                                        LVL.getLAI()))
10124     return CM_ScalarEpilogueNotNeededUsePredicate;
10125 
10126   return CM_ScalarEpilogueAllowed;
10127 }
10128 
10129 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10130   // If Values have been set for this Def return the one relevant for \p Part.
10131   if (hasVectorValue(Def, Part))
10132     return Data.PerPartOutput[Def][Part];
10133 
10134   if (!hasScalarValue(Def, {Part, 0})) {
10135     Value *IRV = Def->getLiveInIRValue();
10136     Value *B = ILV->getBroadcastInstrs(IRV);
10137     set(Def, B, Part);
10138     return B;
10139   }
10140 
10141   Value *ScalarValue = get(Def, {Part, 0});
10142   // If we aren't vectorizing, we can just copy the scalar map values over
10143   // to the vector map.
10144   if (VF.isScalar()) {
10145     set(Def, ScalarValue, Part);
10146     return ScalarValue;
10147   }
10148 
10149   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10150   bool IsUniform = RepR && RepR->isUniform();
10151 
10152   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10153   // Check if there is a scalar value for the selected lane.
10154   if (!hasScalarValue(Def, {Part, LastLane})) {
10155     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10156     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) ||
10157             isa<VPScalarIVStepsRecipe>(Def->getDef())) &&
10158            "unexpected recipe found to be invariant");
10159     IsUniform = true;
10160     LastLane = 0;
10161   }
10162 
10163   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10164   // Set the insert point after the last scalarized instruction or after the
10165   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10166   // will directly follow the scalar definitions.
10167   auto OldIP = Builder.saveIP();
10168   auto NewIP =
10169       isa<PHINode>(LastInst)
10170           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10171           : std::next(BasicBlock::iterator(LastInst));
10172   Builder.SetInsertPoint(&*NewIP);
10173 
10174   // However, if we are vectorizing, we need to construct the vector values.
10175   // If the value is known to be uniform after vectorization, we can just
10176   // broadcast the scalar value corresponding to lane zero for each unroll
10177   // iteration. Otherwise, we construct the vector values using
10178   // insertelement instructions. Since the resulting vectors are stored in
10179   // State, we will only generate the insertelements once.
10180   Value *VectorValue = nullptr;
10181   if (IsUniform) {
10182     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10183     set(Def, VectorValue, Part);
10184   } else {
10185     // Initialize packing with insertelements to start from undef.
10186     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10187     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10188     set(Def, Undef, Part);
10189     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10190       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10191     VectorValue = get(Def, Part);
10192   }
10193   Builder.restoreIP(OldIP);
10194   return VectorValue;
10195 }
10196 
10197 // Process the loop in the VPlan-native vectorization path. This path builds
10198 // VPlan upfront in the vectorization pipeline, which allows to apply
10199 // VPlan-to-VPlan transformations from the very beginning without modifying the
10200 // input LLVM IR.
10201 static bool processLoopInVPlanNativePath(
10202     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10203     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10204     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10205     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10206     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10207     LoopVectorizationRequirements &Requirements) {
10208 
10209   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10210     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10211     return false;
10212   }
10213   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10214   Function *F = L->getHeader()->getParent();
10215   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10216 
10217   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10218       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10219 
10220   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10221                                 &Hints, IAI);
10222   // Use the planner for outer loop vectorization.
10223   // TODO: CM is not used at this point inside the planner. Turn CM into an
10224   // optional argument if we don't need it in the future.
10225   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10226                                Requirements, ORE);
10227 
10228   // Get user vectorization factor.
10229   ElementCount UserVF = Hints.getWidth();
10230 
10231   CM.collectElementTypesForWidening();
10232 
10233   // Plan how to best vectorize, return the best VF and its cost.
10234   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10235 
10236   // If we are stress testing VPlan builds, do not attempt to generate vector
10237   // code. Masked vector code generation support will follow soon.
10238   // Also, do not attempt to vectorize if no vector code will be produced.
10239   if (VPlanBuildStressTest || EnableVPlanPredication ||
10240       VectorizationFactor::Disabled() == VF)
10241     return false;
10242 
10243   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10244 
10245   {
10246     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10247                              F->getParent()->getDataLayout());
10248     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10249                            &CM, BFI, PSI, Checks);
10250     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10251                       << L->getHeader()->getParent()->getName() << "\"\n");
10252     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10253   }
10254 
10255   // Mark the loop as already vectorized to avoid vectorizing again.
10256   Hints.setAlreadyVectorized();
10257   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10258   return true;
10259 }
10260 
10261 // Emit a remark if there are stores to floats that required a floating point
10262 // extension. If the vectorized loop was generated with floating point there
10263 // will be a performance penalty from the conversion overhead and the change in
10264 // the vector width.
10265 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10266   SmallVector<Instruction *, 4> Worklist;
10267   for (BasicBlock *BB : L->getBlocks()) {
10268     for (Instruction &Inst : *BB) {
10269       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10270         if (S->getValueOperand()->getType()->isFloatTy())
10271           Worklist.push_back(S);
10272       }
10273     }
10274   }
10275 
10276   // Traverse the floating point stores upwards searching, for floating point
10277   // conversions.
10278   SmallPtrSet<const Instruction *, 4> Visited;
10279   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10280   while (!Worklist.empty()) {
10281     auto *I = Worklist.pop_back_val();
10282     if (!L->contains(I))
10283       continue;
10284     if (!Visited.insert(I).second)
10285       continue;
10286 
10287     // Emit a remark if the floating point store required a floating
10288     // point conversion.
10289     // TODO: More work could be done to identify the root cause such as a
10290     // constant or a function return type and point the user to it.
10291     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10292       ORE->emit([&]() {
10293         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10294                                           I->getDebugLoc(), L->getHeader())
10295                << "floating point conversion changes vector width. "
10296                << "Mixed floating point precision requires an up/down "
10297                << "cast that will negatively impact performance.";
10298       });
10299 
10300     for (Use &Op : I->operands())
10301       if (auto *OpI = dyn_cast<Instruction>(Op))
10302         Worklist.push_back(OpI);
10303   }
10304 }
10305 
10306 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10307     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10308                                !EnableLoopInterleaving),
10309       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10310                               !EnableLoopVectorization) {}
10311 
10312 bool LoopVectorizePass::processLoop(Loop *L) {
10313   assert((EnableVPlanNativePath || L->isInnermost()) &&
10314          "VPlan-native path is not enabled. Only process inner loops.");
10315 
10316 #ifndef NDEBUG
10317   const std::string DebugLocStr = getDebugLocString(L);
10318 #endif /* NDEBUG */
10319 
10320   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
10321                     << L->getHeader()->getParent()->getName() << "' from "
10322                     << DebugLocStr << "\n");
10323 
10324   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10325 
10326   LLVM_DEBUG(
10327       dbgs() << "LV: Loop hints:"
10328              << " force="
10329              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10330                      ? "disabled"
10331                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10332                             ? "enabled"
10333                             : "?"))
10334              << " width=" << Hints.getWidth()
10335              << " interleave=" << Hints.getInterleave() << "\n");
10336 
10337   // Function containing loop
10338   Function *F = L->getHeader()->getParent();
10339 
10340   // Looking at the diagnostic output is the only way to determine if a loop
10341   // was vectorized (other than looking at the IR or machine code), so it
10342   // is important to generate an optimization remark for each loop. Most of
10343   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10344   // generated as OptimizationRemark and OptimizationRemarkMissed are
10345   // less verbose reporting vectorized loops and unvectorized loops that may
10346   // benefit from vectorization, respectively.
10347 
10348   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10349     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10350     return false;
10351   }
10352 
10353   PredicatedScalarEvolution PSE(*SE, *L);
10354 
10355   // Check if it is legal to vectorize the loop.
10356   LoopVectorizationRequirements Requirements;
10357   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10358                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10359   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10360     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10361     Hints.emitRemarkWithHints();
10362     return false;
10363   }
10364 
10365   // Check the function attributes and profiles to find out if this function
10366   // should be optimized for size.
10367   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10368       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10369 
10370   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10371   // here. They may require CFG and instruction level transformations before
10372   // even evaluating whether vectorization is profitable. Since we cannot modify
10373   // the incoming IR, we need to build VPlan upfront in the vectorization
10374   // pipeline.
10375   if (!L->isInnermost())
10376     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10377                                         ORE, BFI, PSI, Hints, Requirements);
10378 
10379   assert(L->isInnermost() && "Inner loop expected.");
10380 
10381   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10382   // count by optimizing for size, to minimize overheads.
10383   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10384   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10385     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10386                       << "This loop is worth vectorizing only if no scalar "
10387                       << "iteration overheads are incurred.");
10388     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10389       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10390     else {
10391       LLVM_DEBUG(dbgs() << "\n");
10392       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10393     }
10394   }
10395 
10396   // Check the function attributes to see if implicit floats are allowed.
10397   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10398   // an integer loop and the vector instructions selected are purely integer
10399   // vector instructions?
10400   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10401     reportVectorizationFailure(
10402         "Can't vectorize when the NoImplicitFloat attribute is used",
10403         "loop not vectorized due to NoImplicitFloat attribute",
10404         "NoImplicitFloat", ORE, L);
10405     Hints.emitRemarkWithHints();
10406     return false;
10407   }
10408 
10409   // Check if the target supports potentially unsafe FP vectorization.
10410   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10411   // for the target we're vectorizing for, to make sure none of the
10412   // additional fp-math flags can help.
10413   if (Hints.isPotentiallyUnsafe() &&
10414       TTI->isFPVectorizationPotentiallyUnsafe()) {
10415     reportVectorizationFailure(
10416         "Potentially unsafe FP op prevents vectorization",
10417         "loop not vectorized due to unsafe FP support.",
10418         "UnsafeFP", ORE, L);
10419     Hints.emitRemarkWithHints();
10420     return false;
10421   }
10422 
10423   bool AllowOrderedReductions;
10424   // If the flag is set, use that instead and override the TTI behaviour.
10425   if (ForceOrderedReductions.getNumOccurrences() > 0)
10426     AllowOrderedReductions = ForceOrderedReductions;
10427   else
10428     AllowOrderedReductions = TTI->enableOrderedReductions();
10429   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10430     ORE->emit([&]() {
10431       auto *ExactFPMathInst = Requirements.getExactFPInst();
10432       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10433                                                  ExactFPMathInst->getDebugLoc(),
10434                                                  ExactFPMathInst->getParent())
10435              << "loop not vectorized: cannot prove it is safe to reorder "
10436                 "floating-point operations";
10437     });
10438     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10439                          "reorder floating-point operations\n");
10440     Hints.emitRemarkWithHints();
10441     return false;
10442   }
10443 
10444   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10445   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10446 
10447   // If an override option has been passed in for interleaved accesses, use it.
10448   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10449     UseInterleaved = EnableInterleavedMemAccesses;
10450 
10451   // Analyze interleaved memory accesses.
10452   if (UseInterleaved) {
10453     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10454   }
10455 
10456   // Use the cost model.
10457   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10458                                 F, &Hints, IAI);
10459   CM.collectValuesToIgnore();
10460   CM.collectElementTypesForWidening();
10461 
10462   // Use the planner for vectorization.
10463   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10464                                Requirements, ORE);
10465 
10466   // Get user vectorization factor and interleave count.
10467   ElementCount UserVF = Hints.getWidth();
10468   unsigned UserIC = Hints.getInterleave();
10469 
10470   // Plan how to best vectorize, return the best VF and its cost.
10471   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10472 
10473   VectorizationFactor VF = VectorizationFactor::Disabled();
10474   unsigned IC = 1;
10475 
10476   if (MaybeVF) {
10477     VF = *MaybeVF;
10478     // Select the interleave count.
10479     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10480   }
10481 
10482   // Identify the diagnostic messages that should be produced.
10483   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10484   bool VectorizeLoop = true, InterleaveLoop = true;
10485   if (VF.Width.isScalar()) {
10486     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10487     VecDiagMsg = std::make_pair(
10488         "VectorizationNotBeneficial",
10489         "the cost-model indicates that vectorization is not beneficial");
10490     VectorizeLoop = false;
10491   }
10492 
10493   if (!MaybeVF && UserIC > 1) {
10494     // Tell the user interleaving was avoided up-front, despite being explicitly
10495     // requested.
10496     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10497                          "interleaving should be avoided up front\n");
10498     IntDiagMsg = std::make_pair(
10499         "InterleavingAvoided",
10500         "Ignoring UserIC, because interleaving was avoided up front");
10501     InterleaveLoop = false;
10502   } else if (IC == 1 && UserIC <= 1) {
10503     // Tell the user interleaving is not beneficial.
10504     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10505     IntDiagMsg = std::make_pair(
10506         "InterleavingNotBeneficial",
10507         "the cost-model indicates that interleaving is not beneficial");
10508     InterleaveLoop = false;
10509     if (UserIC == 1) {
10510       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10511       IntDiagMsg.second +=
10512           " and is explicitly disabled or interleave count is set to 1";
10513     }
10514   } else if (IC > 1 && UserIC == 1) {
10515     // Tell the user interleaving is beneficial, but it explicitly disabled.
10516     LLVM_DEBUG(
10517         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10518     IntDiagMsg = std::make_pair(
10519         "InterleavingBeneficialButDisabled",
10520         "the cost-model indicates that interleaving is beneficial "
10521         "but is explicitly disabled or interleave count is set to 1");
10522     InterleaveLoop = false;
10523   }
10524 
10525   // Override IC if user provided an interleave count.
10526   IC = UserIC > 0 ? UserIC : IC;
10527 
10528   // Emit diagnostic messages, if any.
10529   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10530   if (!VectorizeLoop && !InterleaveLoop) {
10531     // Do not vectorize or interleaving the loop.
10532     ORE->emit([&]() {
10533       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10534                                       L->getStartLoc(), L->getHeader())
10535              << VecDiagMsg.second;
10536     });
10537     ORE->emit([&]() {
10538       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10539                                       L->getStartLoc(), L->getHeader())
10540              << IntDiagMsg.second;
10541     });
10542     return false;
10543   } else if (!VectorizeLoop && InterleaveLoop) {
10544     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10545     ORE->emit([&]() {
10546       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10547                                         L->getStartLoc(), L->getHeader())
10548              << VecDiagMsg.second;
10549     });
10550   } else if (VectorizeLoop && !InterleaveLoop) {
10551     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10552                       << ") in " << DebugLocStr << '\n');
10553     ORE->emit([&]() {
10554       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10555                                         L->getStartLoc(), L->getHeader())
10556              << IntDiagMsg.second;
10557     });
10558   } else if (VectorizeLoop && InterleaveLoop) {
10559     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10560                       << ") in " << DebugLocStr << '\n');
10561     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10562   }
10563 
10564   bool DisableRuntimeUnroll = false;
10565   MDNode *OrigLoopID = L->getLoopID();
10566   {
10567     // Optimistically generate runtime checks. Drop them if they turn out to not
10568     // be profitable. Limit the scope of Checks, so the cleanup happens
10569     // immediately after vector codegeneration is done.
10570     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10571                              F->getParent()->getDataLayout());
10572     if (!VF.Width.isScalar() || IC > 1)
10573       Checks.Create(L, *LVL.getLAI(), PSE.getPredicate());
10574 
10575     using namespace ore;
10576     if (!VectorizeLoop) {
10577       assert(IC > 1 && "interleave count should not be 1 or 0");
10578       // If we decided that it is not legal to vectorize the loop, then
10579       // interleave it.
10580       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10581                                  &CM, BFI, PSI, Checks);
10582 
10583       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10584       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10585 
10586       ORE->emit([&]() {
10587         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10588                                   L->getHeader())
10589                << "interleaved loop (interleaved count: "
10590                << NV("InterleaveCount", IC) << ")";
10591       });
10592     } else {
10593       // If we decided that it is *legal* to vectorize the loop, then do it.
10594 
10595       // Consider vectorizing the epilogue too if it's profitable.
10596       VectorizationFactor EpilogueVF =
10597           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10598       if (EpilogueVF.Width.isVector()) {
10599 
10600         // The first pass vectorizes the main loop and creates a scalar epilogue
10601         // to be vectorized by executing the plan (potentially with a different
10602         // factor) again shortly afterwards.
10603         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10604         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10605                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10606 
10607         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10608         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10609                         DT);
10610         ++LoopsVectorized;
10611 
10612         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10613         formLCSSARecursively(*L, *DT, LI, SE);
10614 
10615         // Second pass vectorizes the epilogue and adjusts the control flow
10616         // edges from the first pass.
10617         EPI.MainLoopVF = EPI.EpilogueVF;
10618         EPI.MainLoopUF = EPI.EpilogueUF;
10619         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10620                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10621                                                  Checks);
10622 
10623         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10624         BestEpiPlan.getVectorLoopRegion()->getEntryBasicBlock()->setName(
10625             "vec.epilog.vector.body");
10626 
10627         // Ensure that the start values for any VPReductionPHIRecipes are
10628         // updated before vectorising the epilogue loop.
10629         VPBasicBlock *Header =
10630             BestEpiPlan.getVectorLoopRegion()->getEntryBasicBlock();
10631         for (VPRecipeBase &R : Header->phis()) {
10632           if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10633             if (auto *Resume = MainILV.getReductionResumeValue(
10634                     ReductionPhi->getRecurrenceDescriptor())) {
10635               VPValue *StartVal = BestEpiPlan.getOrAddExternalDef(Resume);
10636               ReductionPhi->setOperand(0, StartVal);
10637             }
10638           }
10639         }
10640 
10641         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10642                         DT);
10643         ++LoopsEpilogueVectorized;
10644 
10645         if (!MainILV.areSafetyChecksAdded())
10646           DisableRuntimeUnroll = true;
10647       } else {
10648         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10649                                &LVL, &CM, BFI, PSI, Checks);
10650 
10651         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10652         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10653         ++LoopsVectorized;
10654 
10655         // Add metadata to disable runtime unrolling a scalar loop when there
10656         // are no runtime checks about strides and memory. A scalar loop that is
10657         // rarely used is not worth unrolling.
10658         if (!LB.areSafetyChecksAdded())
10659           DisableRuntimeUnroll = true;
10660       }
10661       // Report the vectorization decision.
10662       ORE->emit([&]() {
10663         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10664                                   L->getHeader())
10665                << "vectorized loop (vectorization width: "
10666                << NV("VectorizationFactor", VF.Width)
10667                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10668       });
10669     }
10670 
10671     if (ORE->allowExtraAnalysis(LV_NAME))
10672       checkMixedPrecision(L, ORE);
10673   }
10674 
10675   Optional<MDNode *> RemainderLoopID =
10676       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10677                                       LLVMLoopVectorizeFollowupEpilogue});
10678   if (RemainderLoopID.hasValue()) {
10679     L->setLoopID(RemainderLoopID.getValue());
10680   } else {
10681     if (DisableRuntimeUnroll)
10682       AddRuntimeUnrollDisableMetaData(L);
10683 
10684     // Mark the loop as already vectorized to avoid vectorizing again.
10685     Hints.setAlreadyVectorized();
10686   }
10687 
10688   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10689   return true;
10690 }
10691 
10692 LoopVectorizeResult LoopVectorizePass::runImpl(
10693     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10694     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10695     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10696     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10697     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10698   SE = &SE_;
10699   LI = &LI_;
10700   TTI = &TTI_;
10701   DT = &DT_;
10702   BFI = &BFI_;
10703   TLI = TLI_;
10704   AA = &AA_;
10705   AC = &AC_;
10706   GetLAA = &GetLAA_;
10707   DB = &DB_;
10708   ORE = &ORE_;
10709   PSI = PSI_;
10710 
10711   // Don't attempt if
10712   // 1. the target claims to have no vector registers, and
10713   // 2. interleaving won't help ILP.
10714   //
10715   // The second condition is necessary because, even if the target has no
10716   // vector registers, loop vectorization may still enable scalar
10717   // interleaving.
10718   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10719       TTI->getMaxInterleaveFactor(1) < 2)
10720     return LoopVectorizeResult(false, false);
10721 
10722   bool Changed = false, CFGChanged = false;
10723 
10724   // The vectorizer requires loops to be in simplified form.
10725   // Since simplification may add new inner loops, it has to run before the
10726   // legality and profitability checks. This means running the loop vectorizer
10727   // will simplify all loops, regardless of whether anything end up being
10728   // vectorized.
10729   for (auto &L : *LI)
10730     Changed |= CFGChanged |=
10731         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10732 
10733   // Build up a worklist of inner-loops to vectorize. This is necessary as
10734   // the act of vectorizing or partially unrolling a loop creates new loops
10735   // and can invalidate iterators across the loops.
10736   SmallVector<Loop *, 8> Worklist;
10737 
10738   for (Loop *L : *LI)
10739     collectSupportedLoops(*L, LI, ORE, Worklist);
10740 
10741   LoopsAnalyzed += Worklist.size();
10742 
10743   // Now walk the identified inner loops.
10744   while (!Worklist.empty()) {
10745     Loop *L = Worklist.pop_back_val();
10746 
10747     // For the inner loops we actually process, form LCSSA to simplify the
10748     // transform.
10749     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10750 
10751     Changed |= CFGChanged |= processLoop(L);
10752   }
10753 
10754   // Process each loop nest in the function.
10755   return LoopVectorizeResult(Changed, CFGChanged);
10756 }
10757 
10758 PreservedAnalyses LoopVectorizePass::run(Function &F,
10759                                          FunctionAnalysisManager &AM) {
10760     auto &LI = AM.getResult<LoopAnalysis>(F);
10761     // There are no loops in the function. Return before computing other expensive
10762     // analyses.
10763     if (LI.empty())
10764       return PreservedAnalyses::all();
10765     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10766     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10767     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10768     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10769     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10770     auto &AA = AM.getResult<AAManager>(F);
10771     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10772     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10773     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10774 
10775     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10776     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10777         [&](Loop &L) -> const LoopAccessInfo & {
10778       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10779                                         TLI, TTI, nullptr, nullptr, nullptr};
10780       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10781     };
10782     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10783     ProfileSummaryInfo *PSI =
10784         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10785     LoopVectorizeResult Result =
10786         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10787     if (!Result.MadeAnyChange)
10788       return PreservedAnalyses::all();
10789     PreservedAnalyses PA;
10790 
10791     // We currently do not preserve loopinfo/dominator analyses with outer loop
10792     // vectorization. Until this is addressed, mark these analyses as preserved
10793     // only for non-VPlan-native path.
10794     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10795     if (!EnableVPlanNativePath) {
10796       PA.preserve<LoopAnalysis>();
10797       PA.preserve<DominatorTreeAnalysis>();
10798     }
10799 
10800     if (Result.MadeCFGChange) {
10801       // Making CFG changes likely means a loop got vectorized. Indicate that
10802       // extra simplification passes should be run.
10803       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10804       // be run if runtime checks have been added.
10805       AM.getResult<ShouldRunExtraVectorPasses>(F);
10806       PA.preserve<ShouldRunExtraVectorPasses>();
10807     } else {
10808       PA.preserveSet<CFGAnalyses>();
10809     }
10810     return PA;
10811 }
10812 
10813 void LoopVectorizePass::printPipeline(
10814     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10815   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10816       OS, MapClassName2PassName);
10817 
10818   OS << "<";
10819   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10820   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10821   OS << ">";
10822 }
10823