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);
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 *CountRoundDown, Value *EndValue,
570                     BasicBlock *MiddleBlock, BasicBlock *VectorHeader);
571 
572   /// Introduce a conditional branch (on true, condition to be set later) at the
573   /// end of the header=latch connecting it to itself (across the backedge) and
574   /// to the exit block of \p L.
575   void createHeaderBranch(Loop *L);
576 
577   /// Handle all cross-iteration phis in the header.
578   void fixCrossIterationPHIs(VPTransformState &State);
579 
580   /// Create the exit value of first order recurrences in the middle block and
581   /// update their users.
582   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
583                                VPTransformState &State);
584 
585   /// Create code for the loop exit value of the reduction.
586   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
587 
588   /// Clear NSW/NUW flags from reduction instructions if necessary.
589   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
590                                VPTransformState &State);
591 
592   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
593   /// means we need to add the appropriate incoming value from the middle
594   /// block as exiting edges from the scalar epilogue loop (if present) are
595   /// already in place, and we exit the vector loop exclusively to the middle
596   /// block.
597   void fixLCSSAPHIs(VPTransformState &State);
598 
599   /// Iteratively sink the scalarized operands of a predicated instruction into
600   /// the block that was created for it.
601   void sinkScalarOperands(Instruction *PredInst);
602 
603   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
604   /// represented as.
605   void truncateToMinimalBitwidths(VPTransformState &State);
606 
607   /// Returns (and creates if needed) the original loop trip count.
608   Value *getOrCreateTripCount(BasicBlock *InsertBlock);
609 
610   /// Returns (and creates if needed) the trip count of the widened loop.
611   Value *getOrCreateVectorTripCount(BasicBlock *InsertBlock);
612 
613   /// Returns a bitcasted value to the requested vector type.
614   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
615   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
616                                 const DataLayout &DL);
617 
618   /// Emit a bypass check to see if the vector trip count is zero, including if
619   /// it overflows.
620   void emitMinimumIterationCountCheck(BasicBlock *Bypass);
621 
622   /// Emit a bypass check to see if all of the SCEV assumptions we've
623   /// had to make are correct. Returns the block containing the checks or
624   /// nullptr if no checks have been added.
625   BasicBlock *emitSCEVChecks(BasicBlock *Bypass);
626 
627   /// Emit bypass checks to check any memory assumptions we may have made.
628   /// Returns the block containing the checks or nullptr if no checks have been
629   /// added.
630   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass);
631 
632   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
633   /// vector loop preheader, middle block and scalar preheader. Also
634   /// allocate a loop object for the new vector loop and return it.
635   Loop *createVectorLoopSkeleton(StringRef Prefix);
636 
637   /// Create new phi nodes for the induction variables to resume iteration count
638   /// in the scalar epilogue, from where the vectorized loop left off.
639   /// In cases where the loop skeleton is more complicated (eg. epilogue
640   /// vectorization) and the resume values can come from an additional bypass
641   /// block, the \p AdditionalBypass pair provides information about the bypass
642   /// block and the end value on the edge from bypass to this loop.
643   void createInductionResumeValues(
644       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
645 
646   /// Complete the loop skeleton by adding debug MDs, creating appropriate
647   /// conditional branches in the middle block, preparing the builder and
648   /// running the verifier. Return the preheader of the completed vector loop.
649   BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
650 
651   /// Add additional metadata to \p To that was not present on \p Orig.
652   ///
653   /// Currently this is used to add the noalias annotations based on the
654   /// inserted memchecks.  Use this for instructions that are *cloned* into the
655   /// vector loop.
656   void addNewMetadata(Instruction *To, const Instruction *Orig);
657 
658   /// Collect poison-generating recipes that may generate a poison value that is
659   /// used after vectorization, even when their operands are not poison. Those
660   /// recipes meet the following conditions:
661   ///  * Contribute to the address computation of a recipe generating a widen
662   ///    memory load/store (VPWidenMemoryInstructionRecipe or
663   ///    VPInterleaveRecipe).
664   ///  * Such a widen memory load/store has at least one underlying Instruction
665   ///    that is in a basic block that needs predication and after vectorization
666   ///    the generated instruction won't be predicated.
667   void collectPoisonGeneratingRecipes(VPTransformState &State);
668 
669   /// Allow subclasses to override and print debug traces before/after vplan
670   /// execution, when trace information is requested.
671   virtual void printDebugTracesAtStart(){};
672   virtual void printDebugTracesAtEnd(){};
673 
674   /// The original loop.
675   Loop *OrigLoop;
676 
677   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
678   /// dynamic knowledge to simplify SCEV expressions and converts them to a
679   /// more usable form.
680   PredicatedScalarEvolution &PSE;
681 
682   /// Loop Info.
683   LoopInfo *LI;
684 
685   /// Dominator Tree.
686   DominatorTree *DT;
687 
688   /// Alias Analysis.
689   AAResults *AA;
690 
691   /// Target Library Info.
692   const TargetLibraryInfo *TLI;
693 
694   /// Target Transform Info.
695   const TargetTransformInfo *TTI;
696 
697   /// Assumption Cache.
698   AssumptionCache *AC;
699 
700   /// Interface to emit optimization remarks.
701   OptimizationRemarkEmitter *ORE;
702 
703   /// LoopVersioning.  It's only set up (non-null) if memchecks were
704   /// used.
705   ///
706   /// This is currently only used to add no-alias metadata based on the
707   /// memchecks.  The actually versioning is performed manually.
708   std::unique_ptr<LoopVersioning> LVer;
709 
710   /// The vectorization SIMD factor to use. Each vector will have this many
711   /// vector elements.
712   ElementCount VF;
713 
714   /// The vectorization unroll factor to use. Each scalar is vectorized to this
715   /// many different vector instructions.
716   unsigned UF;
717 
718   /// The builder that we use
719   IRBuilder<> Builder;
720 
721   // --- Vectorization state ---
722 
723   /// The vector-loop preheader.
724   BasicBlock *LoopVectorPreHeader;
725 
726   /// The scalar-loop preheader.
727   BasicBlock *LoopScalarPreHeader;
728 
729   /// Middle Block between the vector and the scalar.
730   BasicBlock *LoopMiddleBlock;
731 
732   /// The unique ExitBlock of the scalar loop if one exists.  Note that
733   /// there can be multiple exiting edges reaching this block.
734   BasicBlock *LoopExitBlock;
735 
736   /// The scalar loop body.
737   BasicBlock *LoopScalarBody;
738 
739   /// A list of all bypass blocks. The first block is the entry of the loop.
740   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
741 
742   /// Store instructions that were predicated.
743   SmallVector<Instruction *, 4> PredicatedInstructions;
744 
745   /// Trip count of the original loop.
746   Value *TripCount = nullptr;
747 
748   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
749   Value *VectorTripCount = nullptr;
750 
751   /// The legality analysis.
752   LoopVectorizationLegality *Legal;
753 
754   /// The profitablity analysis.
755   LoopVectorizationCostModel *Cost;
756 
757   // Record whether runtime checks are added.
758   bool AddedSafetyChecks = false;
759 
760   // Holds the end values for each induction variable. We save the end values
761   // so we can later fix-up the external users of the induction variables.
762   DenseMap<PHINode *, Value *> IVEndValues;
763 
764   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
765   // fixed up at the end of vector code generation.
766   SmallVector<PHINode *, 8> OrigPHIsToFix;
767 
768   /// BFI and PSI are used to check for profile guided size optimizations.
769   BlockFrequencyInfo *BFI;
770   ProfileSummaryInfo *PSI;
771 
772   // Whether this loop should be optimized for size based on profile guided size
773   // optimizatios.
774   bool OptForSizeBasedOnProfile;
775 
776   /// Structure to hold information about generated runtime checks, responsible
777   /// for cleaning the checks, if vectorization turns out unprofitable.
778   GeneratedRTChecks &RTChecks;
779 
780   // Holds the resume values for reductions in the loops, used to set the
781   // correct start value of reduction PHIs when vectorizing the epilogue.
782   SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
783       ReductionResumeValues;
784 };
785 
786 class InnerLoopUnroller : public InnerLoopVectorizer {
787 public:
788   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
789                     LoopInfo *LI, DominatorTree *DT,
790                     const TargetLibraryInfo *TLI,
791                     const TargetTransformInfo *TTI, AssumptionCache *AC,
792                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
793                     LoopVectorizationLegality *LVL,
794                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
795                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
796       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
797                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
798                             BFI, PSI, Check) {}
799 
800 private:
801   Value *getBroadcastInstrs(Value *V) override;
802 };
803 
804 /// Encapsulate information regarding vectorization of a loop and its epilogue.
805 /// This information is meant to be updated and used across two stages of
806 /// epilogue vectorization.
807 struct EpilogueLoopVectorizationInfo {
808   ElementCount MainLoopVF = ElementCount::getFixed(0);
809   unsigned MainLoopUF = 0;
810   ElementCount EpilogueVF = ElementCount::getFixed(0);
811   unsigned EpilogueUF = 0;
812   BasicBlock *MainLoopIterationCountCheck = nullptr;
813   BasicBlock *EpilogueIterationCountCheck = nullptr;
814   BasicBlock *SCEVSafetyCheck = nullptr;
815   BasicBlock *MemSafetyCheck = nullptr;
816   Value *TripCount = nullptr;
817   Value *VectorTripCount = nullptr;
818 
819   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
820                                 ElementCount EVF, unsigned EUF)
821       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
822     assert(EUF == 1 &&
823            "A high UF for the epilogue loop is likely not beneficial.");
824   }
825 };
826 
827 /// An extension of the inner loop vectorizer that creates a skeleton for a
828 /// vectorized loop that has its epilogue (residual) also vectorized.
829 /// The idea is to run the vplan on a given loop twice, firstly to setup the
830 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
831 /// from the first step and vectorize the epilogue.  This is achieved by
832 /// deriving two concrete strategy classes from this base class and invoking
833 /// them in succession from the loop vectorizer planner.
834 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
835 public:
836   InnerLoopAndEpilogueVectorizer(
837       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
838       DominatorTree *DT, const TargetLibraryInfo *TLI,
839       const TargetTransformInfo *TTI, AssumptionCache *AC,
840       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
841       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
842       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
843       GeneratedRTChecks &Checks)
844       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
845                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
846                             Checks),
847         EPI(EPI) {}
848 
849   // Override this function to handle the more complex control flow around the
850   // three loops.
851   std::pair<BasicBlock *, Value *>
852   createVectorizedLoopSkeleton() final override {
853     return createEpilogueVectorizedLoopSkeleton();
854   }
855 
856   /// The interface for creating a vectorized skeleton using one of two
857   /// different strategies, each corresponding to one execution of the vplan
858   /// as described above.
859   virtual std::pair<BasicBlock *, Value *>
860   createEpilogueVectorizedLoopSkeleton() = 0;
861 
862   /// Holds and updates state information required to vectorize the main loop
863   /// and its epilogue in two separate passes. This setup helps us avoid
864   /// regenerating and recomputing runtime safety checks. It also helps us to
865   /// shorten the iteration-count-check path length for the cases where the
866   /// iteration count of the loop is so small that the main vector loop is
867   /// completely skipped.
868   EpilogueLoopVectorizationInfo &EPI;
869 };
870 
871 /// A specialized derived class of inner loop vectorizer that performs
872 /// vectorization of *main* loops in the process of vectorizing loops and their
873 /// epilogues.
874 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
875 public:
876   EpilogueVectorizerMainLoop(
877       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
878       DominatorTree *DT, const TargetLibraryInfo *TLI,
879       const TargetTransformInfo *TTI, AssumptionCache *AC,
880       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
881       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
882       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
883       GeneratedRTChecks &Check)
884       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
885                                        EPI, LVL, CM, BFI, PSI, Check) {}
886   /// Implements the interface for creating a vectorized skeleton using the
887   /// *main loop* strategy (ie the first pass of vplan execution).
888   std::pair<BasicBlock *, Value *>
889   createEpilogueVectorizedLoopSkeleton() final override;
890 
891 protected:
892   /// Emits an iteration count bypass check once for the main loop (when \p
893   /// ForEpilogue is false) and once for the epilogue loop (when \p
894   /// ForEpilogue is true).
895   BasicBlock *emitMinimumIterationCountCheck(BasicBlock *Bypass,
896                                              bool ForEpilogue);
897   void printDebugTracesAtStart() override;
898   void printDebugTracesAtEnd() override;
899 };
900 
901 // A specialized derived class of inner loop vectorizer that performs
902 // vectorization of *epilogue* loops in the process of vectorizing loops and
903 // their epilogues.
904 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
905 public:
906   EpilogueVectorizerEpilogueLoop(
907       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
908       DominatorTree *DT, const TargetLibraryInfo *TLI,
909       const TargetTransformInfo *TTI, AssumptionCache *AC,
910       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
911       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
912       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
913       GeneratedRTChecks &Checks)
914       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
915                                        EPI, LVL, CM, BFI, PSI, Checks) {}
916   /// Implements the interface for creating a vectorized skeleton using the
917   /// *epilogue loop* strategy (ie the second pass of vplan execution).
918   std::pair<BasicBlock *, Value *>
919   createEpilogueVectorizedLoopSkeleton() final override;
920 
921 protected:
922   /// Emits an iteration count bypass check after the main vector loop has
923   /// finished to see if there are any iterations left to execute by either
924   /// the vector epilogue or the scalar epilogue.
925   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
926                                                       BasicBlock *Bypass,
927                                                       BasicBlock *Insert);
928   void printDebugTracesAtStart() override;
929   void printDebugTracesAtEnd() override;
930 };
931 } // end namespace llvm
932 
933 /// Look for a meaningful debug location on the instruction or it's
934 /// operands.
935 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
936   if (!I)
937     return I;
938 
939   DebugLoc Empty;
940   if (I->getDebugLoc() != Empty)
941     return I;
942 
943   for (Use &Op : I->operands()) {
944     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
945       if (OpInst->getDebugLoc() != Empty)
946         return OpInst;
947   }
948 
949   return I;
950 }
951 
952 void InnerLoopVectorizer::setDebugLocFromInst(
953     const Value *V, Optional<IRBuilderBase *> CustomBuilder) {
954   IRBuilderBase *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
955   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
956     const DILocation *DIL = Inst->getDebugLoc();
957 
958     // When a FSDiscriminator is enabled, we don't need to add the multiply
959     // factors to the discriminators.
960     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
961         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
962       // FIXME: For scalable vectors, assume vscale=1.
963       auto NewDIL =
964           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
965       if (NewDIL)
966         B->SetCurrentDebugLocation(NewDIL.getValue());
967       else
968         LLVM_DEBUG(dbgs()
969                    << "Failed to create new discriminator: "
970                    << DIL->getFilename() << " Line: " << DIL->getLine());
971     } else
972       B->SetCurrentDebugLocation(DIL);
973   } else
974     B->SetCurrentDebugLocation(DebugLoc());
975 }
976 
977 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
978 /// is passed, the message relates to that particular instruction.
979 #ifndef NDEBUG
980 static void debugVectorizationMessage(const StringRef Prefix,
981                                       const StringRef DebugMsg,
982                                       Instruction *I) {
983   dbgs() << "LV: " << Prefix << DebugMsg;
984   if (I != nullptr)
985     dbgs() << " " << *I;
986   else
987     dbgs() << '.';
988   dbgs() << '\n';
989 }
990 #endif
991 
992 /// Create an analysis remark that explains why vectorization failed
993 ///
994 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
995 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
996 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
997 /// the location of the remark.  \return the remark object that can be
998 /// streamed to.
999 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1000     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1001   Value *CodeRegion = TheLoop->getHeader();
1002   DebugLoc DL = TheLoop->getStartLoc();
1003 
1004   if (I) {
1005     CodeRegion = I->getParent();
1006     // If there is no debug location attached to the instruction, revert back to
1007     // using the loop's.
1008     if (I->getDebugLoc())
1009       DL = I->getDebugLoc();
1010   }
1011 
1012   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1013 }
1014 
1015 namespace llvm {
1016 
1017 /// Return a value for Step multiplied by VF.
1018 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
1019                        int64_t Step) {
1020   assert(Ty->isIntegerTy() && "Expected an integer step");
1021   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
1022   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1023 }
1024 
1025 /// Return the runtime value for VF.
1026 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF) {
1027   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1028   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1029 }
1030 
1031 static Value *getRuntimeVFAsFloat(IRBuilderBase &B, Type *FTy,
1032                                   ElementCount VF) {
1033   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1034   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1035   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1036   return B.CreateUIToFP(RuntimeVF, FTy);
1037 }
1038 
1039 void reportVectorizationFailure(const StringRef DebugMsg,
1040                                 const StringRef OREMsg, const StringRef ORETag,
1041                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1042                                 Instruction *I) {
1043   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1044   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1045   ORE->emit(
1046       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1047       << "loop not vectorized: " << OREMsg);
1048 }
1049 
1050 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1051                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1052                              Instruction *I) {
1053   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1054   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1055   ORE->emit(
1056       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1057       << Msg);
1058 }
1059 
1060 } // end namespace llvm
1061 
1062 #ifndef NDEBUG
1063 /// \return string containing a file name and a line # for the given loop.
1064 static std::string getDebugLocString(const Loop *L) {
1065   std::string Result;
1066   if (L) {
1067     raw_string_ostream OS(Result);
1068     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1069       LoopDbgLoc.print(OS);
1070     else
1071       // Just print the module name.
1072       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1073     OS.flush();
1074   }
1075   return Result;
1076 }
1077 #endif
1078 
1079 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1080                                          const Instruction *Orig) {
1081   // If the loop was versioned with memchecks, add the corresponding no-alias
1082   // metadata.
1083   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1084     LVer->annotateInstWithNoAlias(To, Orig);
1085 }
1086 
1087 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1088     VPTransformState &State) {
1089 
1090   // Collect recipes in the backward slice of `Root` that may generate a poison
1091   // value that is used after vectorization.
1092   SmallPtrSet<VPRecipeBase *, 16> Visited;
1093   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1094     SmallVector<VPRecipeBase *, 16> Worklist;
1095     Worklist.push_back(Root);
1096 
1097     // Traverse the backward slice of Root through its use-def chain.
1098     while (!Worklist.empty()) {
1099       VPRecipeBase *CurRec = Worklist.back();
1100       Worklist.pop_back();
1101 
1102       if (!Visited.insert(CurRec).second)
1103         continue;
1104 
1105       // Prune search if we find another recipe generating a widen memory
1106       // instruction. Widen memory instructions involved in address computation
1107       // will lead to gather/scatter instructions, which don't need to be
1108       // handled.
1109       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1110           isa<VPInterleaveRecipe>(CurRec) ||
1111           isa<VPScalarIVStepsRecipe>(CurRec) ||
1112           isa<VPCanonicalIVPHIRecipe>(CurRec))
1113         continue;
1114 
1115       // This recipe contributes to the address computation of a widen
1116       // load/store. Collect recipe if its underlying instruction has
1117       // poison-generating flags.
1118       Instruction *Instr = CurRec->getUnderlyingInstr();
1119       if (Instr && Instr->hasPoisonGeneratingFlags())
1120         State.MayGeneratePoisonRecipes.insert(CurRec);
1121 
1122       // Add new definitions to the worklist.
1123       for (VPValue *operand : CurRec->operands())
1124         if (VPDef *OpDef = operand->getDef())
1125           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1126     }
1127   });
1128 
1129   // Traverse all the recipes in the VPlan and collect the poison-generating
1130   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1131   // VPInterleaveRecipe.
1132   auto Iter = depth_first(
1133       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1134   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1135     for (VPRecipeBase &Recipe : *VPBB) {
1136       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1137         Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
1138         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1139         if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
1140             Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
1141           collectPoisonGeneratingInstrsInBackwardSlice(
1142               cast<VPRecipeBase>(AddrDef));
1143       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1144         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1145         if (AddrDef) {
1146           // Check if any member of the interleave group needs predication.
1147           const InterleaveGroup<Instruction> *InterGroup =
1148               InterleaveRec->getInterleaveGroup();
1149           bool NeedPredication = false;
1150           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1151                I < NumMembers; ++I) {
1152             Instruction *Member = InterGroup->getMember(I);
1153             if (Member)
1154               NeedPredication |=
1155                   Legal->blockNeedsPredication(Member->getParent());
1156           }
1157 
1158           if (NeedPredication)
1159             collectPoisonGeneratingInstrsInBackwardSlice(
1160                 cast<VPRecipeBase>(AddrDef));
1161         }
1162       }
1163     }
1164   }
1165 }
1166 
1167 void InnerLoopVectorizer::addMetadata(Instruction *To,
1168                                       Instruction *From) {
1169   propagateMetadata(To, From);
1170   addNewMetadata(To, From);
1171 }
1172 
1173 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1174                                       Instruction *From) {
1175   for (Value *V : To) {
1176     if (Instruction *I = dyn_cast<Instruction>(V))
1177       addMetadata(I, From);
1178   }
1179 }
1180 
1181 PHINode *InnerLoopVectorizer::getReductionResumeValue(
1182     const RecurrenceDescriptor &RdxDesc) {
1183   auto It = ReductionResumeValues.find(&RdxDesc);
1184   assert(It != ReductionResumeValues.end() &&
1185          "Expected to find a resume value for the reduction.");
1186   return It->second;
1187 }
1188 
1189 namespace llvm {
1190 
1191 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1192 // lowered.
1193 enum ScalarEpilogueLowering {
1194 
1195   // The default: allowing scalar epilogues.
1196   CM_ScalarEpilogueAllowed,
1197 
1198   // Vectorization with OptForSize: don't allow epilogues.
1199   CM_ScalarEpilogueNotAllowedOptSize,
1200 
1201   // A special case of vectorisation with OptForSize: loops with a very small
1202   // trip count are considered for vectorization under OptForSize, thereby
1203   // making sure the cost of their loop body is dominant, free of runtime
1204   // guards and scalar iteration overheads.
1205   CM_ScalarEpilogueNotAllowedLowTripLoop,
1206 
1207   // Loop hint predicate indicating an epilogue is undesired.
1208   CM_ScalarEpilogueNotNeededUsePredicate,
1209 
1210   // Directive indicating we must either tail fold or not vectorize
1211   CM_ScalarEpilogueNotAllowedUsePredicate
1212 };
1213 
1214 /// ElementCountComparator creates a total ordering for ElementCount
1215 /// for the purposes of using it in a set structure.
1216 struct ElementCountComparator {
1217   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1218     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1219            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1220   }
1221 };
1222 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1223 
1224 /// LoopVectorizationCostModel - estimates the expected speedups due to
1225 /// vectorization.
1226 /// In many cases vectorization is not profitable. This can happen because of
1227 /// a number of reasons. In this class we mainly attempt to predict the
1228 /// expected speedup/slowdowns due to the supported instruction set. We use the
1229 /// TargetTransformInfo to query the different backends for the cost of
1230 /// different operations.
1231 class LoopVectorizationCostModel {
1232 public:
1233   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1234                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1235                              LoopVectorizationLegality *Legal,
1236                              const TargetTransformInfo &TTI,
1237                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1238                              AssumptionCache *AC,
1239                              OptimizationRemarkEmitter *ORE, const Function *F,
1240                              const LoopVectorizeHints *Hints,
1241                              InterleavedAccessInfo &IAI)
1242       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1243         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1244         Hints(Hints), InterleaveInfo(IAI) {}
1245 
1246   /// \return An upper bound for the vectorization factors (both fixed and
1247   /// scalable). If the factors are 0, vectorization and interleaving should be
1248   /// avoided up front.
1249   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1250 
1251   /// \return True if runtime checks are required for vectorization, and false
1252   /// otherwise.
1253   bool runtimeChecksRequired();
1254 
1255   /// \return The most profitable vectorization factor and the cost of that VF.
1256   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1257   /// then this vectorization factor will be selected if vectorization is
1258   /// possible.
1259   VectorizationFactor
1260   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1261 
1262   VectorizationFactor
1263   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1264                                     const LoopVectorizationPlanner &LVP);
1265 
1266   /// Setup cost-based decisions for user vectorization factor.
1267   /// \return true if the UserVF is a feasible VF to be chosen.
1268   bool selectUserVectorizationFactor(ElementCount UserVF) {
1269     collectUniformsAndScalars(UserVF);
1270     collectInstsToScalarize(UserVF);
1271     return expectedCost(UserVF).first.isValid();
1272   }
1273 
1274   /// \return The size (in bits) of the smallest and widest types in the code
1275   /// that needs to be vectorized. We ignore values that remain scalar such as
1276   /// 64 bit loop indices.
1277   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1278 
1279   /// \return The desired interleave count.
1280   /// If interleave count has been specified by metadata it will be returned.
1281   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1282   /// are the selected vectorization factor and the cost of the selected VF.
1283   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1284 
1285   /// Memory access instruction may be vectorized in more than one way.
1286   /// Form of instruction after vectorization depends on cost.
1287   /// This function takes cost-based decisions for Load/Store instructions
1288   /// and collects them in a map. This decisions map is used for building
1289   /// the lists of loop-uniform and loop-scalar instructions.
1290   /// The calculated cost is saved with widening decision in order to
1291   /// avoid redundant calculations.
1292   void setCostBasedWideningDecision(ElementCount VF);
1293 
1294   /// A struct that represents some properties of the register usage
1295   /// of a loop.
1296   struct RegisterUsage {
1297     /// Holds the number of loop invariant values that are used in the loop.
1298     /// The key is ClassID of target-provided register class.
1299     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1300     /// Holds the maximum number of concurrent live intervals in the loop.
1301     /// The key is ClassID of target-provided register class.
1302     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1303   };
1304 
1305   /// \return Returns information about the register usages of the loop for the
1306   /// given vectorization factors.
1307   SmallVector<RegisterUsage, 8>
1308   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1309 
1310   /// Collect values we want to ignore in the cost model.
1311   void collectValuesToIgnore();
1312 
1313   /// Collect all element types in the loop for which widening is needed.
1314   void collectElementTypesForWidening();
1315 
1316   /// Split reductions into those that happen in the loop, and those that happen
1317   /// outside. In loop reductions are collected into InLoopReductionChains.
1318   void collectInLoopReductions();
1319 
1320   /// Returns true if we should use strict in-order reductions for the given
1321   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1322   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1323   /// of FP operations.
1324   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1325     return !Hints->allowReordering() && RdxDesc.isOrdered();
1326   }
1327 
1328   /// \returns The smallest bitwidth each instruction can be represented with.
1329   /// The vector equivalents of these instructions should be truncated to this
1330   /// type.
1331   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1332     return MinBWs;
1333   }
1334 
1335   /// \returns True if it is more profitable to scalarize instruction \p I for
1336   /// vectorization factor \p VF.
1337   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1338     assert(VF.isVector() &&
1339            "Profitable to scalarize relevant only for VF > 1.");
1340 
1341     // Cost model is not run in the VPlan-native path - return conservative
1342     // result until this changes.
1343     if (EnableVPlanNativePath)
1344       return false;
1345 
1346     auto Scalars = InstsToScalarize.find(VF);
1347     assert(Scalars != InstsToScalarize.end() &&
1348            "VF not yet analyzed for scalarization profitability");
1349     return Scalars->second.find(I) != Scalars->second.end();
1350   }
1351 
1352   /// Returns true if \p I is known to be uniform after vectorization.
1353   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1354     if (VF.isScalar())
1355       return true;
1356 
1357     // Cost model is not run in the VPlan-native path - return conservative
1358     // result until this changes.
1359     if (EnableVPlanNativePath)
1360       return false;
1361 
1362     auto UniformsPerVF = Uniforms.find(VF);
1363     assert(UniformsPerVF != Uniforms.end() &&
1364            "VF not yet analyzed for uniformity");
1365     return UniformsPerVF->second.count(I);
1366   }
1367 
1368   /// Returns true if \p I is known to be scalar after vectorization.
1369   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1370     if (VF.isScalar())
1371       return true;
1372 
1373     // Cost model is not run in the VPlan-native path - return conservative
1374     // result until this changes.
1375     if (EnableVPlanNativePath)
1376       return false;
1377 
1378     auto ScalarsPerVF = Scalars.find(VF);
1379     assert(ScalarsPerVF != Scalars.end() &&
1380            "Scalar values are not calculated for VF");
1381     return ScalarsPerVF->second.count(I);
1382   }
1383 
1384   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1385   /// for vectorization factor \p VF.
1386   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1387     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1388            !isProfitableToScalarize(I, VF) &&
1389            !isScalarAfterVectorization(I, VF);
1390   }
1391 
1392   /// Decision that was taken during cost calculation for memory instruction.
1393   enum InstWidening {
1394     CM_Unknown,
1395     CM_Widen,         // For consecutive accesses with stride +1.
1396     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1397     CM_Interleave,
1398     CM_GatherScatter,
1399     CM_Scalarize
1400   };
1401 
1402   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1403   /// instruction \p I and vector width \p VF.
1404   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1405                            InstructionCost Cost) {
1406     assert(VF.isVector() && "Expected VF >=2");
1407     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1408   }
1409 
1410   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1411   /// interleaving group \p Grp and vector width \p VF.
1412   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1413                            ElementCount VF, InstWidening W,
1414                            InstructionCost Cost) {
1415     assert(VF.isVector() && "Expected VF >=2");
1416     /// Broadcast this decicion to all instructions inside the group.
1417     /// But the cost will be assigned to one instruction only.
1418     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1419       if (auto *I = Grp->getMember(i)) {
1420         if (Grp->getInsertPos() == I)
1421           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1422         else
1423           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1424       }
1425     }
1426   }
1427 
1428   /// Return the cost model decision for the given instruction \p I and vector
1429   /// width \p VF. Return CM_Unknown if this instruction did not pass
1430   /// through the cost modeling.
1431   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1432     assert(VF.isVector() && "Expected VF to be a vector VF");
1433     // Cost model is not run in the VPlan-native path - return conservative
1434     // result until this changes.
1435     if (EnableVPlanNativePath)
1436       return CM_GatherScatter;
1437 
1438     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1439     auto Itr = WideningDecisions.find(InstOnVF);
1440     if (Itr == WideningDecisions.end())
1441       return CM_Unknown;
1442     return Itr->second.first;
1443   }
1444 
1445   /// Return the vectorization cost for the given instruction \p I and vector
1446   /// width \p VF.
1447   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1448     assert(VF.isVector() && "Expected VF >=2");
1449     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1450     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1451            "The cost is not calculated");
1452     return WideningDecisions[InstOnVF].second;
1453   }
1454 
1455   /// Return True if instruction \p I is an optimizable truncate whose operand
1456   /// is an induction variable. Such a truncate will be removed by adding a new
1457   /// induction variable with the destination type.
1458   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1459     // If the instruction is not a truncate, return false.
1460     auto *Trunc = dyn_cast<TruncInst>(I);
1461     if (!Trunc)
1462       return false;
1463 
1464     // Get the source and destination types of the truncate.
1465     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1466     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1467 
1468     // If the truncate is free for the given types, return false. Replacing a
1469     // free truncate with an induction variable would add an induction variable
1470     // update instruction to each iteration of the loop. We exclude from this
1471     // check the primary induction variable since it will need an update
1472     // instruction regardless.
1473     Value *Op = Trunc->getOperand(0);
1474     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1475       return false;
1476 
1477     // If the truncated value is not an induction variable, return false.
1478     return Legal->isInductionPhi(Op);
1479   }
1480 
1481   /// Collects the instructions to scalarize for each predicated instruction in
1482   /// the loop.
1483   void collectInstsToScalarize(ElementCount VF);
1484 
1485   /// Collect Uniform and Scalar values for the given \p VF.
1486   /// The sets depend on CM decision for Load/Store instructions
1487   /// that may be vectorized as interleave, gather-scatter or scalarized.
1488   void collectUniformsAndScalars(ElementCount VF) {
1489     // Do the analysis once.
1490     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1491       return;
1492     setCostBasedWideningDecision(VF);
1493     collectLoopUniforms(VF);
1494     collectLoopScalars(VF);
1495   }
1496 
1497   /// Returns true if the target machine supports masked store operation
1498   /// for the given \p DataType and kind of access to \p Ptr.
1499   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1500     return Legal->isConsecutivePtr(DataType, Ptr) &&
1501            TTI.isLegalMaskedStore(DataType, Alignment);
1502   }
1503 
1504   /// Returns true if the target machine supports masked load operation
1505   /// for the given \p DataType and kind of access to \p Ptr.
1506   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1507     return Legal->isConsecutivePtr(DataType, Ptr) &&
1508            TTI.isLegalMaskedLoad(DataType, Alignment);
1509   }
1510 
1511   /// Returns true if the target machine can represent \p V as a masked gather
1512   /// or scatter operation.
1513   bool isLegalGatherOrScatter(Value *V,
1514                               ElementCount VF = ElementCount::getFixed(1)) {
1515     bool LI = isa<LoadInst>(V);
1516     bool SI = isa<StoreInst>(V);
1517     if (!LI && !SI)
1518       return false;
1519     auto *Ty = getLoadStoreType(V);
1520     Align Align = getLoadStoreAlignment(V);
1521     if (VF.isVector())
1522       Ty = VectorType::get(Ty, VF);
1523     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1524            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1525   }
1526 
1527   /// Returns true if the target machine supports all of the reduction
1528   /// variables found for the given VF.
1529   bool canVectorizeReductions(ElementCount VF) const {
1530     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1531       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1532       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1533     }));
1534   }
1535 
1536   /// Returns true if \p I is an instruction that will be scalarized with
1537   /// predication when vectorizing \p I with vectorization factor \p VF. Such
1538   /// instructions include conditional stores and instructions that may divide
1539   /// by zero.
1540   bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1541 
1542   // Returns true if \p I is an instruction that will be predicated either
1543   // through scalar predication or masked load/store or masked gather/scatter.
1544   // \p VF is the vectorization factor that will be used to vectorize \p I.
1545   // Superset of instructions that return true for isScalarWithPredication.
1546   bool isPredicatedInst(Instruction *I, ElementCount VF,
1547                         bool IsKnownUniform = false) {
1548     // When we know the load is uniform and the original scalar loop was not
1549     // predicated we don't need to mark it as a predicated instruction. Any
1550     // vectorised blocks created when tail-folding are something artificial we
1551     // have introduced and we know there is always at least one active lane.
1552     // That's why we call Legal->blockNeedsPredication here because it doesn't
1553     // query tail-folding.
1554     if (IsKnownUniform && isa<LoadInst>(I) &&
1555         !Legal->blockNeedsPredication(I->getParent()))
1556       return false;
1557     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1558       return false;
1559     // Loads and stores that need some form of masked operation are predicated
1560     // instructions.
1561     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1562       return Legal->isMaskRequired(I);
1563     return isScalarWithPredication(I, VF);
1564   }
1565 
1566   /// Returns true if \p I is a memory instruction with consecutive memory
1567   /// access that can be widened.
1568   bool
1569   memoryInstructionCanBeWidened(Instruction *I,
1570                                 ElementCount VF = ElementCount::getFixed(1));
1571 
1572   /// Returns true if \p I is a memory instruction in an interleaved-group
1573   /// of memory accesses that can be vectorized with wide vector loads/stores
1574   /// and shuffles.
1575   bool
1576   interleavedAccessCanBeWidened(Instruction *I,
1577                                 ElementCount VF = ElementCount::getFixed(1));
1578 
1579   /// Check if \p Instr belongs to any interleaved access group.
1580   bool isAccessInterleaved(Instruction *Instr) {
1581     return InterleaveInfo.isInterleaved(Instr);
1582   }
1583 
1584   /// Get the interleaved access group that \p Instr belongs to.
1585   const InterleaveGroup<Instruction> *
1586   getInterleavedAccessGroup(Instruction *Instr) {
1587     return InterleaveInfo.getInterleaveGroup(Instr);
1588   }
1589 
1590   /// Returns true if we're required to use a scalar epilogue for at least
1591   /// the final iteration of the original loop.
1592   bool requiresScalarEpilogue(ElementCount VF) const {
1593     if (!isScalarEpilogueAllowed())
1594       return false;
1595     // If we might exit from anywhere but the latch, must run the exiting
1596     // iteration in scalar form.
1597     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1598       return true;
1599     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1600   }
1601 
1602   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1603   /// loop hint annotation.
1604   bool isScalarEpilogueAllowed() const {
1605     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1606   }
1607 
1608   /// Returns true if all loop blocks should be masked to fold tail loop.
1609   bool foldTailByMasking() const { return FoldTailByMasking; }
1610 
1611   /// Returns true if the instructions in this block requires predication
1612   /// for any reason, e.g. because tail folding now requires a predicate
1613   /// or because the block in the original loop was predicated.
1614   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1615     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1616   }
1617 
1618   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1619   /// nodes to the chain of instructions representing the reductions. Uses a
1620   /// MapVector to ensure deterministic iteration order.
1621   using ReductionChainMap =
1622       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1623 
1624   /// Return the chain of instructions representing an inloop reduction.
1625   const ReductionChainMap &getInLoopReductionChains() const {
1626     return InLoopReductionChains;
1627   }
1628 
1629   /// Returns true if the Phi is part of an inloop reduction.
1630   bool isInLoopReduction(PHINode *Phi) const {
1631     return InLoopReductionChains.count(Phi);
1632   }
1633 
1634   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1635   /// with factor VF.  Return the cost of the instruction, including
1636   /// scalarization overhead if it's needed.
1637   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1638 
1639   /// Estimate cost of a call instruction CI if it were vectorized with factor
1640   /// VF. Return the cost of the instruction, including scalarization overhead
1641   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1642   /// scalarized -
1643   /// i.e. either vector version isn't available, or is too expensive.
1644   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1645                                     bool &NeedToScalarize) const;
1646 
1647   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1648   /// that of B.
1649   bool isMoreProfitable(const VectorizationFactor &A,
1650                         const VectorizationFactor &B) const;
1651 
1652   /// Invalidates decisions already taken by the cost model.
1653   void invalidateCostModelingDecisions() {
1654     WideningDecisions.clear();
1655     Uniforms.clear();
1656     Scalars.clear();
1657   }
1658 
1659 private:
1660   unsigned NumPredStores = 0;
1661 
1662   /// Convenience function that returns the value of vscale_range iff
1663   /// vscale_range.min == vscale_range.max or otherwise returns the value
1664   /// returned by the corresponding TLI method.
1665   Optional<unsigned> getVScaleForTuning() const;
1666 
1667   /// \return An upper bound for the vectorization factors for both
1668   /// fixed and scalable vectorization, where the minimum-known number of
1669   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1670   /// disabled or unsupported, then the scalable part will be equal to
1671   /// ElementCount::getScalable(0).
1672   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1673                                            ElementCount UserVF,
1674                                            bool FoldTailByMasking);
1675 
1676   /// \return the maximized element count based on the targets vector
1677   /// registers and the loop trip-count, but limited to a maximum safe VF.
1678   /// This is a helper function of computeFeasibleMaxVF.
1679   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1680   /// issue that occurred on one of the buildbots which cannot be reproduced
1681   /// without having access to the properietary compiler (see comments on
1682   /// D98509). The issue is currently under investigation and this workaround
1683   /// will be removed as soon as possible.
1684   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1685                                        unsigned SmallestType,
1686                                        unsigned WidestType,
1687                                        const ElementCount &MaxSafeVF,
1688                                        bool FoldTailByMasking);
1689 
1690   /// \return the maximum legal scalable VF, based on the safe max number
1691   /// of elements.
1692   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1693 
1694   /// The vectorization cost is a combination of the cost itself and a boolean
1695   /// indicating whether any of the contributing operations will actually
1696   /// operate on vector values after type legalization in the backend. If this
1697   /// latter value is false, then all operations will be scalarized (i.e. no
1698   /// vectorization has actually taken place).
1699   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1700 
1701   /// Returns the expected execution cost. The unit of the cost does
1702   /// not matter because we use the 'cost' units to compare different
1703   /// vector widths. The cost that is returned is *not* normalized by
1704   /// the factor width. If \p Invalid is not nullptr, this function
1705   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1706   /// each instruction that has an Invalid cost for the given VF.
1707   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1708   VectorizationCostTy
1709   expectedCost(ElementCount VF,
1710                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1711 
1712   /// Returns the execution time cost of an instruction for a given vector
1713   /// width. Vector width of one means scalar.
1714   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1715 
1716   /// The cost-computation logic from getInstructionCost which provides
1717   /// the vector type as an output parameter.
1718   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1719                                      Type *&VectorTy);
1720 
1721   /// Return the cost of instructions in an inloop reduction pattern, if I is
1722   /// part of that pattern.
1723   Optional<InstructionCost>
1724   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1725                           TTI::TargetCostKind CostKind);
1726 
1727   /// Calculate vectorization cost of memory instruction \p I.
1728   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1729 
1730   /// The cost computation for scalarized memory instruction.
1731   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1732 
1733   /// The cost computation for interleaving group of memory instructions.
1734   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1735 
1736   /// The cost computation for Gather/Scatter instruction.
1737   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1738 
1739   /// The cost computation for widening instruction \p I with consecutive
1740   /// memory access.
1741   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1742 
1743   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1744   /// Load: scalar load + broadcast.
1745   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1746   /// element)
1747   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1748 
1749   /// Estimate the overhead of scalarizing an instruction. This is a
1750   /// convenience wrapper for the type-based getScalarizationOverhead API.
1751   InstructionCost getScalarizationOverhead(Instruction *I,
1752                                            ElementCount VF) const;
1753 
1754   /// Returns whether the instruction is a load or store and will be a emitted
1755   /// as a vector operation.
1756   bool isConsecutiveLoadOrStore(Instruction *I);
1757 
1758   /// Returns true if an artificially high cost for emulated masked memrefs
1759   /// should be used.
1760   bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1761 
1762   /// Map of scalar integer values to the smallest bitwidth they can be legally
1763   /// represented as. The vector equivalents of these values should be truncated
1764   /// to this type.
1765   MapVector<Instruction *, uint64_t> MinBWs;
1766 
1767   /// A type representing the costs for instructions if they were to be
1768   /// scalarized rather than vectorized. The entries are Instruction-Cost
1769   /// pairs.
1770   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1771 
1772   /// A set containing all BasicBlocks that are known to present after
1773   /// vectorization as a predicated block.
1774   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1775 
1776   /// Records whether it is allowed to have the original scalar loop execute at
1777   /// least once. This may be needed as a fallback loop in case runtime
1778   /// aliasing/dependence checks fail, or to handle the tail/remainder
1779   /// iterations when the trip count is unknown or doesn't divide by the VF,
1780   /// or as a peel-loop to handle gaps in interleave-groups.
1781   /// Under optsize and when the trip count is very small we don't allow any
1782   /// iterations to execute in the scalar loop.
1783   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1784 
1785   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1786   bool FoldTailByMasking = false;
1787 
1788   /// A map holding scalar costs for different vectorization factors. The
1789   /// presence of a cost for an instruction in the mapping indicates that the
1790   /// instruction will be scalarized when vectorizing with the associated
1791   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1792   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1793 
1794   /// Holds the instructions known to be uniform after vectorization.
1795   /// The data is collected per VF.
1796   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1797 
1798   /// Holds the instructions known to be scalar after vectorization.
1799   /// The data is collected per VF.
1800   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1801 
1802   /// Holds the instructions (address computations) that are forced to be
1803   /// scalarized.
1804   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1805 
1806   /// PHINodes of the reductions that should be expanded in-loop along with
1807   /// their associated chains of reduction operations, in program order from top
1808   /// (PHI) to bottom
1809   ReductionChainMap InLoopReductionChains;
1810 
1811   /// A Map of inloop reduction operations and their immediate chain operand.
1812   /// FIXME: This can be removed once reductions can be costed correctly in
1813   /// vplan. This was added to allow quick lookup to the inloop operations,
1814   /// without having to loop through InLoopReductionChains.
1815   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1816 
1817   /// Returns the expected difference in cost from scalarizing the expression
1818   /// feeding a predicated instruction \p PredInst. The instructions to
1819   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1820   /// non-negative return value implies the expression will be scalarized.
1821   /// Currently, only single-use chains are considered for scalarization.
1822   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1823                               ElementCount VF);
1824 
1825   /// Collect the instructions that are uniform after vectorization. An
1826   /// instruction is uniform if we represent it with a single scalar value in
1827   /// the vectorized loop corresponding to each vector iteration. Examples of
1828   /// uniform instructions include pointer operands of consecutive or
1829   /// interleaved memory accesses. Note that although uniformity implies an
1830   /// instruction will be scalar, the reverse is not true. In general, a
1831   /// scalarized instruction will be represented by VF scalar values in the
1832   /// vectorized loop, each corresponding to an iteration of the original
1833   /// scalar loop.
1834   void collectLoopUniforms(ElementCount VF);
1835 
1836   /// Collect the instructions that are scalar after vectorization. An
1837   /// instruction is scalar if it is known to be uniform or will be scalarized
1838   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1839   /// to the list if they are used by a load/store instruction that is marked as
1840   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1841   /// VF values in the vectorized loop, each corresponding to an iteration of
1842   /// the original scalar loop.
1843   void collectLoopScalars(ElementCount VF);
1844 
1845   /// Keeps cost model vectorization decision and cost for instructions.
1846   /// Right now it is used for memory instructions only.
1847   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1848                                 std::pair<InstWidening, InstructionCost>>;
1849 
1850   DecisionList WideningDecisions;
1851 
1852   /// Returns true if \p V is expected to be vectorized and it needs to be
1853   /// extracted.
1854   bool needsExtract(Value *V, ElementCount VF) const {
1855     Instruction *I = dyn_cast<Instruction>(V);
1856     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1857         TheLoop->isLoopInvariant(I))
1858       return false;
1859 
1860     // Assume we can vectorize V (and hence we need extraction) if the
1861     // scalars are not computed yet. This can happen, because it is called
1862     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1863     // the scalars are collected. That should be a safe assumption in most
1864     // cases, because we check if the operands have vectorizable types
1865     // beforehand in LoopVectorizationLegality.
1866     return Scalars.find(VF) == Scalars.end() ||
1867            !isScalarAfterVectorization(I, VF);
1868   };
1869 
1870   /// Returns a range containing only operands needing to be extracted.
1871   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1872                                                    ElementCount VF) const {
1873     return SmallVector<Value *, 4>(make_filter_range(
1874         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1875   }
1876 
1877   /// Determines if we have the infrastructure to vectorize loop \p L and its
1878   /// epilogue, assuming the main loop is vectorized by \p VF.
1879   bool isCandidateForEpilogueVectorization(const Loop &L,
1880                                            const ElementCount VF) const;
1881 
1882   /// Returns true if epilogue vectorization is considered profitable, and
1883   /// false otherwise.
1884   /// \p VF is the vectorization factor chosen for the original loop.
1885   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1886 
1887 public:
1888   /// The loop that we evaluate.
1889   Loop *TheLoop;
1890 
1891   /// Predicated scalar evolution analysis.
1892   PredicatedScalarEvolution &PSE;
1893 
1894   /// Loop Info analysis.
1895   LoopInfo *LI;
1896 
1897   /// Vectorization legality.
1898   LoopVectorizationLegality *Legal;
1899 
1900   /// Vector target information.
1901   const TargetTransformInfo &TTI;
1902 
1903   /// Target Library Info.
1904   const TargetLibraryInfo *TLI;
1905 
1906   /// Demanded bits analysis.
1907   DemandedBits *DB;
1908 
1909   /// Assumption cache.
1910   AssumptionCache *AC;
1911 
1912   /// Interface to emit optimization remarks.
1913   OptimizationRemarkEmitter *ORE;
1914 
1915   const Function *TheFunction;
1916 
1917   /// Loop Vectorize Hint.
1918   const LoopVectorizeHints *Hints;
1919 
1920   /// The interleave access information contains groups of interleaved accesses
1921   /// with the same stride and close to each other.
1922   InterleavedAccessInfo &InterleaveInfo;
1923 
1924   /// Values to ignore in the cost model.
1925   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1926 
1927   /// Values to ignore in the cost model when VF > 1.
1928   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1929 
1930   /// All element types found in the loop.
1931   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1932 
1933   /// Profitable vector factors.
1934   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1935 };
1936 } // end namespace llvm
1937 
1938 /// Helper struct to manage generating runtime checks for vectorization.
1939 ///
1940 /// The runtime checks are created up-front in temporary blocks to allow better
1941 /// estimating the cost and un-linked from the existing IR. After deciding to
1942 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1943 /// temporary blocks are completely removed.
1944 class GeneratedRTChecks {
1945   /// Basic block which contains the generated SCEV checks, if any.
1946   BasicBlock *SCEVCheckBlock = nullptr;
1947 
1948   /// The value representing the result of the generated SCEV checks. If it is
1949   /// nullptr, either no SCEV checks have been generated or they have been used.
1950   Value *SCEVCheckCond = nullptr;
1951 
1952   /// Basic block which contains the generated memory runtime checks, if any.
1953   BasicBlock *MemCheckBlock = nullptr;
1954 
1955   /// The value representing the result of the generated memory runtime checks.
1956   /// If it is nullptr, either no memory runtime checks have been generated or
1957   /// they have been used.
1958   Value *MemRuntimeCheckCond = nullptr;
1959 
1960   DominatorTree *DT;
1961   LoopInfo *LI;
1962 
1963   SCEVExpander SCEVExp;
1964   SCEVExpander MemCheckExp;
1965 
1966 public:
1967   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1968                     const DataLayout &DL)
1969       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1970         MemCheckExp(SE, DL, "scev.check") {}
1971 
1972   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1973   /// accurately estimate the cost of the runtime checks. The blocks are
1974   /// un-linked from the IR and is added back during vector code generation. If
1975   /// there is no vector code generation, the check blocks are removed
1976   /// completely.
1977   void Create(Loop *L, const LoopAccessInfo &LAI,
1978               const SCEVPredicate &Pred) {
1979 
1980     BasicBlock *LoopHeader = L->getHeader();
1981     BasicBlock *Preheader = L->getLoopPreheader();
1982 
1983     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1984     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1985     // may be used by SCEVExpander. The blocks will be un-linked from their
1986     // predecessors and removed from LI & DT at the end of the function.
1987     if (!Pred.isAlwaysTrue()) {
1988       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1989                                   nullptr, "vector.scevcheck");
1990 
1991       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1992           &Pred, SCEVCheckBlock->getTerminator());
1993     }
1994 
1995     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1996     if (RtPtrChecking.Need) {
1997       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1998       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1999                                  "vector.memcheck");
2000 
2001       MemRuntimeCheckCond =
2002           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
2003                            RtPtrChecking.getChecks(), MemCheckExp);
2004       assert(MemRuntimeCheckCond &&
2005              "no RT checks generated although RtPtrChecking "
2006              "claimed checks are required");
2007     }
2008 
2009     if (!MemCheckBlock && !SCEVCheckBlock)
2010       return;
2011 
2012     // Unhook the temporary block with the checks, update various places
2013     // accordingly.
2014     if (SCEVCheckBlock)
2015       SCEVCheckBlock->replaceAllUsesWith(Preheader);
2016     if (MemCheckBlock)
2017       MemCheckBlock->replaceAllUsesWith(Preheader);
2018 
2019     if (SCEVCheckBlock) {
2020       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2021       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
2022       Preheader->getTerminator()->eraseFromParent();
2023     }
2024     if (MemCheckBlock) {
2025       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2026       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2027       Preheader->getTerminator()->eraseFromParent();
2028     }
2029 
2030     DT->changeImmediateDominator(LoopHeader, Preheader);
2031     if (MemCheckBlock) {
2032       DT->eraseNode(MemCheckBlock);
2033       LI->removeBlock(MemCheckBlock);
2034     }
2035     if (SCEVCheckBlock) {
2036       DT->eraseNode(SCEVCheckBlock);
2037       LI->removeBlock(SCEVCheckBlock);
2038     }
2039   }
2040 
2041   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2042   /// unused.
2043   ~GeneratedRTChecks() {
2044     SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2045     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2046     if (!SCEVCheckCond)
2047       SCEVCleaner.markResultUsed();
2048 
2049     if (!MemRuntimeCheckCond)
2050       MemCheckCleaner.markResultUsed();
2051 
2052     if (MemRuntimeCheckCond) {
2053       auto &SE = *MemCheckExp.getSE();
2054       // Memory runtime check generation creates compares that use expanded
2055       // values. Remove them before running the SCEVExpanderCleaners.
2056       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2057         if (MemCheckExp.isInsertedInstruction(&I))
2058           continue;
2059         SE.forgetValue(&I);
2060         I.eraseFromParent();
2061       }
2062     }
2063     MemCheckCleaner.cleanup();
2064     SCEVCleaner.cleanup();
2065 
2066     if (SCEVCheckCond)
2067       SCEVCheckBlock->eraseFromParent();
2068     if (MemRuntimeCheckCond)
2069       MemCheckBlock->eraseFromParent();
2070   }
2071 
2072   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2073   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2074   /// depending on the generated condition.
2075   BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2076                              BasicBlock *LoopVectorPreHeader,
2077                              BasicBlock *LoopExitBlock) {
2078     if (!SCEVCheckCond)
2079       return nullptr;
2080     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2081       if (C->isZero())
2082         return nullptr;
2083 
2084     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2085 
2086     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2087     // Create new preheader for vector loop.
2088     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2089       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2090 
2091     SCEVCheckBlock->getTerminator()->eraseFromParent();
2092     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2093     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2094                                                 SCEVCheckBlock);
2095 
2096     DT->addNewBlock(SCEVCheckBlock, Pred);
2097     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2098 
2099     ReplaceInstWithInst(
2100         SCEVCheckBlock->getTerminator(),
2101         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2102     // Mark the check as used, to prevent it from being removed during cleanup.
2103     SCEVCheckCond = nullptr;
2104     return SCEVCheckBlock;
2105   }
2106 
2107   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2108   /// the branches to branch to the vector preheader or \p Bypass, depending on
2109   /// the generated condition.
2110   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2111                                    BasicBlock *LoopVectorPreHeader) {
2112     // Check if we generated code that checks in runtime if arrays overlap.
2113     if (!MemRuntimeCheckCond)
2114       return nullptr;
2115 
2116     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2117     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2118                                                 MemCheckBlock);
2119 
2120     DT->addNewBlock(MemCheckBlock, Pred);
2121     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2122     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2123 
2124     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2125       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2126 
2127     ReplaceInstWithInst(
2128         MemCheckBlock->getTerminator(),
2129         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2130     MemCheckBlock->getTerminator()->setDebugLoc(
2131         Pred->getTerminator()->getDebugLoc());
2132 
2133     // Mark the check as used, to prevent it from being removed during cleanup.
2134     MemRuntimeCheckCond = nullptr;
2135     return MemCheckBlock;
2136   }
2137 };
2138 
2139 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2140 // vectorization. The loop needs to be annotated with #pragma omp simd
2141 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2142 // vector length information is not provided, vectorization is not considered
2143 // explicit. Interleave hints are not allowed either. These limitations will be
2144 // relaxed in the future.
2145 // Please, note that we are currently forced to abuse the pragma 'clang
2146 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2147 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2148 // provides *explicit vectorization hints* (LV can bypass legal checks and
2149 // assume that vectorization is legal). However, both hints are implemented
2150 // using the same metadata (llvm.loop.vectorize, processed by
2151 // LoopVectorizeHints). This will be fixed in the future when the native IR
2152 // representation for pragma 'omp simd' is introduced.
2153 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2154                                    OptimizationRemarkEmitter *ORE) {
2155   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2156   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2157 
2158   // Only outer loops with an explicit vectorization hint are supported.
2159   // Unannotated outer loops are ignored.
2160   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2161     return false;
2162 
2163   Function *Fn = OuterLp->getHeader()->getParent();
2164   if (!Hints.allowVectorization(Fn, OuterLp,
2165                                 true /*VectorizeOnlyWhenForced*/)) {
2166     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2167     return false;
2168   }
2169 
2170   if (Hints.getInterleave() > 1) {
2171     // TODO: Interleave support is future work.
2172     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2173                          "outer loops.\n");
2174     Hints.emitRemarkWithHints();
2175     return false;
2176   }
2177 
2178   return true;
2179 }
2180 
2181 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2182                                   OptimizationRemarkEmitter *ORE,
2183                                   SmallVectorImpl<Loop *> &V) {
2184   // Collect inner loops and outer loops without irreducible control flow. For
2185   // now, only collect outer loops that have explicit vectorization hints. If we
2186   // are stress testing the VPlan H-CFG construction, we collect the outermost
2187   // loop of every loop nest.
2188   if (L.isInnermost() || VPlanBuildStressTest ||
2189       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2190     LoopBlocksRPO RPOT(&L);
2191     RPOT.perform(LI);
2192     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2193       V.push_back(&L);
2194       // TODO: Collect inner loops inside marked outer loops in case
2195       // vectorization fails for the outer loop. Do not invoke
2196       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2197       // already known to be reducible. We can use an inherited attribute for
2198       // that.
2199       return;
2200     }
2201   }
2202   for (Loop *InnerL : L)
2203     collectSupportedLoops(*InnerL, LI, ORE, V);
2204 }
2205 
2206 namespace {
2207 
2208 /// The LoopVectorize Pass.
2209 struct LoopVectorize : public FunctionPass {
2210   /// Pass identification, replacement for typeid
2211   static char ID;
2212 
2213   LoopVectorizePass Impl;
2214 
2215   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2216                          bool VectorizeOnlyWhenForced = false)
2217       : FunctionPass(ID),
2218         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2219     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2220   }
2221 
2222   bool runOnFunction(Function &F) override {
2223     if (skipFunction(F))
2224       return false;
2225 
2226     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2227     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2228     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2229     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2230     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2231     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2232     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2233     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2234     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2235     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2236     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2237     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2238     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2239 
2240     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2241         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2242 
2243     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2244                         GetLAA, *ORE, PSI).MadeAnyChange;
2245   }
2246 
2247   void getAnalysisUsage(AnalysisUsage &AU) const override {
2248     AU.addRequired<AssumptionCacheTracker>();
2249     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2250     AU.addRequired<DominatorTreeWrapperPass>();
2251     AU.addRequired<LoopInfoWrapperPass>();
2252     AU.addRequired<ScalarEvolutionWrapperPass>();
2253     AU.addRequired<TargetTransformInfoWrapperPass>();
2254     AU.addRequired<AAResultsWrapperPass>();
2255     AU.addRequired<LoopAccessLegacyAnalysis>();
2256     AU.addRequired<DemandedBitsWrapperPass>();
2257     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2258     AU.addRequired<InjectTLIMappingsLegacy>();
2259 
2260     // We currently do not preserve loopinfo/dominator analyses with outer loop
2261     // vectorization. Until this is addressed, mark these analyses as preserved
2262     // only for non-VPlan-native path.
2263     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2264     if (!EnableVPlanNativePath) {
2265       AU.addPreserved<LoopInfoWrapperPass>();
2266       AU.addPreserved<DominatorTreeWrapperPass>();
2267     }
2268 
2269     AU.addPreserved<BasicAAWrapperPass>();
2270     AU.addPreserved<GlobalsAAWrapperPass>();
2271     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2272   }
2273 };
2274 
2275 } // end anonymous namespace
2276 
2277 //===----------------------------------------------------------------------===//
2278 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2279 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2280 //===----------------------------------------------------------------------===//
2281 
2282 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2283   // We need to place the broadcast of invariant variables outside the loop,
2284   // but only if it's proven safe to do so. Else, broadcast will be inside
2285   // vector loop body.
2286   Instruction *Instr = dyn_cast<Instruction>(V);
2287   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2288                      (!Instr ||
2289                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2290   // Place the code for broadcasting invariant variables in the new preheader.
2291   IRBuilder<>::InsertPointGuard Guard(Builder);
2292   if (SafeToHoist)
2293     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2294 
2295   // Broadcast the scalar into all locations in the vector.
2296   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2297 
2298   return Shuf;
2299 }
2300 
2301 /// This function adds
2302 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2303 /// to each vector element of Val. The sequence starts at StartIndex.
2304 /// \p Opcode is relevant for FP induction variable.
2305 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2306                             Instruction::BinaryOps BinOp, ElementCount VF,
2307                             IRBuilderBase &Builder) {
2308   assert(VF.isVector() && "only vector VFs are supported");
2309 
2310   // Create and check the types.
2311   auto *ValVTy = cast<VectorType>(Val->getType());
2312   ElementCount VLen = ValVTy->getElementCount();
2313 
2314   Type *STy = Val->getType()->getScalarType();
2315   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2316          "Induction Step must be an integer or FP");
2317   assert(Step->getType() == STy && "Step has wrong type");
2318 
2319   SmallVector<Constant *, 8> Indices;
2320 
2321   // Create a vector of consecutive numbers from zero to VF.
2322   VectorType *InitVecValVTy = ValVTy;
2323   if (STy->isFloatingPointTy()) {
2324     Type *InitVecValSTy =
2325         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2326     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2327   }
2328   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2329 
2330   // Splat the StartIdx
2331   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2332 
2333   if (STy->isIntegerTy()) {
2334     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2335     Step = Builder.CreateVectorSplat(VLen, Step);
2336     assert(Step->getType() == Val->getType() && "Invalid step vec");
2337     // FIXME: The newly created binary instructions should contain nsw/nuw
2338     // flags, which can be found from the original scalar operations.
2339     Step = Builder.CreateMul(InitVec, Step);
2340     return Builder.CreateAdd(Val, Step, "induction");
2341   }
2342 
2343   // Floating point induction.
2344   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2345          "Binary Opcode should be specified for FP induction");
2346   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2347   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2348 
2349   Step = Builder.CreateVectorSplat(VLen, Step);
2350   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2351   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2352 }
2353 
2354 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2355 /// variable on which to base the steps, \p Step is the size of the step.
2356 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2357                              const InductionDescriptor &ID, VPValue *Def,
2358                              VPTransformState &State) {
2359   IRBuilderBase &Builder = State.Builder;
2360   // We shouldn't have to build scalar steps if we aren't vectorizing.
2361   assert(State.VF.isVector() && "VF should be greater than one");
2362   // Get the value type and ensure it and the step have the same integer type.
2363   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2364   assert(ScalarIVTy == Step->getType() &&
2365          "Val and Step should have the same type");
2366 
2367   // We build scalar steps for both integer and floating-point induction
2368   // variables. Here, we determine the kind of arithmetic we will perform.
2369   Instruction::BinaryOps AddOp;
2370   Instruction::BinaryOps MulOp;
2371   if (ScalarIVTy->isIntegerTy()) {
2372     AddOp = Instruction::Add;
2373     MulOp = Instruction::Mul;
2374   } else {
2375     AddOp = ID.getInductionOpcode();
2376     MulOp = Instruction::FMul;
2377   }
2378 
2379   // Determine the number of scalars we need to generate for each unroll
2380   // iteration.
2381   bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2382   unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2383   // Compute the scalar steps and save the results in State.
2384   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2385                                      ScalarIVTy->getScalarSizeInBits());
2386   Type *VecIVTy = nullptr;
2387   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2388   if (!FirstLaneOnly && State.VF.isScalable()) {
2389     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2390     UnitStepVec =
2391         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2392     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2393     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2394   }
2395 
2396   for (unsigned Part = 0; Part < State.UF; ++Part) {
2397     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2398 
2399     if (!FirstLaneOnly && State.VF.isScalable()) {
2400       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2401       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2402       if (ScalarIVTy->isFloatingPointTy())
2403         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2404       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2405       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2406       State.set(Def, Add, Part);
2407       // It's useful to record the lane values too for the known minimum number
2408       // of elements so we do those below. This improves the code quality when
2409       // trying to extract the first element, for example.
2410     }
2411 
2412     if (ScalarIVTy->isFloatingPointTy())
2413       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2414 
2415     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2416       Value *StartIdx = Builder.CreateBinOp(
2417           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2418       // The step returned by `createStepForVF` is a runtime-evaluated value
2419       // when VF is scalable. Otherwise, it should be folded into a Constant.
2420       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2421              "Expected StartIdx to be folded to a constant when VF is not "
2422              "scalable");
2423       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2424       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2425       State.set(Def, Add, VPIteration(Part, Lane));
2426     }
2427   }
2428 }
2429 
2430 // Generate code for the induction step. Note that induction steps are
2431 // required to be loop-invariant
2432 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2433                               Instruction *InsertBefore,
2434                               Loop *OrigLoop = nullptr) {
2435   const DataLayout &DL = SE.getDataLayout();
2436   assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2437          "Induction step should be loop invariant");
2438   if (auto *E = dyn_cast<SCEVUnknown>(Step))
2439     return E->getValue();
2440 
2441   SCEVExpander Exp(SE, DL, "induction");
2442   return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2443 }
2444 
2445 /// Compute the transformed value of Index at offset StartValue using step
2446 /// StepValue.
2447 /// For integer induction, returns StartValue + Index * StepValue.
2448 /// For pointer induction, returns StartValue[Index * StepValue].
2449 /// FIXME: The newly created binary instructions should contain nsw/nuw
2450 /// flags, which can be found from the original scalar operations.
2451 static Value *emitTransformedIndex(IRBuilderBase &B, Value *Index,
2452                                    Value *StartValue, Value *Step,
2453                                    const InductionDescriptor &ID) {
2454   assert(Index->getType()->getScalarType() == Step->getType() &&
2455          "Index scalar type does not match StepValue type");
2456 
2457   // Note: the IR at this point is broken. We cannot use SE to create any new
2458   // SCEV and then expand it, hoping that SCEV's simplification will give us
2459   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2460   // lead to various SCEV crashes. So all we can do is to use builder and rely
2461   // on InstCombine for future simplifications. Here we handle some trivial
2462   // cases only.
2463   auto CreateAdd = [&B](Value *X, Value *Y) {
2464     assert(X->getType() == Y->getType() && "Types don't match!");
2465     if (auto *CX = dyn_cast<ConstantInt>(X))
2466       if (CX->isZero())
2467         return Y;
2468     if (auto *CY = dyn_cast<ConstantInt>(Y))
2469       if (CY->isZero())
2470         return X;
2471     return B.CreateAdd(X, Y);
2472   };
2473 
2474   // We allow X to be a vector type, in which case Y will potentially be
2475   // splatted into a vector with the same element count.
2476   auto CreateMul = [&B](Value *X, Value *Y) {
2477     assert(X->getType()->getScalarType() == Y->getType() &&
2478            "Types don't match!");
2479     if (auto *CX = dyn_cast<ConstantInt>(X))
2480       if (CX->isOne())
2481         return Y;
2482     if (auto *CY = dyn_cast<ConstantInt>(Y))
2483       if (CY->isOne())
2484         return X;
2485     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2486     if (XVTy && !isa<VectorType>(Y->getType()))
2487       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2488     return B.CreateMul(X, Y);
2489   };
2490 
2491   switch (ID.getKind()) {
2492   case InductionDescriptor::IK_IntInduction: {
2493     assert(!isa<VectorType>(Index->getType()) &&
2494            "Vector indices not supported for integer inductions yet");
2495     assert(Index->getType() == StartValue->getType() &&
2496            "Index type does not match StartValue type");
2497     if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2498       return B.CreateSub(StartValue, Index);
2499     auto *Offset = CreateMul(Index, Step);
2500     return CreateAdd(StartValue, Offset);
2501   }
2502   case InductionDescriptor::IK_PtrInduction: {
2503     assert(isa<Constant>(Step) &&
2504            "Expected constant step for pointer induction");
2505     return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2506   }
2507   case InductionDescriptor::IK_FpInduction: {
2508     assert(!isa<VectorType>(Index->getType()) &&
2509            "Vector indices not supported for FP inductions yet");
2510     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2511     auto InductionBinOp = ID.getInductionBinOp();
2512     assert(InductionBinOp &&
2513            (InductionBinOp->getOpcode() == Instruction::FAdd ||
2514             InductionBinOp->getOpcode() == Instruction::FSub) &&
2515            "Original bin op should be defined for FP induction");
2516 
2517     Value *MulExp = B.CreateFMul(Step, Index);
2518     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2519                          "induction");
2520   }
2521   case InductionDescriptor::IK_NoInduction:
2522     return nullptr;
2523   }
2524   llvm_unreachable("invalid enum");
2525 }
2526 
2527 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2528                                                     const VPIteration &Instance,
2529                                                     VPTransformState &State) {
2530   Value *ScalarInst = State.get(Def, Instance);
2531   Value *VectorValue = State.get(Def, Instance.Part);
2532   VectorValue = Builder.CreateInsertElement(
2533       VectorValue, ScalarInst,
2534       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2535   State.set(Def, VectorValue, Instance.Part);
2536 }
2537 
2538 // Return whether we allow using masked interleave-groups (for dealing with
2539 // strided loads/stores that reside in predicated blocks, or for dealing
2540 // with gaps).
2541 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2542   // If an override option has been passed in for interleaved accesses, use it.
2543   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2544     return EnableMaskedInterleavedMemAccesses;
2545 
2546   return TTI.enableMaskedInterleavedAccessVectorization();
2547 }
2548 
2549 // Try to vectorize the interleave group that \p Instr belongs to.
2550 //
2551 // E.g. Translate following interleaved load group (factor = 3):
2552 //   for (i = 0; i < N; i+=3) {
2553 //     R = Pic[i];             // Member of index 0
2554 //     G = Pic[i+1];           // Member of index 1
2555 //     B = Pic[i+2];           // Member of index 2
2556 //     ... // do something to R, G, B
2557 //   }
2558 // To:
2559 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2560 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2561 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2562 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2563 //
2564 // Or translate following interleaved store group (factor = 3):
2565 //   for (i = 0; i < N; i+=3) {
2566 //     ... do something to R, G, B
2567 //     Pic[i]   = R;           // Member of index 0
2568 //     Pic[i+1] = G;           // Member of index 1
2569 //     Pic[i+2] = B;           // Member of index 2
2570 //   }
2571 // To:
2572 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2573 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2574 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2575 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2576 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2577 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2578     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2579     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2580     VPValue *BlockInMask) {
2581   Instruction *Instr = Group->getInsertPos();
2582   const DataLayout &DL = Instr->getModule()->getDataLayout();
2583 
2584   // Prepare for the vector type of the interleaved load/store.
2585   Type *ScalarTy = getLoadStoreType(Instr);
2586   unsigned InterleaveFactor = Group->getFactor();
2587   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2588   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2589 
2590   // Prepare for the new pointers.
2591   SmallVector<Value *, 2> AddrParts;
2592   unsigned Index = Group->getIndex(Instr);
2593 
2594   // TODO: extend the masked interleaved-group support to reversed access.
2595   assert((!BlockInMask || !Group->isReverse()) &&
2596          "Reversed masked interleave-group not supported.");
2597 
2598   // If the group is reverse, adjust the index to refer to the last vector lane
2599   // instead of the first. We adjust the index from the first vector lane,
2600   // rather than directly getting the pointer for lane VF - 1, because the
2601   // pointer operand of the interleaved access is supposed to be uniform. For
2602   // uniform instructions, we're only required to generate a value for the
2603   // first vector lane in each unroll iteration.
2604   if (Group->isReverse())
2605     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2606 
2607   for (unsigned Part = 0; Part < UF; Part++) {
2608     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2609     setDebugLocFromInst(AddrPart);
2610 
2611     // Notice current instruction could be any index. Need to adjust the address
2612     // to the member of index 0.
2613     //
2614     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2615     //       b = A[i];       // Member of index 0
2616     // Current pointer is pointed to A[i+1], adjust it to A[i].
2617     //
2618     // E.g.  A[i+1] = a;     // Member of index 1
2619     //       A[i]   = b;     // Member of index 0
2620     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2621     // Current pointer is pointed to A[i+2], adjust it to A[i].
2622 
2623     bool InBounds = false;
2624     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2625       InBounds = gep->isInBounds();
2626     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2627     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2628 
2629     // Cast to the vector pointer type.
2630     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2631     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2632     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2633   }
2634 
2635   setDebugLocFromInst(Instr);
2636   Value *PoisonVec = PoisonValue::get(VecTy);
2637 
2638   Value *MaskForGaps = nullptr;
2639   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2640     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2641     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2642   }
2643 
2644   // Vectorize the interleaved load group.
2645   if (isa<LoadInst>(Instr)) {
2646     // For each unroll part, create a wide load for the group.
2647     SmallVector<Value *, 2> NewLoads;
2648     for (unsigned Part = 0; Part < UF; Part++) {
2649       Instruction *NewLoad;
2650       if (BlockInMask || MaskForGaps) {
2651         assert(useMaskedInterleavedAccesses(*TTI) &&
2652                "masked interleaved groups are not allowed.");
2653         Value *GroupMask = MaskForGaps;
2654         if (BlockInMask) {
2655           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2656           Value *ShuffledMask = Builder.CreateShuffleVector(
2657               BlockInMaskPart,
2658               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2659               "interleaved.mask");
2660           GroupMask = MaskForGaps
2661                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2662                                                 MaskForGaps)
2663                           : ShuffledMask;
2664         }
2665         NewLoad =
2666             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2667                                      GroupMask, PoisonVec, "wide.masked.vec");
2668       }
2669       else
2670         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2671                                             Group->getAlign(), "wide.vec");
2672       Group->addMetadata(NewLoad);
2673       NewLoads.push_back(NewLoad);
2674     }
2675 
2676     // For each member in the group, shuffle out the appropriate data from the
2677     // wide loads.
2678     unsigned J = 0;
2679     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2680       Instruction *Member = Group->getMember(I);
2681 
2682       // Skip the gaps in the group.
2683       if (!Member)
2684         continue;
2685 
2686       auto StrideMask =
2687           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2688       for (unsigned Part = 0; Part < UF; Part++) {
2689         Value *StridedVec = Builder.CreateShuffleVector(
2690             NewLoads[Part], StrideMask, "strided.vec");
2691 
2692         // If this member has different type, cast the result type.
2693         if (Member->getType() != ScalarTy) {
2694           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2695           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2696           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2697         }
2698 
2699         if (Group->isReverse())
2700           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2701 
2702         State.set(VPDefs[J], StridedVec, Part);
2703       }
2704       ++J;
2705     }
2706     return;
2707   }
2708 
2709   // The sub vector type for current instruction.
2710   auto *SubVT = VectorType::get(ScalarTy, VF);
2711 
2712   // Vectorize the interleaved store group.
2713   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2714   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2715          "masked interleaved groups are not allowed.");
2716   assert((!MaskForGaps || !VF.isScalable()) &&
2717          "masking gaps for scalable vectors is not yet supported.");
2718   for (unsigned Part = 0; Part < UF; Part++) {
2719     // Collect the stored vector from each member.
2720     SmallVector<Value *, 4> StoredVecs;
2721     for (unsigned i = 0; i < InterleaveFactor; i++) {
2722       assert((Group->getMember(i) || MaskForGaps) &&
2723              "Fail to get a member from an interleaved store group");
2724       Instruction *Member = Group->getMember(i);
2725 
2726       // Skip the gaps in the group.
2727       if (!Member) {
2728         Value *Undef = PoisonValue::get(SubVT);
2729         StoredVecs.push_back(Undef);
2730         continue;
2731       }
2732 
2733       Value *StoredVec = State.get(StoredValues[i], Part);
2734 
2735       if (Group->isReverse())
2736         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2737 
2738       // If this member has different type, cast it to a unified type.
2739 
2740       if (StoredVec->getType() != SubVT)
2741         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2742 
2743       StoredVecs.push_back(StoredVec);
2744     }
2745 
2746     // Concatenate all vectors into a wide vector.
2747     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2748 
2749     // Interleave the elements in the wide vector.
2750     Value *IVec = Builder.CreateShuffleVector(
2751         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2752         "interleaved.vec");
2753 
2754     Instruction *NewStoreInstr;
2755     if (BlockInMask || MaskForGaps) {
2756       Value *GroupMask = MaskForGaps;
2757       if (BlockInMask) {
2758         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2759         Value *ShuffledMask = Builder.CreateShuffleVector(
2760             BlockInMaskPart,
2761             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2762             "interleaved.mask");
2763         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2764                                                       ShuffledMask, MaskForGaps)
2765                                 : ShuffledMask;
2766       }
2767       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2768                                                 Group->getAlign(), GroupMask);
2769     } else
2770       NewStoreInstr =
2771           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2772 
2773     Group->addMetadata(NewStoreInstr);
2774   }
2775 }
2776 
2777 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2778                                                VPReplicateRecipe *RepRecipe,
2779                                                const VPIteration &Instance,
2780                                                bool IfPredicateInstr,
2781                                                VPTransformState &State) {
2782   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2783 
2784   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2785   // the first lane and part.
2786   if (isa<NoAliasScopeDeclInst>(Instr))
2787     if (!Instance.isFirstIteration())
2788       return;
2789 
2790   setDebugLocFromInst(Instr);
2791 
2792   // Does this instruction return a value ?
2793   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2794 
2795   Instruction *Cloned = Instr->clone();
2796   if (!IsVoidRetTy)
2797     Cloned->setName(Instr->getName() + ".cloned");
2798 
2799   // If the scalarized instruction contributes to the address computation of a
2800   // widen masked load/store which was in a basic block that needed predication
2801   // and is not predicated after vectorization, we can't propagate
2802   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2803   // instruction could feed a poison value to the base address of the widen
2804   // load/store.
2805   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2806     Cloned->dropPoisonGeneratingFlags();
2807 
2808   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
2809                                Builder.GetInsertPoint());
2810   // Replace the operands of the cloned instructions with their scalar
2811   // equivalents in the new loop.
2812   for (auto &I : enumerate(RepRecipe->operands())) {
2813     auto InputInstance = Instance;
2814     VPValue *Operand = I.value();
2815     VPReplicateRecipe *OperandR = dyn_cast<VPReplicateRecipe>(Operand);
2816     if (OperandR && OperandR->isUniform())
2817       InputInstance.Lane = VPLane::getFirstLane();
2818     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2819   }
2820   addNewMetadata(Cloned, Instr);
2821 
2822   // Place the cloned scalar in the new loop.
2823   Builder.Insert(Cloned);
2824 
2825   State.set(RepRecipe, Cloned, Instance);
2826 
2827   // If we just cloned a new assumption, add it the assumption cache.
2828   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2829     AC->registerAssumption(II);
2830 
2831   // End if-block.
2832   if (IfPredicateInstr)
2833     PredicatedInstructions.push_back(Cloned);
2834 }
2835 
2836 void InnerLoopVectorizer::createHeaderBranch(Loop *L) {
2837   BasicBlock *Header = L->getHeader();
2838   assert(!L->getLoopLatch() && "loop should not have a latch at this point");
2839 
2840   IRBuilder<> B(Header->getTerminator());
2841   Instruction *OldInst =
2842       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
2843   setDebugLocFromInst(OldInst, &B);
2844 
2845   // Connect the header to the exit and header blocks and replace the old
2846   // terminator.
2847   B.CreateCondBr(B.getTrue(), L->getUniqueExitBlock(), Header);
2848 
2849   // Now we have two terminators. Remove the old one from the block.
2850   Header->getTerminator()->eraseFromParent();
2851 }
2852 
2853 Value *InnerLoopVectorizer::getOrCreateTripCount(BasicBlock *InsertBlock) {
2854   if (TripCount)
2855     return TripCount;
2856 
2857   assert(InsertBlock);
2858   IRBuilder<> Builder(InsertBlock->getTerminator());
2859   // Find the loop boundaries.
2860   ScalarEvolution *SE = PSE.getSE();
2861   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2862   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2863          "Invalid loop count");
2864 
2865   Type *IdxTy = Legal->getWidestInductionType();
2866   assert(IdxTy && "No type for induction");
2867 
2868   // The exit count might have the type of i64 while the phi is i32. This can
2869   // happen if we have an induction variable that is sign extended before the
2870   // compare. The only way that we get a backedge taken count is that the
2871   // induction variable was signed and as such will not overflow. In such a case
2872   // truncation is legal.
2873   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2874       IdxTy->getPrimitiveSizeInBits())
2875     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2876   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2877 
2878   // Get the total trip count from the count by adding 1.
2879   const SCEV *ExitCount = SE->getAddExpr(
2880       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2881 
2882   const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2883 
2884   // Expand the trip count and place the new instructions in the preheader.
2885   // Notice that the pre-header does not change, only the loop body.
2886   SCEVExpander Exp(*SE, DL, "induction");
2887 
2888   // Count holds the overall loop count (N).
2889   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2890                                 InsertBlock->getTerminator());
2891 
2892   if (TripCount->getType()->isPointerTy())
2893     TripCount =
2894         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2895                                     InsertBlock->getTerminator());
2896 
2897   return TripCount;
2898 }
2899 
2900 Value *
2901 InnerLoopVectorizer::getOrCreateVectorTripCount(BasicBlock *InsertBlock) {
2902   if (VectorTripCount)
2903     return VectorTripCount;
2904 
2905   Value *TC = getOrCreateTripCount(InsertBlock);
2906   IRBuilder<> Builder(InsertBlock->getTerminator());
2907 
2908   Type *Ty = TC->getType();
2909   // This is where we can make the step a runtime constant.
2910   Value *Step = createStepForVF(Builder, Ty, VF, UF);
2911 
2912   // If the tail is to be folded by masking, round the number of iterations N
2913   // up to a multiple of Step instead of rounding down. This is done by first
2914   // adding Step-1 and then rounding down. Note that it's ok if this addition
2915   // overflows: the vector induction variable will eventually wrap to zero given
2916   // that it starts at zero and its Step is a power of two; the loop will then
2917   // exit, with the last early-exit vector comparison also producing all-true.
2918   if (Cost->foldTailByMasking()) {
2919     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2920            "VF*UF must be a power of 2 when folding tail by masking");
2921     Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2922     TC = Builder.CreateAdd(
2923         TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2924   }
2925 
2926   // Now we need to generate the expression for the part of the loop that the
2927   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2928   // iterations are not required for correctness, or N - Step, otherwise. Step
2929   // is equal to the vectorization factor (number of SIMD elements) times the
2930   // unroll factor (number of SIMD instructions).
2931   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2932 
2933   // There are cases where we *must* run at least one iteration in the remainder
2934   // loop.  See the cost model for when this can happen.  If the step evenly
2935   // divides the trip count, we set the remainder to be equal to the step. If
2936   // the step does not evenly divide the trip count, no adjustment is necessary
2937   // since there will already be scalar iterations. Note that the minimum
2938   // iterations check ensures that N >= Step.
2939   if (Cost->requiresScalarEpilogue(VF)) {
2940     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2941     R = Builder.CreateSelect(IsZero, Step, R);
2942   }
2943 
2944   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2945 
2946   return VectorTripCount;
2947 }
2948 
2949 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2950                                                    const DataLayout &DL) {
2951   // Verify that V is a vector type with same number of elements as DstVTy.
2952   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2953   unsigned VF = DstFVTy->getNumElements();
2954   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2955   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2956   Type *SrcElemTy = SrcVecTy->getElementType();
2957   Type *DstElemTy = DstFVTy->getElementType();
2958   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2959          "Vector elements must have same size");
2960 
2961   // Do a direct cast if element types are castable.
2962   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2963     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2964   }
2965   // V cannot be directly casted to desired vector type.
2966   // May happen when V is a floating point vector but DstVTy is a vector of
2967   // pointers or vice-versa. Handle this using a two-step bitcast using an
2968   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2969   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2970          "Only one type should be a pointer type");
2971   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2972          "Only one type should be a floating point type");
2973   Type *IntTy =
2974       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2975   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2976   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2977   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2978 }
2979 
2980 void InnerLoopVectorizer::emitMinimumIterationCountCheck(BasicBlock *Bypass) {
2981   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
2982   // Reuse existing vector loop preheader for TC checks.
2983   // Note that new preheader block is generated for vector loop.
2984   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2985   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2986 
2987   // Generate code to check if the loop's trip count is less than VF * UF, or
2988   // equal to it in case a scalar epilogue is required; this implies that the
2989   // vector trip count is zero. This check also covers the case where adding one
2990   // to the backedge-taken count overflowed leading to an incorrect trip count
2991   // of zero. In this case we will also jump to the scalar loop.
2992   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
2993                                             : ICmpInst::ICMP_ULT;
2994 
2995   // If tail is to be folded, vector loop takes care of all iterations.
2996   Value *CheckMinIters = Builder.getFalse();
2997   if (!Cost->foldTailByMasking()) {
2998     Value *Step = createStepForVF(Builder, Count->getType(), VF, UF);
2999     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3000   }
3001   // Create new preheader for vector loop.
3002   LoopVectorPreHeader =
3003       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3004                  "vector.ph");
3005 
3006   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3007                                DT->getNode(Bypass)->getIDom()) &&
3008          "TC check is expected to dominate Bypass");
3009 
3010   // Update dominator for Bypass & LoopExit (if needed).
3011   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3012   if (!Cost->requiresScalarEpilogue(VF))
3013     // If there is an epilogue which must run, there's no edge from the
3014     // middle block to exit blocks  and thus no need to update the immediate
3015     // dominator of the exit blocks.
3016     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3017 
3018   ReplaceInstWithInst(
3019       TCCheckBlock->getTerminator(),
3020       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3021   LoopBypassBlocks.push_back(TCCheckBlock);
3022 }
3023 
3024 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(BasicBlock *Bypass) {
3025 
3026   BasicBlock *const SCEVCheckBlock =
3027       RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3028   if (!SCEVCheckBlock)
3029     return nullptr;
3030 
3031   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3032            (OptForSizeBasedOnProfile &&
3033             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3034          "Cannot SCEV check stride or overflow when optimizing for size");
3035 
3036 
3037   // Update dominator only if this is first RT check.
3038   if (LoopBypassBlocks.empty()) {
3039     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3040     if (!Cost->requiresScalarEpilogue(VF))
3041       // If there is an epilogue which must run, there's no edge from the
3042       // middle block to exit blocks  and thus no need to update the immediate
3043       // dominator of the exit blocks.
3044       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3045   }
3046 
3047   LoopBypassBlocks.push_back(SCEVCheckBlock);
3048   AddedSafetyChecks = true;
3049   return SCEVCheckBlock;
3050 }
3051 
3052 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(BasicBlock *Bypass) {
3053   // VPlan-native path does not do any analysis for runtime checks currently.
3054   if (EnableVPlanNativePath)
3055     return nullptr;
3056 
3057   BasicBlock *const MemCheckBlock =
3058       RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3059 
3060   // Check if we generated code that checks in runtime if arrays overlap. We put
3061   // the checks into a separate block to make the more common case of few
3062   // elements faster.
3063   if (!MemCheckBlock)
3064     return nullptr;
3065 
3066   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3067     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3068            "Cannot emit memory checks when optimizing for size, unless forced "
3069            "to vectorize.");
3070     ORE->emit([&]() {
3071       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3072                                         OrigLoop->getStartLoc(),
3073                                         OrigLoop->getHeader())
3074              << "Code-size may be reduced by not forcing "
3075                 "vectorization, or by source-code modifications "
3076                 "eliminating the need for runtime checks "
3077                 "(e.g., adding 'restrict').";
3078     });
3079   }
3080 
3081   LoopBypassBlocks.push_back(MemCheckBlock);
3082 
3083   AddedSafetyChecks = true;
3084 
3085   // We currently don't use LoopVersioning for the actual loop cloning but we
3086   // still use it to add the noalias metadata.
3087   LVer = std::make_unique<LoopVersioning>(
3088       *Legal->getLAI(),
3089       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3090       DT, PSE.getSE());
3091   LVer->prepareNoAliasMetadata();
3092   return MemCheckBlock;
3093 }
3094 
3095 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3096   LoopScalarBody = OrigLoop->getHeader();
3097   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3098   assert(LoopVectorPreHeader && "Invalid loop structure");
3099   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3100   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3101          "multiple exit loop without required epilogue?");
3102 
3103   LoopMiddleBlock =
3104       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3105                  LI, nullptr, Twine(Prefix) + "middle.block");
3106   LoopScalarPreHeader =
3107       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3108                  nullptr, Twine(Prefix) + "scalar.ph");
3109 
3110   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3111 
3112   // Set up the middle block terminator.  Two cases:
3113   // 1) If we know that we must execute the scalar epilogue, emit an
3114   //    unconditional branch.
3115   // 2) Otherwise, we must have a single unique exit block (due to how we
3116   //    implement the multiple exit case).  In this case, set up a conditonal
3117   //    branch from the middle block to the loop scalar preheader, and the
3118   //    exit block.  completeLoopSkeleton will update the condition to use an
3119   //    iteration check, if required to decide whether to execute the remainder.
3120   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3121     BranchInst::Create(LoopScalarPreHeader) :
3122     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3123                        Builder.getTrue());
3124   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3125   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3126 
3127   // We intentionally don't let SplitBlock to update LoopInfo since
3128   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3129   // LoopVectorBody is explicitly added to the correct place few lines later.
3130   BasicBlock *LoopVectorBody =
3131       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3132                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3133 
3134   // Update dominator for loop exit.
3135   if (!Cost->requiresScalarEpilogue(VF))
3136     // If there is an epilogue which must run, there's no edge from the
3137     // middle block to exit blocks  and thus no need to update the immediate
3138     // dominator of the exit blocks.
3139     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3140 
3141   // Create and register the new vector loop.
3142   Loop *Lp = LI->AllocateLoop();
3143   Loop *ParentLoop = OrigLoop->getParentLoop();
3144 
3145   // Insert the new loop into the loop nest and register the new basic blocks
3146   // before calling any utilities such as SCEV that require valid LoopInfo.
3147   if (ParentLoop) {
3148     ParentLoop->addChildLoop(Lp);
3149   } else {
3150     LI->addTopLevelLoop(Lp);
3151   }
3152   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3153   return Lp;
3154 }
3155 
3156 void InnerLoopVectorizer::createInductionResumeValues(
3157     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3158   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3159           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3160          "Inconsistent information about additional bypass.");
3161 
3162   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3163   assert(VectorTripCount && "Expected valid arguments");
3164   // We are going to resume the execution of the scalar loop.
3165   // Go over all of the induction variables that we found and fix the
3166   // PHIs that are left in the scalar version of the loop.
3167   // The starting values of PHI nodes depend on the counter of the last
3168   // iteration in the vectorized loop.
3169   // If we come from a bypass edge then we need to start from the original
3170   // start value.
3171   Instruction *OldInduction = Legal->getPrimaryInduction();
3172   for (auto &InductionEntry : Legal->getInductionVars()) {
3173     PHINode *OrigPhi = InductionEntry.first;
3174     InductionDescriptor II = InductionEntry.second;
3175 
3176     // Create phi nodes to merge from the  backedge-taken check block.
3177     PHINode *BCResumeVal =
3178         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3179                         LoopScalarPreHeader->getTerminator());
3180     // Copy original phi DL over to the new one.
3181     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3182     Value *&EndValue = IVEndValues[OrigPhi];
3183     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3184     if (OrigPhi == OldInduction) {
3185       // We know what the end value is.
3186       EndValue = VectorTripCount;
3187     } else {
3188       IRBuilder<> B(LoopVectorPreHeader->getTerminator());
3189 
3190       // Fast-math-flags propagate from the original induction instruction.
3191       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3192         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3193 
3194       Type *StepType = II.getStep()->getType();
3195       Instruction::CastOps CastOp =
3196           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3197       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3198       Value *Step =
3199           CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3200       EndValue = emitTransformedIndex(B, CRD, II.getStartValue(), Step, II);
3201       EndValue->setName("ind.end");
3202 
3203       // Compute the end value for the additional bypass (if applicable).
3204       if (AdditionalBypass.first) {
3205         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3206         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3207                                          StepType, true);
3208         Value *Step =
3209             CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3210         CRD =
3211             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3212         EndValueFromAdditionalBypass =
3213             emitTransformedIndex(B, CRD, II.getStartValue(), Step, II);
3214         EndValueFromAdditionalBypass->setName("ind.end");
3215       }
3216     }
3217     // The new PHI merges the original incoming value, in case of a bypass,
3218     // or the value at the end of the vectorized loop.
3219     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3220 
3221     // Fix the scalar body counter (PHI node).
3222     // The old induction's phi node in the scalar body needs the truncated
3223     // value.
3224     for (BasicBlock *BB : LoopBypassBlocks)
3225       BCResumeVal->addIncoming(II.getStartValue(), BB);
3226 
3227     if (AdditionalBypass.first)
3228       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3229                                             EndValueFromAdditionalBypass);
3230 
3231     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3232   }
3233 }
3234 
3235 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(MDNode *OrigLoopID) {
3236   // The trip counts should be cached by now.
3237   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
3238   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3239 
3240   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3241 
3242   // Add a check in the middle block to see if we have completed
3243   // all of the iterations in the first vector loop.  Three cases:
3244   // 1) If we require a scalar epilogue, there is no conditional branch as
3245   //    we unconditionally branch to the scalar preheader.  Do nothing.
3246   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3247   //    Thus if tail is to be folded, we know we don't need to run the
3248   //    remainder and we can use the previous value for the condition (true).
3249   // 3) Otherwise, construct a runtime check.
3250   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3251     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3252                                         Count, VectorTripCount, "cmp.n",
3253                                         LoopMiddleBlock->getTerminator());
3254 
3255     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3256     // of the corresponding compare because they may have ended up with
3257     // different line numbers and we want to avoid awkward line stepping while
3258     // debugging. Eg. if the compare has got a line number inside the loop.
3259     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3260     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3261   }
3262 
3263 #ifdef EXPENSIVE_CHECKS
3264   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3265   LI->verify(*DT);
3266 #endif
3267 
3268   return LoopVectorPreHeader;
3269 }
3270 
3271 std::pair<BasicBlock *, Value *>
3272 InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3273   /*
3274    In this function we generate a new loop. The new loop will contain
3275    the vectorized instructions while the old loop will continue to run the
3276    scalar remainder.
3277 
3278        [ ] <-- loop iteration number check.
3279     /   |
3280    /    v
3281   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3282   |  /  |
3283   | /   v
3284   ||   [ ]     <-- vector pre header.
3285   |/    |
3286   |     v
3287   |    [  ] \
3288   |    [  ]_|   <-- vector loop.
3289   |     |
3290   |     v
3291   \   -[ ]   <--- middle-block.
3292    \/   |
3293    /\   v
3294    | ->[ ]     <--- new preheader.
3295    |    |
3296  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3297    |   [ ] \
3298    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3299     \   |
3300      \  v
3301       >[ ]     <-- exit block(s).
3302    ...
3303    */
3304 
3305   // Get the metadata of the original loop before it gets modified.
3306   MDNode *OrigLoopID = OrigLoop->getLoopID();
3307 
3308   // Workaround!  Compute the trip count of the original loop and cache it
3309   // before we start modifying the CFG.  This code has a systemic problem
3310   // wherein it tries to run analysis over partially constructed IR; this is
3311   // wrong, and not simply for SCEV.  The trip count of the original loop
3312   // simply happens to be prone to hitting this in practice.  In theory, we
3313   // can hit the same issue for any SCEV, or ValueTracking query done during
3314   // mutation.  See PR49900.
3315   getOrCreateTripCount(OrigLoop->getLoopPreheader());
3316 
3317   // Create an empty vector loop, and prepare basic blocks for the runtime
3318   // checks.
3319   Loop *Lp = createVectorLoopSkeleton("");
3320 
3321   // Now, compare the new count to zero. If it is zero skip the vector loop and
3322   // jump to the scalar loop. This check also covers the case where the
3323   // backedge-taken count is uint##_max: adding one to it will overflow leading
3324   // to an incorrect trip count of zero. In this (rare) case we will also jump
3325   // to the scalar loop.
3326   emitMinimumIterationCountCheck(LoopScalarPreHeader);
3327 
3328   // Generate the code to check any assumptions that we've made for SCEV
3329   // expressions.
3330   emitSCEVChecks(LoopScalarPreHeader);
3331 
3332   // Generate the code that checks in runtime if arrays overlap. We put the
3333   // checks into a separate block to make the more common case of few elements
3334   // faster.
3335   emitMemRuntimeChecks(LoopScalarPreHeader);
3336 
3337   createHeaderBranch(Lp);
3338 
3339   // Emit phis for the new starting index of the scalar loop.
3340   createInductionResumeValues();
3341 
3342   return {completeLoopSkeleton(OrigLoopID), nullptr};
3343 }
3344 
3345 // Fix up external users of the induction variable. At this point, we are
3346 // in LCSSA form, with all external PHIs that use the IV having one input value,
3347 // coming from the remainder loop. We need those PHIs to also have a correct
3348 // value for the IV when arriving directly from the middle block.
3349 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3350                                        const InductionDescriptor &II,
3351                                        Value *CountRoundDown, Value *EndValue,
3352                                        BasicBlock *MiddleBlock,
3353                                        BasicBlock *VectorHeader) {
3354   // There are two kinds of external IV usages - those that use the value
3355   // computed in the last iteration (the PHI) and those that use the penultimate
3356   // value (the value that feeds into the phi from the loop latch).
3357   // We allow both, but they, obviously, have different values.
3358 
3359   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3360 
3361   DenseMap<Value *, Value *> MissingVals;
3362 
3363   // An external user of the last iteration's value should see the value that
3364   // the remainder loop uses to initialize its own IV.
3365   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3366   for (User *U : PostInc->users()) {
3367     Instruction *UI = cast<Instruction>(U);
3368     if (!OrigLoop->contains(UI)) {
3369       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3370       MissingVals[UI] = EndValue;
3371     }
3372   }
3373 
3374   // An external user of the penultimate value need to see EndValue - Step.
3375   // The simplest way to get this is to recompute it from the constituent SCEVs,
3376   // that is Start + (Step * (CRD - 1)).
3377   for (User *U : OrigPhi->users()) {
3378     auto *UI = cast<Instruction>(U);
3379     if (!OrigLoop->contains(UI)) {
3380       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3381 
3382       IRBuilder<> B(MiddleBlock->getTerminator());
3383 
3384       // Fast-math-flags propagate from the original induction instruction.
3385       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3386         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3387 
3388       Value *CountMinusOne = B.CreateSub(
3389           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3390       Value *CMO =
3391           !II.getStep()->getType()->isIntegerTy()
3392               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3393                              II.getStep()->getType())
3394               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3395       CMO->setName("cast.cmo");
3396 
3397       Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3398                                     VectorHeader->getTerminator());
3399       Value *Escape =
3400           emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3401       Escape->setName("ind.escape");
3402       MissingVals[UI] = Escape;
3403     }
3404   }
3405 
3406   for (auto &I : MissingVals) {
3407     PHINode *PHI = cast<PHINode>(I.first);
3408     // One corner case we have to handle is two IVs "chasing" each-other,
3409     // that is %IV2 = phi [...], [ %IV1, %latch ]
3410     // In this case, if IV1 has an external use, we need to avoid adding both
3411     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3412     // don't already have an incoming value for the middle block.
3413     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3414       PHI->addIncoming(I.second, MiddleBlock);
3415   }
3416 }
3417 
3418 namespace {
3419 
3420 struct CSEDenseMapInfo {
3421   static bool canHandle(const Instruction *I) {
3422     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3423            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3424   }
3425 
3426   static inline Instruction *getEmptyKey() {
3427     return DenseMapInfo<Instruction *>::getEmptyKey();
3428   }
3429 
3430   static inline Instruction *getTombstoneKey() {
3431     return DenseMapInfo<Instruction *>::getTombstoneKey();
3432   }
3433 
3434   static unsigned getHashValue(const Instruction *I) {
3435     assert(canHandle(I) && "Unknown instruction!");
3436     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3437                                                            I->value_op_end()));
3438   }
3439 
3440   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3441     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3442         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3443       return LHS == RHS;
3444     return LHS->isIdenticalTo(RHS);
3445   }
3446 };
3447 
3448 } // end anonymous namespace
3449 
3450 ///Perform cse of induction variable instructions.
3451 static void cse(BasicBlock *BB) {
3452   // Perform simple cse.
3453   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3454   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3455     if (!CSEDenseMapInfo::canHandle(&In))
3456       continue;
3457 
3458     // Check if we can replace this instruction with any of the
3459     // visited instructions.
3460     if (Instruction *V = CSEMap.lookup(&In)) {
3461       In.replaceAllUsesWith(V);
3462       In.eraseFromParent();
3463       continue;
3464     }
3465 
3466     CSEMap[&In] = &In;
3467   }
3468 }
3469 
3470 InstructionCost
3471 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3472                                               bool &NeedToScalarize) const {
3473   Function *F = CI->getCalledFunction();
3474   Type *ScalarRetTy = CI->getType();
3475   SmallVector<Type *, 4> Tys, ScalarTys;
3476   for (auto &ArgOp : CI->args())
3477     ScalarTys.push_back(ArgOp->getType());
3478 
3479   // Estimate cost of scalarized vector call. The source operands are assumed
3480   // to be vectors, so we need to extract individual elements from there,
3481   // execute VF scalar calls, and then gather the result into the vector return
3482   // value.
3483   InstructionCost ScalarCallCost =
3484       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3485   if (VF.isScalar())
3486     return ScalarCallCost;
3487 
3488   // Compute corresponding vector type for return value and arguments.
3489   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3490   for (Type *ScalarTy : ScalarTys)
3491     Tys.push_back(ToVectorTy(ScalarTy, VF));
3492 
3493   // Compute costs of unpacking argument values for the scalar calls and
3494   // packing the return values to a vector.
3495   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3496 
3497   InstructionCost Cost =
3498       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3499 
3500   // If we can't emit a vector call for this function, then the currently found
3501   // cost is the cost we need to return.
3502   NeedToScalarize = true;
3503   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3504   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3505 
3506   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3507     return Cost;
3508 
3509   // If the corresponding vector cost is cheaper, return its cost.
3510   InstructionCost VectorCallCost =
3511       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3512   if (VectorCallCost < Cost) {
3513     NeedToScalarize = false;
3514     Cost = VectorCallCost;
3515   }
3516   return Cost;
3517 }
3518 
3519 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3520   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3521     return Elt;
3522   return VectorType::get(Elt, VF);
3523 }
3524 
3525 InstructionCost
3526 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3527                                                    ElementCount VF) const {
3528   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3529   assert(ID && "Expected intrinsic call!");
3530   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3531   FastMathFlags FMF;
3532   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3533     FMF = FPMO->getFastMathFlags();
3534 
3535   SmallVector<const Value *> Arguments(CI->args());
3536   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3537   SmallVector<Type *> ParamTys;
3538   std::transform(FTy->param_begin(), FTy->param_end(),
3539                  std::back_inserter(ParamTys),
3540                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3541 
3542   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3543                                     dyn_cast<IntrinsicInst>(CI));
3544   return TTI.getIntrinsicInstrCost(CostAttrs,
3545                                    TargetTransformInfo::TCK_RecipThroughput);
3546 }
3547 
3548 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3549   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3550   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3551   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3552 }
3553 
3554 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3555   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3556   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3557   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3558 }
3559 
3560 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3561   // For every instruction `I` in MinBWs, truncate the operands, create a
3562   // truncated version of `I` and reextend its result. InstCombine runs
3563   // later and will remove any ext/trunc pairs.
3564   SmallPtrSet<Value *, 4> Erased;
3565   for (const auto &KV : Cost->getMinimalBitwidths()) {
3566     // If the value wasn't vectorized, we must maintain the original scalar
3567     // type. The absence of the value from State indicates that it
3568     // wasn't vectorized.
3569     // FIXME: Should not rely on getVPValue at this point.
3570     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3571     if (!State.hasAnyVectorValue(Def))
3572       continue;
3573     for (unsigned Part = 0; Part < UF; ++Part) {
3574       Value *I = State.get(Def, Part);
3575       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3576         continue;
3577       Type *OriginalTy = I->getType();
3578       Type *ScalarTruncatedTy =
3579           IntegerType::get(OriginalTy->getContext(), KV.second);
3580       auto *TruncatedTy = VectorType::get(
3581           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3582       if (TruncatedTy == OriginalTy)
3583         continue;
3584 
3585       IRBuilder<> B(cast<Instruction>(I));
3586       auto ShrinkOperand = [&](Value *V) -> Value * {
3587         if (auto *ZI = dyn_cast<ZExtInst>(V))
3588           if (ZI->getSrcTy() == TruncatedTy)
3589             return ZI->getOperand(0);
3590         return B.CreateZExtOrTrunc(V, TruncatedTy);
3591       };
3592 
3593       // The actual instruction modification depends on the instruction type,
3594       // unfortunately.
3595       Value *NewI = nullptr;
3596       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3597         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3598                              ShrinkOperand(BO->getOperand(1)));
3599 
3600         // Any wrapping introduced by shrinking this operation shouldn't be
3601         // considered undefined behavior. So, we can't unconditionally copy
3602         // arithmetic wrapping flags to NewI.
3603         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3604       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3605         NewI =
3606             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3607                          ShrinkOperand(CI->getOperand(1)));
3608       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3609         NewI = B.CreateSelect(SI->getCondition(),
3610                               ShrinkOperand(SI->getTrueValue()),
3611                               ShrinkOperand(SI->getFalseValue()));
3612       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3613         switch (CI->getOpcode()) {
3614         default:
3615           llvm_unreachable("Unhandled cast!");
3616         case Instruction::Trunc:
3617           NewI = ShrinkOperand(CI->getOperand(0));
3618           break;
3619         case Instruction::SExt:
3620           NewI = B.CreateSExtOrTrunc(
3621               CI->getOperand(0),
3622               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3623           break;
3624         case Instruction::ZExt:
3625           NewI = B.CreateZExtOrTrunc(
3626               CI->getOperand(0),
3627               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3628           break;
3629         }
3630       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3631         auto Elements0 =
3632             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3633         auto *O0 = B.CreateZExtOrTrunc(
3634             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3635         auto Elements1 =
3636             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3637         auto *O1 = B.CreateZExtOrTrunc(
3638             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3639 
3640         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3641       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3642         // Don't do anything with the operands, just extend the result.
3643         continue;
3644       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3645         auto Elements =
3646             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3647         auto *O0 = B.CreateZExtOrTrunc(
3648             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3649         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3650         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3651       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3652         auto Elements =
3653             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3654         auto *O0 = B.CreateZExtOrTrunc(
3655             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3656         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3657       } else {
3658         // If we don't know what to do, be conservative and don't do anything.
3659         continue;
3660       }
3661 
3662       // Lastly, extend the result.
3663       NewI->takeName(cast<Instruction>(I));
3664       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3665       I->replaceAllUsesWith(Res);
3666       cast<Instruction>(I)->eraseFromParent();
3667       Erased.insert(I);
3668       State.reset(Def, Res, Part);
3669     }
3670   }
3671 
3672   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3673   for (const auto &KV : Cost->getMinimalBitwidths()) {
3674     // If the value wasn't vectorized, we must maintain the original scalar
3675     // type. The absence of the value from State indicates that it
3676     // wasn't vectorized.
3677     // FIXME: Should not rely on getVPValue at this point.
3678     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3679     if (!State.hasAnyVectorValue(Def))
3680       continue;
3681     for (unsigned Part = 0; Part < UF; ++Part) {
3682       Value *I = State.get(Def, Part);
3683       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3684       if (Inst && Inst->use_empty()) {
3685         Value *NewI = Inst->getOperand(0);
3686         Inst->eraseFromParent();
3687         State.reset(Def, NewI, Part);
3688       }
3689     }
3690   }
3691 }
3692 
3693 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
3694   // Insert truncates and extends for any truncated instructions as hints to
3695   // InstCombine.
3696   if (VF.isVector())
3697     truncateToMinimalBitwidths(State);
3698 
3699   // Fix widened non-induction PHIs by setting up the PHI operands.
3700   if (OrigPHIsToFix.size()) {
3701     assert(EnableVPlanNativePath &&
3702            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
3703     fixNonInductionPHIs(State);
3704   }
3705 
3706   // At this point every instruction in the original loop is widened to a
3707   // vector form. Now we need to fix the recurrences in the loop. These PHI
3708   // nodes are currently empty because we did not want to introduce cycles.
3709   // This is the second stage of vectorizing recurrences.
3710   fixCrossIterationPHIs(State);
3711 
3712   // Forget the original basic block.
3713   PSE.getSE()->forgetLoop(OrigLoop);
3714 
3715   Loop *VectorLoop = LI->getLoopFor(State.CFG.PrevBB);
3716   // If we inserted an edge from the middle block to the unique exit block,
3717   // update uses outside the loop (phis) to account for the newly inserted
3718   // edge.
3719   if (!Cost->requiresScalarEpilogue(VF)) {
3720     // Fix-up external users of the induction variables.
3721     for (auto &Entry : Legal->getInductionVars())
3722       fixupIVUsers(Entry.first, Entry.second,
3723                    getOrCreateVectorTripCount(VectorLoop->getLoopPreheader()),
3724                    IVEndValues[Entry.first], LoopMiddleBlock,
3725                    VectorLoop->getHeader());
3726 
3727     fixLCSSAPHIs(State);
3728   }
3729 
3730   for (Instruction *PI : PredicatedInstructions)
3731     sinkScalarOperands(&*PI);
3732 
3733   // Remove redundant induction instructions.
3734   cse(VectorLoop->getHeader());
3735 
3736   // Set/update profile weights for the vector and remainder loops as original
3737   // loop iterations are now distributed among them. Note that original loop
3738   // represented by LoopScalarBody becomes remainder loop after vectorization.
3739   //
3740   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3741   // end up getting slightly roughened result but that should be OK since
3742   // profile is not inherently precise anyway. Note also possible bypass of
3743   // vector code caused by legality checks is ignored, assigning all the weight
3744   // to the vector loop, optimistically.
3745   //
3746   // For scalable vectorization we can't know at compile time how many iterations
3747   // of the loop are handled in one vector iteration, so instead assume a pessimistic
3748   // vscale of '1'.
3749   setProfileInfoAfterUnrolling(LI->getLoopFor(LoopScalarBody), VectorLoop,
3750                                LI->getLoopFor(LoopScalarBody),
3751                                VF.getKnownMinValue() * UF);
3752 }
3753 
3754 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
3755   // In order to support recurrences we need to be able to vectorize Phi nodes.
3756   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3757   // stage #2: We now need to fix the recurrences by adding incoming edges to
3758   // the currently empty PHI nodes. At this point every instruction in the
3759   // original loop is widened to a vector form so we can use them to construct
3760   // the incoming edges.
3761   VPBasicBlock *Header =
3762       State.Plan->getVectorLoopRegion()->getEntryBasicBlock();
3763   for (VPRecipeBase &R : Header->phis()) {
3764     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3765       fixReduction(ReductionPhi, State);
3766     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3767       fixFirstOrderRecurrence(FOR, State);
3768   }
3769 }
3770 
3771 void InnerLoopVectorizer::fixFirstOrderRecurrence(
3772     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
3773   // This is the second phase of vectorizing first-order recurrences. An
3774   // overview of the transformation is described below. Suppose we have the
3775   // following loop.
3776   //
3777   //   for (int i = 0; i < n; ++i)
3778   //     b[i] = a[i] - a[i - 1];
3779   //
3780   // There is a first-order recurrence on "a". For this loop, the shorthand
3781   // scalar IR looks like:
3782   //
3783   //   scalar.ph:
3784   //     s_init = a[-1]
3785   //     br scalar.body
3786   //
3787   //   scalar.body:
3788   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3789   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3790   //     s2 = a[i]
3791   //     b[i] = s2 - s1
3792   //     br cond, scalar.body, ...
3793   //
3794   // In this example, s1 is a recurrence because it's value depends on the
3795   // previous iteration. In the first phase of vectorization, we created a
3796   // vector phi v1 for s1. We now complete the vectorization and produce the
3797   // shorthand vector IR shown below (for VF = 4, UF = 1).
3798   //
3799   //   vector.ph:
3800   //     v_init = vector(..., ..., ..., a[-1])
3801   //     br vector.body
3802   //
3803   //   vector.body
3804   //     i = phi [0, vector.ph], [i+4, vector.body]
3805   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3806   //     v2 = a[i, i+1, i+2, i+3];
3807   //     v3 = vector(v1(3), v2(0, 1, 2))
3808   //     b[i, i+1, i+2, i+3] = v2 - v3
3809   //     br cond, vector.body, middle.block
3810   //
3811   //   middle.block:
3812   //     x = v2(3)
3813   //     br scalar.ph
3814   //
3815   //   scalar.ph:
3816   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3817   //     br scalar.body
3818   //
3819   // After execution completes the vector loop, we extract the next value of
3820   // the recurrence (x) to use as the initial value in the scalar loop.
3821 
3822   // Extract the last vector element in the middle block. This will be the
3823   // initial value for the recurrence when jumping to the scalar loop.
3824   VPValue *PreviousDef = PhiR->getBackedgeValue();
3825   Value *Incoming = State.get(PreviousDef, UF - 1);
3826   auto *ExtractForScalar = Incoming;
3827   auto *IdxTy = Builder.getInt32Ty();
3828   if (VF.isVector()) {
3829     auto *One = ConstantInt::get(IdxTy, 1);
3830     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3831     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3832     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3833     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3834                                                     "vector.recur.extract");
3835   }
3836   // Extract the second last element in the middle block if the
3837   // Phi is used outside the loop. We need to extract the phi itself
3838   // and not the last element (the phi update in the current iteration). This
3839   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3840   // when the scalar loop is not run at all.
3841   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3842   if (VF.isVector()) {
3843     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3844     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3845     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3846         Incoming, Idx, "vector.recur.extract.for.phi");
3847   } else if (UF > 1)
3848     // When loop is unrolled without vectorizing, initialize
3849     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3850     // of `Incoming`. This is analogous to the vectorized case above: extracting
3851     // the second last element when VF > 1.
3852     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3853 
3854   // Fix the initial value of the original recurrence in the scalar loop.
3855   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3856   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3857   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3858   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3859   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3860     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3861     Start->addIncoming(Incoming, BB);
3862   }
3863 
3864   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3865   Phi->setName("scalar.recur");
3866 
3867   // Finally, fix users of the recurrence outside the loop. The users will need
3868   // either the last value of the scalar recurrence or the last value of the
3869   // vector recurrence we extracted in the middle block. Since the loop is in
3870   // LCSSA form, we just need to find all the phi nodes for the original scalar
3871   // recurrence in the exit block, and then add an edge for the middle block.
3872   // Note that LCSSA does not imply single entry when the original scalar loop
3873   // had multiple exiting edges (as we always run the last iteration in the
3874   // scalar epilogue); in that case, there is no edge from middle to exit and
3875   // and thus no phis which needed updated.
3876   if (!Cost->requiresScalarEpilogue(VF))
3877     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3878       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
3879         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3880 }
3881 
3882 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
3883                                        VPTransformState &State) {
3884   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3885   // Get it's reduction variable descriptor.
3886   assert(Legal->isReductionVariable(OrigPhi) &&
3887          "Unable to find the reduction variable");
3888   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3889 
3890   RecurKind RK = RdxDesc.getRecurrenceKind();
3891   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3892   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3893   setDebugLocFromInst(ReductionStartValue);
3894 
3895   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3896   // This is the vector-clone of the value that leaves the loop.
3897   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3898 
3899   // Wrap flags are in general invalid after vectorization, clear them.
3900   clearReductionWrapFlags(RdxDesc, State);
3901 
3902   // Before each round, move the insertion point right between
3903   // the PHIs and the values we are going to write.
3904   // This allows us to write both PHINodes and the extractelement
3905   // instructions.
3906   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3907 
3908   setDebugLocFromInst(LoopExitInst);
3909 
3910   Type *PhiTy = OrigPhi->getType();
3911   BasicBlock *VectorLoopLatch =
3912       LI->getLoopFor(State.CFG.PrevBB)->getLoopLatch();
3913   // If tail is folded by masking, the vector value to leave the loop should be
3914   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3915   // instead of the former. For an inloop reduction the reduction will already
3916   // be predicated, and does not need to be handled here.
3917   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3918     for (unsigned Part = 0; Part < UF; ++Part) {
3919       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3920       Value *Sel = nullptr;
3921       for (User *U : VecLoopExitInst->users()) {
3922         if (isa<SelectInst>(U)) {
3923           assert(!Sel && "Reduction exit feeding two selects");
3924           Sel = U;
3925         } else
3926           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3927       }
3928       assert(Sel && "Reduction exit feeds no select");
3929       State.reset(LoopExitInstDef, Sel, Part);
3930 
3931       // If the target can create a predicated operator for the reduction at no
3932       // extra cost in the loop (for example a predicated vadd), it can be
3933       // cheaper for the select to remain in the loop than be sunk out of it,
3934       // and so use the select value for the phi instead of the old
3935       // LoopExitValue.
3936       if (PreferPredicatedReductionSelect ||
3937           TTI->preferPredicatedReductionSelect(
3938               RdxDesc.getOpcode(), PhiTy,
3939               TargetTransformInfo::ReductionFlags())) {
3940         auto *VecRdxPhi =
3941             cast<PHINode>(State.get(PhiR, Part));
3942         VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3943       }
3944     }
3945   }
3946 
3947   // If the vector reduction can be performed in a smaller type, we truncate
3948   // then extend the loop exit value to enable InstCombine to evaluate the
3949   // entire expression in the smaller type.
3950   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3951     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3952     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3953     Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3954     VectorParts RdxParts(UF);
3955     for (unsigned Part = 0; Part < UF; ++Part) {
3956       RdxParts[Part] = State.get(LoopExitInstDef, Part);
3957       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3958       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3959                                         : Builder.CreateZExt(Trunc, VecTy);
3960       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3961         if (U != Trunc) {
3962           U->replaceUsesOfWith(RdxParts[Part], Extnd);
3963           RdxParts[Part] = Extnd;
3964         }
3965     }
3966     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3967     for (unsigned Part = 0; Part < UF; ++Part) {
3968       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3969       State.reset(LoopExitInstDef, RdxParts[Part], Part);
3970     }
3971   }
3972 
3973   // Reduce all of the unrolled parts into a single vector.
3974   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3975   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3976 
3977   // The middle block terminator has already been assigned a DebugLoc here (the
3978   // OrigLoop's single latch terminator). We want the whole middle block to
3979   // appear to execute on this line because: (a) it is all compiler generated,
3980   // (b) these instructions are always executed after evaluating the latch
3981   // conditional branch, and (c) other passes may add new predecessors which
3982   // terminate on this line. This is the easiest way to ensure we don't
3983   // accidentally cause an extra step back into the loop while debugging.
3984   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
3985   if (PhiR->isOrdered())
3986     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3987   else {
3988     // Floating-point operations should have some FMF to enable the reduction.
3989     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
3990     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
3991     for (unsigned Part = 1; Part < UF; ++Part) {
3992       Value *RdxPart = State.get(LoopExitInstDef, Part);
3993       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3994         ReducedPartRdx = Builder.CreateBinOp(
3995             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3996       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
3997         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3998                                            ReducedPartRdx, RdxPart);
3999       else
4000         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4001     }
4002   }
4003 
4004   // Create the reduction after the loop. Note that inloop reductions create the
4005   // target reduction in the loop using a Reduction recipe.
4006   if (VF.isVector() && !PhiR->isInLoop()) {
4007     ReducedPartRdx =
4008         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
4009     // If the reduction can be performed in a smaller type, we need to extend
4010     // the reduction to the wider type before we branch to the original loop.
4011     if (PhiTy != RdxDesc.getRecurrenceType())
4012       ReducedPartRdx = RdxDesc.isSigned()
4013                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4014                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4015   }
4016 
4017   PHINode *ResumePhi =
4018       dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
4019 
4020   // Create a phi node that merges control-flow from the backedge-taken check
4021   // block and the middle block.
4022   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4023                                         LoopScalarPreHeader->getTerminator());
4024 
4025   // If we are fixing reductions in the epilogue loop then we should already
4026   // have created a bc.merge.rdx Phi after the main vector body. Ensure that
4027   // we carry over the incoming values correctly.
4028   for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
4029     if (Incoming == LoopMiddleBlock)
4030       BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4031     else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4032       BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4033                               Incoming);
4034     else
4035       BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4036   }
4037 
4038   // Set the resume value for this reduction
4039   ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4040 
4041   // Now, we need to fix the users of the reduction variable
4042   // inside and outside of the scalar remainder loop.
4043 
4044   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4045   // in the exit blocks.  See comment on analogous loop in
4046   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4047   if (!Cost->requiresScalarEpilogue(VF))
4048     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4049       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4050         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4051 
4052   // Fix the scalar loop reduction variable with the incoming reduction sum
4053   // from the vector body and from the backedge value.
4054   int IncomingEdgeBlockIdx =
4055       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4056   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4057   // Pick the other block.
4058   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4059   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4060   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4061 }
4062 
4063 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4064                                                   VPTransformState &State) {
4065   RecurKind RK = RdxDesc.getRecurrenceKind();
4066   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4067     return;
4068 
4069   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4070   assert(LoopExitInstr && "null loop exit instruction");
4071   SmallVector<Instruction *, 8> Worklist;
4072   SmallPtrSet<Instruction *, 8> Visited;
4073   Worklist.push_back(LoopExitInstr);
4074   Visited.insert(LoopExitInstr);
4075 
4076   while (!Worklist.empty()) {
4077     Instruction *Cur = Worklist.pop_back_val();
4078     if (isa<OverflowingBinaryOperator>(Cur))
4079       for (unsigned Part = 0; Part < UF; ++Part) {
4080         // FIXME: Should not rely on getVPValue at this point.
4081         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4082         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4083       }
4084 
4085     for (User *U : Cur->users()) {
4086       Instruction *UI = cast<Instruction>(U);
4087       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4088           Visited.insert(UI).second)
4089         Worklist.push_back(UI);
4090     }
4091   }
4092 }
4093 
4094 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4095   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4096     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4097       // Some phis were already hand updated by the reduction and recurrence
4098       // code above, leave them alone.
4099       continue;
4100 
4101     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4102     // Non-instruction incoming values will have only one value.
4103 
4104     VPLane Lane = VPLane::getFirstLane();
4105     if (isa<Instruction>(IncomingValue) &&
4106         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4107                                            VF))
4108       Lane = VPLane::getLastLaneForVF(VF);
4109 
4110     // Can be a loop invariant incoming value or the last scalar value to be
4111     // extracted from the vectorized loop.
4112     // FIXME: Should not rely on getVPValue at this point.
4113     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4114     Value *lastIncomingValue =
4115         OrigLoop->isLoopInvariant(IncomingValue)
4116             ? IncomingValue
4117             : State.get(State.Plan->getVPValue(IncomingValue, true),
4118                         VPIteration(UF - 1, Lane));
4119     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4120   }
4121 }
4122 
4123 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4124   // The basic block and loop containing the predicated instruction.
4125   auto *PredBB = PredInst->getParent();
4126   auto *VectorLoop = LI->getLoopFor(PredBB);
4127 
4128   // Initialize a worklist with the operands of the predicated instruction.
4129   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4130 
4131   // Holds instructions that we need to analyze again. An instruction may be
4132   // reanalyzed if we don't yet know if we can sink it or not.
4133   SmallVector<Instruction *, 8> InstsToReanalyze;
4134 
4135   // Returns true if a given use occurs in the predicated block. Phi nodes use
4136   // their operands in their corresponding predecessor blocks.
4137   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4138     auto *I = cast<Instruction>(U.getUser());
4139     BasicBlock *BB = I->getParent();
4140     if (auto *Phi = dyn_cast<PHINode>(I))
4141       BB = Phi->getIncomingBlock(
4142           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4143     return BB == PredBB;
4144   };
4145 
4146   // Iteratively sink the scalarized operands of the predicated instruction
4147   // into the block we created for it. When an instruction is sunk, it's
4148   // operands are then added to the worklist. The algorithm ends after one pass
4149   // through the worklist doesn't sink a single instruction.
4150   bool Changed;
4151   do {
4152     // Add the instructions that need to be reanalyzed to the worklist, and
4153     // reset the changed indicator.
4154     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4155     InstsToReanalyze.clear();
4156     Changed = false;
4157 
4158     while (!Worklist.empty()) {
4159       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4160 
4161       // We can't sink an instruction if it is a phi node, is not in the loop,
4162       // or may have side effects.
4163       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4164           I->mayHaveSideEffects())
4165         continue;
4166 
4167       // If the instruction is already in PredBB, check if we can sink its
4168       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4169       // sinking the scalar instruction I, hence it appears in PredBB; but it
4170       // may have failed to sink I's operands (recursively), which we try
4171       // (again) here.
4172       if (I->getParent() == PredBB) {
4173         Worklist.insert(I->op_begin(), I->op_end());
4174         continue;
4175       }
4176 
4177       // It's legal to sink the instruction if all its uses occur in the
4178       // predicated block. Otherwise, there's nothing to do yet, and we may
4179       // need to reanalyze the instruction.
4180       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4181         InstsToReanalyze.push_back(I);
4182         continue;
4183       }
4184 
4185       // Move the instruction to the beginning of the predicated block, and add
4186       // it's operands to the worklist.
4187       I->moveBefore(&*PredBB->getFirstInsertionPt());
4188       Worklist.insert(I->op_begin(), I->op_end());
4189 
4190       // The sinking may have enabled other instructions to be sunk, so we will
4191       // need to iterate.
4192       Changed = true;
4193     }
4194   } while (Changed);
4195 }
4196 
4197 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4198   for (PHINode *OrigPhi : OrigPHIsToFix) {
4199     VPWidenPHIRecipe *VPPhi =
4200         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4201     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4202     // Make sure the builder has a valid insert point.
4203     Builder.SetInsertPoint(NewPhi);
4204     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4205       VPValue *Inc = VPPhi->getIncomingValue(i);
4206       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4207       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4208     }
4209   }
4210 }
4211 
4212 bool InnerLoopVectorizer::useOrderedReductions(
4213     const RecurrenceDescriptor &RdxDesc) {
4214   return Cost->useOrderedReductions(RdxDesc);
4215 }
4216 
4217 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4218                                               VPWidenPHIRecipe *PhiR,
4219                                               VPTransformState &State) {
4220   assert(EnableVPlanNativePath &&
4221          "Non-native vplans are not expected to have VPWidenPHIRecipes.");
4222   // Currently we enter here in the VPlan-native path for non-induction
4223   // PHIs where all control flow is uniform. We simply widen these PHIs.
4224   // Create a vector phi with no operands - the vector phi operands will be
4225   // set at the end of vector code generation.
4226   Type *VecTy = (State.VF.isScalar())
4227                     ? PN->getType()
4228                     : VectorType::get(PN->getType(), State.VF);
4229   Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4230   State.set(PhiR, VecPhi, 0);
4231   OrigPHIsToFix.push_back(cast<PHINode>(PN));
4232 }
4233 
4234 /// A helper function for checking whether an integer division-related
4235 /// instruction may divide by zero (in which case it must be predicated if
4236 /// executed conditionally in the scalar code).
4237 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4238 /// Non-zero divisors that are non compile-time constants will not be
4239 /// converted into multiplication, so we will still end up scalarizing
4240 /// the division, but can do so w/o predication.
4241 static bool mayDivideByZero(Instruction &I) {
4242   assert((I.getOpcode() == Instruction::UDiv ||
4243           I.getOpcode() == Instruction::SDiv ||
4244           I.getOpcode() == Instruction::URem ||
4245           I.getOpcode() == Instruction::SRem) &&
4246          "Unexpected instruction");
4247   Value *Divisor = I.getOperand(1);
4248   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4249   return !CInt || CInt->isZero();
4250 }
4251 
4252 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4253                                                VPUser &ArgOperands,
4254                                                VPTransformState &State) {
4255   assert(!isa<DbgInfoIntrinsic>(I) &&
4256          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4257   setDebugLocFromInst(&I);
4258 
4259   Module *M = I.getParent()->getParent()->getParent();
4260   auto *CI = cast<CallInst>(&I);
4261 
4262   SmallVector<Type *, 4> Tys;
4263   for (Value *ArgOperand : CI->args())
4264     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4265 
4266   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4267 
4268   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4269   // version of the instruction.
4270   // Is it beneficial to perform intrinsic call compared to lib call?
4271   bool NeedToScalarize = false;
4272   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4273   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4274   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4275   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4276          "Instruction should be scalarized elsewhere.");
4277   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4278          "Either the intrinsic cost or vector call cost must be valid");
4279 
4280   for (unsigned Part = 0; Part < UF; ++Part) {
4281     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4282     SmallVector<Value *, 4> Args;
4283     for (auto &I : enumerate(ArgOperands.operands())) {
4284       // Some intrinsics have a scalar argument - don't replace it with a
4285       // vector.
4286       Value *Arg;
4287       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
4288         Arg = State.get(I.value(), Part);
4289       else {
4290         Arg = State.get(I.value(), VPIteration(0, 0));
4291         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
4292           TysForDecl.push_back(Arg->getType());
4293       }
4294       Args.push_back(Arg);
4295     }
4296 
4297     Function *VectorF;
4298     if (UseVectorIntrinsic) {
4299       // Use vector version of the intrinsic.
4300       if (VF.isVector())
4301         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4302       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4303       assert(VectorF && "Can't retrieve vector intrinsic.");
4304     } else {
4305       // Use vector version of the function call.
4306       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4307 #ifndef NDEBUG
4308       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4309              "Can't create vector function.");
4310 #endif
4311         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4312     }
4313       SmallVector<OperandBundleDef, 1> OpBundles;
4314       CI->getOperandBundlesAsDefs(OpBundles);
4315       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4316 
4317       if (isa<FPMathOperator>(V))
4318         V->copyFastMathFlags(CI);
4319 
4320       State.set(Def, V, Part);
4321       addMetadata(V, &I);
4322   }
4323 }
4324 
4325 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4326   // We should not collect Scalars more than once per VF. Right now, this
4327   // function is called from collectUniformsAndScalars(), which already does
4328   // this check. Collecting Scalars for VF=1 does not make any sense.
4329   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4330          "This function should not be visited twice for the same VF");
4331 
4332   // This avoids any chances of creating a REPLICATE recipe during planning
4333   // since that would result in generation of scalarized code during execution,
4334   // which is not supported for scalable vectors.
4335   if (VF.isScalable()) {
4336     Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4337     return;
4338   }
4339 
4340   SmallSetVector<Instruction *, 8> Worklist;
4341 
4342   // These sets are used to seed the analysis with pointers used by memory
4343   // accesses that will remain scalar.
4344   SmallSetVector<Instruction *, 8> ScalarPtrs;
4345   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4346   auto *Latch = TheLoop->getLoopLatch();
4347 
4348   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4349   // The pointer operands of loads and stores will be scalar as long as the
4350   // memory access is not a gather or scatter operation. The value operand of a
4351   // store will remain scalar if the store is scalarized.
4352   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4353     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4354     assert(WideningDecision != CM_Unknown &&
4355            "Widening decision should be ready at this moment");
4356     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4357       if (Ptr == Store->getValueOperand())
4358         return WideningDecision == CM_Scalarize;
4359     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4360            "Ptr is neither a value or pointer operand");
4361     return WideningDecision != CM_GatherScatter;
4362   };
4363 
4364   // A helper that returns true if the given value is a bitcast or
4365   // getelementptr instruction contained in the loop.
4366   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4367     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4368             isa<GetElementPtrInst>(V)) &&
4369            !TheLoop->isLoopInvariant(V);
4370   };
4371 
4372   // A helper that evaluates a memory access's use of a pointer. If the use will
4373   // be a scalar use and the pointer is only used by memory accesses, we place
4374   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4375   // PossibleNonScalarPtrs.
4376   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4377     // We only care about bitcast and getelementptr instructions contained in
4378     // the loop.
4379     if (!isLoopVaryingBitCastOrGEP(Ptr))
4380       return;
4381 
4382     // If the pointer has already been identified as scalar (e.g., if it was
4383     // also identified as uniform), there's nothing to do.
4384     auto *I = cast<Instruction>(Ptr);
4385     if (Worklist.count(I))
4386       return;
4387 
4388     // If the use of the pointer will be a scalar use, and all users of the
4389     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4390     // place the pointer in PossibleNonScalarPtrs.
4391     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4392           return isa<LoadInst>(U) || isa<StoreInst>(U);
4393         }))
4394       ScalarPtrs.insert(I);
4395     else
4396       PossibleNonScalarPtrs.insert(I);
4397   };
4398 
4399   // We seed the scalars analysis with three classes of instructions: (1)
4400   // instructions marked uniform-after-vectorization and (2) bitcast,
4401   // getelementptr and (pointer) phi instructions used by memory accesses
4402   // requiring a scalar use.
4403   //
4404   // (1) Add to the worklist all instructions that have been identified as
4405   // uniform-after-vectorization.
4406   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4407 
4408   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4409   // memory accesses requiring a scalar use. The pointer operands of loads and
4410   // stores will be scalar as long as the memory accesses is not a gather or
4411   // scatter operation. The value operand of a store will remain scalar if the
4412   // store is scalarized.
4413   for (auto *BB : TheLoop->blocks())
4414     for (auto &I : *BB) {
4415       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4416         evaluatePtrUse(Load, Load->getPointerOperand());
4417       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4418         evaluatePtrUse(Store, Store->getPointerOperand());
4419         evaluatePtrUse(Store, Store->getValueOperand());
4420       }
4421     }
4422   for (auto *I : ScalarPtrs)
4423     if (!PossibleNonScalarPtrs.count(I)) {
4424       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4425       Worklist.insert(I);
4426     }
4427 
4428   // Insert the forced scalars.
4429   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4430   // induction variable when the PHI user is scalarized.
4431   auto ForcedScalar = ForcedScalars.find(VF);
4432   if (ForcedScalar != ForcedScalars.end())
4433     for (auto *I : ForcedScalar->second)
4434       Worklist.insert(I);
4435 
4436   // Expand the worklist by looking through any bitcasts and getelementptr
4437   // instructions we've already identified as scalar. This is similar to the
4438   // expansion step in collectLoopUniforms(); however, here we're only
4439   // expanding to include additional bitcasts and getelementptr instructions.
4440   unsigned Idx = 0;
4441   while (Idx != Worklist.size()) {
4442     Instruction *Dst = Worklist[Idx++];
4443     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4444       continue;
4445     auto *Src = cast<Instruction>(Dst->getOperand(0));
4446     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4447           auto *J = cast<Instruction>(U);
4448           return !TheLoop->contains(J) || Worklist.count(J) ||
4449                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4450                   isScalarUse(J, Src));
4451         })) {
4452       Worklist.insert(Src);
4453       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4454     }
4455   }
4456 
4457   // An induction variable will remain scalar if all users of the induction
4458   // variable and induction variable update remain scalar.
4459   for (auto &Induction : Legal->getInductionVars()) {
4460     auto *Ind = Induction.first;
4461     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4462 
4463     // If tail-folding is applied, the primary induction variable will be used
4464     // to feed a vector compare.
4465     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4466       continue;
4467 
4468     // Returns true if \p Indvar is a pointer induction that is used directly by
4469     // load/store instruction \p I.
4470     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4471                                               Instruction *I) {
4472       return Induction.second.getKind() ==
4473                  InductionDescriptor::IK_PtrInduction &&
4474              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4475              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4476     };
4477 
4478     // Determine if all users of the induction variable are scalar after
4479     // vectorization.
4480     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4481       auto *I = cast<Instruction>(U);
4482       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4483              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4484     });
4485     if (!ScalarInd)
4486       continue;
4487 
4488     // Determine if all users of the induction variable update instruction are
4489     // scalar after vectorization.
4490     auto ScalarIndUpdate =
4491         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4492           auto *I = cast<Instruction>(U);
4493           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4494                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4495         });
4496     if (!ScalarIndUpdate)
4497       continue;
4498 
4499     // The induction variable and its update instruction will remain scalar.
4500     Worklist.insert(Ind);
4501     Worklist.insert(IndUpdate);
4502     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4503     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4504                       << "\n");
4505   }
4506 
4507   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4508 }
4509 
4510 bool LoopVectorizationCostModel::isScalarWithPredication(
4511     Instruction *I, ElementCount VF) const {
4512   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4513     return false;
4514   switch(I->getOpcode()) {
4515   default:
4516     break;
4517   case Instruction::Load:
4518   case Instruction::Store: {
4519     if (!Legal->isMaskRequired(I))
4520       return false;
4521     auto *Ptr = getLoadStorePointerOperand(I);
4522     auto *Ty = getLoadStoreType(I);
4523     Type *VTy = Ty;
4524     if (VF.isVector())
4525       VTy = VectorType::get(Ty, VF);
4526     const Align Alignment = getLoadStoreAlignment(I);
4527     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4528                                 TTI.isLegalMaskedGather(VTy, Alignment))
4529                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4530                                 TTI.isLegalMaskedScatter(VTy, Alignment));
4531   }
4532   case Instruction::UDiv:
4533   case Instruction::SDiv:
4534   case Instruction::SRem:
4535   case Instruction::URem:
4536     return mayDivideByZero(*I);
4537   }
4538   return false;
4539 }
4540 
4541 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4542     Instruction *I, ElementCount VF) {
4543   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4544   assert(getWideningDecision(I, VF) == CM_Unknown &&
4545          "Decision should not be set yet.");
4546   auto *Group = getInterleavedAccessGroup(I);
4547   assert(Group && "Must have a group.");
4548 
4549   // If the instruction's allocated size doesn't equal it's type size, it
4550   // requires padding and will be scalarized.
4551   auto &DL = I->getModule()->getDataLayout();
4552   auto *ScalarTy = getLoadStoreType(I);
4553   if (hasIrregularType(ScalarTy, DL))
4554     return false;
4555 
4556   // Check if masking is required.
4557   // A Group may need masking for one of two reasons: it resides in a block that
4558   // needs predication, or it was decided to use masking to deal with gaps
4559   // (either a gap at the end of a load-access that may result in a speculative
4560   // load, or any gaps in a store-access).
4561   bool PredicatedAccessRequiresMasking =
4562       blockNeedsPredicationForAnyReason(I->getParent()) &&
4563       Legal->isMaskRequired(I);
4564   bool LoadAccessWithGapsRequiresEpilogMasking =
4565       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4566       !isScalarEpilogueAllowed();
4567   bool StoreAccessWithGapsRequiresMasking =
4568       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4569   if (!PredicatedAccessRequiresMasking &&
4570       !LoadAccessWithGapsRequiresEpilogMasking &&
4571       !StoreAccessWithGapsRequiresMasking)
4572     return true;
4573 
4574   // If masked interleaving is required, we expect that the user/target had
4575   // enabled it, because otherwise it either wouldn't have been created or
4576   // it should have been invalidated by the CostModel.
4577   assert(useMaskedInterleavedAccesses(TTI) &&
4578          "Masked interleave-groups for predicated accesses are not enabled.");
4579 
4580   if (Group->isReverse())
4581     return false;
4582 
4583   auto *Ty = getLoadStoreType(I);
4584   const Align Alignment = getLoadStoreAlignment(I);
4585   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4586                           : TTI.isLegalMaskedStore(Ty, Alignment);
4587 }
4588 
4589 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4590     Instruction *I, ElementCount VF) {
4591   // Get and ensure we have a valid memory instruction.
4592   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4593 
4594   auto *Ptr = getLoadStorePointerOperand(I);
4595   auto *ScalarTy = getLoadStoreType(I);
4596 
4597   // In order to be widened, the pointer should be consecutive, first of all.
4598   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4599     return false;
4600 
4601   // If the instruction is a store located in a predicated block, it will be
4602   // scalarized.
4603   if (isScalarWithPredication(I, VF))
4604     return false;
4605 
4606   // If the instruction's allocated size doesn't equal it's type size, it
4607   // requires padding and will be scalarized.
4608   auto &DL = I->getModule()->getDataLayout();
4609   if (hasIrregularType(ScalarTy, DL))
4610     return false;
4611 
4612   return true;
4613 }
4614 
4615 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4616   // We should not collect Uniforms more than once per VF. Right now,
4617   // this function is called from collectUniformsAndScalars(), which
4618   // already does this check. Collecting Uniforms for VF=1 does not make any
4619   // sense.
4620 
4621   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4622          "This function should not be visited twice for the same VF");
4623 
4624   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4625   // not analyze again.  Uniforms.count(VF) will return 1.
4626   Uniforms[VF].clear();
4627 
4628   // We now know that the loop is vectorizable!
4629   // Collect instructions inside the loop that will remain uniform after
4630   // vectorization.
4631 
4632   // Global values, params and instructions outside of current loop are out of
4633   // scope.
4634   auto isOutOfScope = [&](Value *V) -> bool {
4635     Instruction *I = dyn_cast<Instruction>(V);
4636     return (!I || !TheLoop->contains(I));
4637   };
4638 
4639   // Worklist containing uniform instructions demanding lane 0.
4640   SetVector<Instruction *> Worklist;
4641   BasicBlock *Latch = TheLoop->getLoopLatch();
4642 
4643   // Add uniform instructions demanding lane 0 to the worklist. Instructions
4644   // that are scalar with predication must not be considered uniform after
4645   // vectorization, because that would create an erroneous replicating region
4646   // where only a single instance out of VF should be formed.
4647   // TODO: optimize such seldom cases if found important, see PR40816.
4648   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4649     if (isOutOfScope(I)) {
4650       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4651                         << *I << "\n");
4652       return;
4653     }
4654     if (isScalarWithPredication(I, VF)) {
4655       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4656                         << *I << "\n");
4657       return;
4658     }
4659     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4660     Worklist.insert(I);
4661   };
4662 
4663   // Start with the conditional branch. If the branch condition is an
4664   // instruction contained in the loop that is only used by the branch, it is
4665   // uniform.
4666   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4667   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4668     addToWorklistIfAllowed(Cmp);
4669 
4670   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
4671     InstWidening WideningDecision = getWideningDecision(I, VF);
4672     assert(WideningDecision != CM_Unknown &&
4673            "Widening decision should be ready at this moment");
4674 
4675     // A uniform memory op is itself uniform.  We exclude uniform stores
4676     // here as they demand the last lane, not the first one.
4677     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
4678       assert(WideningDecision == CM_Scalarize);
4679       return true;
4680     }
4681 
4682     return (WideningDecision == CM_Widen ||
4683             WideningDecision == CM_Widen_Reverse ||
4684             WideningDecision == CM_Interleave);
4685   };
4686 
4687 
4688   // Returns true if Ptr is the pointer operand of a memory access instruction
4689   // I, and I is known to not require scalarization.
4690   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4691     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4692   };
4693 
4694   // Holds a list of values which are known to have at least one uniform use.
4695   // Note that there may be other uses which aren't uniform.  A "uniform use"
4696   // here is something which only demands lane 0 of the unrolled iterations;
4697   // it does not imply that all lanes produce the same value (e.g. this is not
4698   // the usual meaning of uniform)
4699   SetVector<Value *> HasUniformUse;
4700 
4701   // Scan the loop for instructions which are either a) known to have only
4702   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
4703   for (auto *BB : TheLoop->blocks())
4704     for (auto &I : *BB) {
4705       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
4706         switch (II->getIntrinsicID()) {
4707         case Intrinsic::sideeffect:
4708         case Intrinsic::experimental_noalias_scope_decl:
4709         case Intrinsic::assume:
4710         case Intrinsic::lifetime_start:
4711         case Intrinsic::lifetime_end:
4712           if (TheLoop->hasLoopInvariantOperands(&I))
4713             addToWorklistIfAllowed(&I);
4714           break;
4715         default:
4716           break;
4717         }
4718       }
4719 
4720       // ExtractValue instructions must be uniform, because the operands are
4721       // known to be loop-invariant.
4722       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
4723         assert(isOutOfScope(EVI->getAggregateOperand()) &&
4724                "Expected aggregate value to be loop invariant");
4725         addToWorklistIfAllowed(EVI);
4726         continue;
4727       }
4728 
4729       // If there's no pointer operand, there's nothing to do.
4730       auto *Ptr = getLoadStorePointerOperand(&I);
4731       if (!Ptr)
4732         continue;
4733 
4734       // A uniform memory op is itself uniform.  We exclude uniform stores
4735       // here as they demand the last lane, not the first one.
4736       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
4737         addToWorklistIfAllowed(&I);
4738 
4739       if (isUniformDecision(&I, VF)) {
4740         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
4741         HasUniformUse.insert(Ptr);
4742       }
4743     }
4744 
4745   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
4746   // demanding) users.  Since loops are assumed to be in LCSSA form, this
4747   // disallows uses outside the loop as well.
4748   for (auto *V : HasUniformUse) {
4749     if (isOutOfScope(V))
4750       continue;
4751     auto *I = cast<Instruction>(V);
4752     auto UsersAreMemAccesses =
4753       llvm::all_of(I->users(), [&](User *U) -> bool {
4754         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4755       });
4756     if (UsersAreMemAccesses)
4757       addToWorklistIfAllowed(I);
4758   }
4759 
4760   // Expand Worklist in topological order: whenever a new instruction
4761   // is added , its users should be already inside Worklist.  It ensures
4762   // a uniform instruction will only be used by uniform instructions.
4763   unsigned idx = 0;
4764   while (idx != Worklist.size()) {
4765     Instruction *I = Worklist[idx++];
4766 
4767     for (auto OV : I->operand_values()) {
4768       // isOutOfScope operands cannot be uniform instructions.
4769       if (isOutOfScope(OV))
4770         continue;
4771       // First order recurrence Phi's should typically be considered
4772       // non-uniform.
4773       auto *OP = dyn_cast<PHINode>(OV);
4774       if (OP && Legal->isFirstOrderRecurrence(OP))
4775         continue;
4776       // If all the users of the operand are uniform, then add the
4777       // operand into the uniform worklist.
4778       auto *OI = cast<Instruction>(OV);
4779       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4780             auto *J = cast<Instruction>(U);
4781             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4782           }))
4783         addToWorklistIfAllowed(OI);
4784     }
4785   }
4786 
4787   // For an instruction to be added into Worklist above, all its users inside
4788   // the loop should also be in Worklist. However, this condition cannot be
4789   // true for phi nodes that form a cyclic dependence. We must process phi
4790   // nodes separately. An induction variable will remain uniform if all users
4791   // of the induction variable and induction variable update remain uniform.
4792   // The code below handles both pointer and non-pointer induction variables.
4793   for (auto &Induction : Legal->getInductionVars()) {
4794     auto *Ind = Induction.first;
4795     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4796 
4797     // Determine if all users of the induction variable are uniform after
4798     // vectorization.
4799     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4800       auto *I = cast<Instruction>(U);
4801       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4802              isVectorizedMemAccessUse(I, Ind);
4803     });
4804     if (!UniformInd)
4805       continue;
4806 
4807     // Determine if all users of the induction variable update instruction are
4808     // uniform after vectorization.
4809     auto UniformIndUpdate =
4810         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4811           auto *I = cast<Instruction>(U);
4812           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4813                  isVectorizedMemAccessUse(I, IndUpdate);
4814         });
4815     if (!UniformIndUpdate)
4816       continue;
4817 
4818     // The induction variable and its update instruction will remain uniform.
4819     addToWorklistIfAllowed(Ind);
4820     addToWorklistIfAllowed(IndUpdate);
4821   }
4822 
4823   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4824 }
4825 
4826 bool LoopVectorizationCostModel::runtimeChecksRequired() {
4827   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
4828 
4829   if (Legal->getRuntimePointerChecking()->Need) {
4830     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
4831         "runtime pointer checks needed. Enable vectorization of this "
4832         "loop with '#pragma clang loop vectorize(enable)' when "
4833         "compiling with -Os/-Oz",
4834         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4835     return true;
4836   }
4837 
4838   if (!PSE.getPredicate().isAlwaysTrue()) {
4839     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
4840         "runtime SCEV checks needed. Enable vectorization of this "
4841         "loop with '#pragma clang loop vectorize(enable)' when "
4842         "compiling with -Os/-Oz",
4843         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4844     return true;
4845   }
4846 
4847   // FIXME: Avoid specializing for stride==1 instead of bailing out.
4848   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
4849     reportVectorizationFailure("Runtime stride check for small trip count",
4850         "runtime stride == 1 checks needed. Enable vectorization of "
4851         "this loop without such check by compiling with -Os/-Oz",
4852         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4853     return true;
4854   }
4855 
4856   return false;
4857 }
4858 
4859 ElementCount
4860 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
4861   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
4862     return ElementCount::getScalable(0);
4863 
4864   if (Hints->isScalableVectorizationDisabled()) {
4865     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
4866                             "ScalableVectorizationDisabled", ORE, TheLoop);
4867     return ElementCount::getScalable(0);
4868   }
4869 
4870   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
4871 
4872   auto MaxScalableVF = ElementCount::getScalable(
4873       std::numeric_limits<ElementCount::ScalarTy>::max());
4874 
4875   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
4876   // FIXME: While for scalable vectors this is currently sufficient, this should
4877   // be replaced by a more detailed mechanism that filters out specific VFs,
4878   // instead of invalidating vectorization for a whole set of VFs based on the
4879   // MaxVF.
4880 
4881   // Disable scalable vectorization if the loop contains unsupported reductions.
4882   if (!canVectorizeReductions(MaxScalableVF)) {
4883     reportVectorizationInfo(
4884         "Scalable vectorization not supported for the reduction "
4885         "operations found in this loop.",
4886         "ScalableVFUnfeasible", ORE, TheLoop);
4887     return ElementCount::getScalable(0);
4888   }
4889 
4890   // Disable scalable vectorization if the loop contains any instructions
4891   // with element types not supported for scalable vectors.
4892   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
4893         return !Ty->isVoidTy() &&
4894                !this->TTI.isElementTypeLegalForScalableVector(Ty);
4895       })) {
4896     reportVectorizationInfo("Scalable vectorization is not supported "
4897                             "for all element types found in this loop.",
4898                             "ScalableVFUnfeasible", ORE, TheLoop);
4899     return ElementCount::getScalable(0);
4900   }
4901 
4902   if (Legal->isSafeForAnyVectorWidth())
4903     return MaxScalableVF;
4904 
4905   // Limit MaxScalableVF by the maximum safe dependence distance.
4906   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
4907   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
4908     MaxVScale =
4909         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
4910   MaxScalableVF = ElementCount::getScalable(
4911       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
4912   if (!MaxScalableVF)
4913     reportVectorizationInfo(
4914         "Max legal vector width too small, scalable vectorization "
4915         "unfeasible.",
4916         "ScalableVFUnfeasible", ORE, TheLoop);
4917 
4918   return MaxScalableVF;
4919 }
4920 
4921 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
4922     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
4923   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4924   unsigned SmallestType, WidestType;
4925   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4926 
4927   // Get the maximum safe dependence distance in bits computed by LAA.
4928   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4929   // the memory accesses that is most restrictive (involved in the smallest
4930   // dependence distance).
4931   unsigned MaxSafeElements =
4932       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
4933 
4934   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
4935   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4936 
4937   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
4938                     << ".\n");
4939   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
4940                     << ".\n");
4941 
4942   // First analyze the UserVF, fall back if the UserVF should be ignored.
4943   if (UserVF) {
4944     auto MaxSafeUserVF =
4945         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4946 
4947     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
4948       // If `VF=vscale x N` is safe, then so is `VF=N`
4949       if (UserVF.isScalable())
4950         return FixedScalableVFPair(
4951             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
4952       else
4953         return UserVF;
4954     }
4955 
4956     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
4957 
4958     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
4959     // is better to ignore the hint and let the compiler choose a suitable VF.
4960     if (!UserVF.isScalable()) {
4961       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4962                         << " is unsafe, clamping to max safe VF="
4963                         << MaxSafeFixedVF << ".\n");
4964       ORE->emit([&]() {
4965         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4966                                           TheLoop->getStartLoc(),
4967                                           TheLoop->getHeader())
4968                << "User-specified vectorization factor "
4969                << ore::NV("UserVectorizationFactor", UserVF)
4970                << " is unsafe, clamping to maximum safe vectorization factor "
4971                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
4972       });
4973       return MaxSafeFixedVF;
4974     }
4975 
4976     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
4977       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4978                         << " is ignored because scalable vectors are not "
4979                            "available.\n");
4980       ORE->emit([&]() {
4981         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4982                                           TheLoop->getStartLoc(),
4983                                           TheLoop->getHeader())
4984                << "User-specified vectorization factor "
4985                << ore::NV("UserVectorizationFactor", UserVF)
4986                << " is ignored because the target does not support scalable "
4987                   "vectors. The compiler will pick a more suitable value.";
4988       });
4989     } else {
4990       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4991                         << " is unsafe. Ignoring scalable UserVF.\n");
4992       ORE->emit([&]() {
4993         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4994                                           TheLoop->getStartLoc(),
4995                                           TheLoop->getHeader())
4996                << "User-specified vectorization factor "
4997                << ore::NV("UserVectorizationFactor", UserVF)
4998                << " is unsafe. Ignoring the hint to let the compiler pick a "
4999                   "more suitable value.";
5000       });
5001     }
5002   }
5003 
5004   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5005                     << " / " << WidestType << " bits.\n");
5006 
5007   FixedScalableVFPair Result(ElementCount::getFixed(1),
5008                              ElementCount::getScalable(0));
5009   if (auto MaxVF =
5010           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5011                                   MaxSafeFixedVF, FoldTailByMasking))
5012     Result.FixedVF = MaxVF;
5013 
5014   if (auto MaxVF =
5015           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5016                                   MaxSafeScalableVF, FoldTailByMasking))
5017     if (MaxVF.isScalable()) {
5018       Result.ScalableVF = MaxVF;
5019       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5020                         << "\n");
5021     }
5022 
5023   return Result;
5024 }
5025 
5026 FixedScalableVFPair
5027 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5028   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5029     // TODO: It may by useful to do since it's still likely to be dynamically
5030     // uniform if the target can skip.
5031     reportVectorizationFailure(
5032         "Not inserting runtime ptr check for divergent target",
5033         "runtime pointer checks needed. Not enabled for divergent target",
5034         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5035     return FixedScalableVFPair::getNone();
5036   }
5037 
5038   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5039   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5040   if (TC == 1) {
5041     reportVectorizationFailure("Single iteration (non) loop",
5042         "loop trip count is one, irrelevant for vectorization",
5043         "SingleIterationLoop", ORE, TheLoop);
5044     return FixedScalableVFPair::getNone();
5045   }
5046 
5047   switch (ScalarEpilogueStatus) {
5048   case CM_ScalarEpilogueAllowed:
5049     return computeFeasibleMaxVF(TC, UserVF, false);
5050   case CM_ScalarEpilogueNotAllowedUsePredicate:
5051     LLVM_FALLTHROUGH;
5052   case CM_ScalarEpilogueNotNeededUsePredicate:
5053     LLVM_DEBUG(
5054         dbgs() << "LV: vector predicate hint/switch found.\n"
5055                << "LV: Not allowing scalar epilogue, creating predicated "
5056                << "vector loop.\n");
5057     break;
5058   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5059     // fallthrough as a special case of OptForSize
5060   case CM_ScalarEpilogueNotAllowedOptSize:
5061     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5062       LLVM_DEBUG(
5063           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5064     else
5065       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5066                         << "count.\n");
5067 
5068     // Bail if runtime checks are required, which are not good when optimising
5069     // for size.
5070     if (runtimeChecksRequired())
5071       return FixedScalableVFPair::getNone();
5072 
5073     break;
5074   }
5075 
5076   // The only loops we can vectorize without a scalar epilogue, are loops with
5077   // a bottom-test and a single exiting block. We'd have to handle the fact
5078   // that not every instruction executes on the last iteration.  This will
5079   // require a lane mask which varies through the vector loop body.  (TODO)
5080   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5081     // If there was a tail-folding hint/switch, but we can't fold the tail by
5082     // masking, fallback to a vectorization with a scalar epilogue.
5083     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5084       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5085                            "scalar epilogue instead.\n");
5086       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5087       return computeFeasibleMaxVF(TC, UserVF, false);
5088     }
5089     return FixedScalableVFPair::getNone();
5090   }
5091 
5092   // Now try the tail folding
5093 
5094   // Invalidate interleave groups that require an epilogue if we can't mask
5095   // the interleave-group.
5096   if (!useMaskedInterleavedAccesses(TTI)) {
5097     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5098            "No decisions should have been taken at this point");
5099     // Note: There is no need to invalidate any cost modeling decisions here, as
5100     // non where taken so far.
5101     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5102   }
5103 
5104   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5105   // Avoid tail folding if the trip count is known to be a multiple of any VF
5106   // we chose.
5107   // FIXME: The condition below pessimises the case for fixed-width vectors,
5108   // when scalable VFs are also candidates for vectorization.
5109   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5110     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5111     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5112            "MaxFixedVF must be a power of 2");
5113     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5114                                    : MaxFixedVF.getFixedValue();
5115     ScalarEvolution *SE = PSE.getSE();
5116     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5117     const SCEV *ExitCount = SE->getAddExpr(
5118         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5119     const SCEV *Rem = SE->getURemExpr(
5120         SE->applyLoopGuards(ExitCount, TheLoop),
5121         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5122     if (Rem->isZero()) {
5123       // Accept MaxFixedVF if we do not have a tail.
5124       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5125       return MaxFactors;
5126     }
5127   }
5128 
5129   // For scalable vectors don't use tail folding for low trip counts or
5130   // optimizing for code size. We only permit this if the user has explicitly
5131   // requested it.
5132   if (ScalarEpilogueStatus != CM_ScalarEpilogueNotNeededUsePredicate &&
5133       ScalarEpilogueStatus != CM_ScalarEpilogueNotAllowedUsePredicate &&
5134       MaxFactors.ScalableVF.isVector())
5135     MaxFactors.ScalableVF = ElementCount::getScalable(0);
5136 
5137   // If we don't know the precise trip count, or if the trip count that we
5138   // found modulo the vectorization factor is not zero, try to fold the tail
5139   // by masking.
5140   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5141   if (Legal->prepareToFoldTailByMasking()) {
5142     FoldTailByMasking = true;
5143     return MaxFactors;
5144   }
5145 
5146   // If there was a tail-folding hint/switch, but we can't fold the tail by
5147   // masking, fallback to a vectorization with a scalar epilogue.
5148   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5149     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5150                          "scalar epilogue instead.\n");
5151     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5152     return MaxFactors;
5153   }
5154 
5155   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5156     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5157     return FixedScalableVFPair::getNone();
5158   }
5159 
5160   if (TC == 0) {
5161     reportVectorizationFailure(
5162         "Unable to calculate the loop count due to complex control flow",
5163         "unable to calculate the loop count due to complex control flow",
5164         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5165     return FixedScalableVFPair::getNone();
5166   }
5167 
5168   reportVectorizationFailure(
5169       "Cannot optimize for size and vectorize at the same time.",
5170       "cannot optimize for size and vectorize at the same time. "
5171       "Enable vectorization of this loop with '#pragma clang loop "
5172       "vectorize(enable)' when compiling with -Os/-Oz",
5173       "NoTailLoopWithOptForSize", ORE, TheLoop);
5174   return FixedScalableVFPair::getNone();
5175 }
5176 
5177 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5178     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5179     const ElementCount &MaxSafeVF, bool FoldTailByMasking) {
5180   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5181   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5182       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5183                            : TargetTransformInfo::RGK_FixedWidthVector);
5184 
5185   // Convenience function to return the minimum of two ElementCounts.
5186   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5187     assert((LHS.isScalable() == RHS.isScalable()) &&
5188            "Scalable flags must match");
5189     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5190   };
5191 
5192   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5193   // Note that both WidestRegister and WidestType may not be a powers of 2.
5194   auto MaxVectorElementCount = ElementCount::get(
5195       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5196       ComputeScalableMaxVF);
5197   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5198   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5199                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5200 
5201   if (!MaxVectorElementCount) {
5202     LLVM_DEBUG(dbgs() << "LV: The target has no "
5203                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5204                       << " vector registers.\n");
5205     return ElementCount::getFixed(1);
5206   }
5207 
5208   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5209   if (ConstTripCount &&
5210       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5211       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5212     // If loop trip count (TC) is known at compile time there is no point in
5213     // choosing VF greater than TC (as done in the loop below). Select maximum
5214     // power of two which doesn't exceed TC.
5215     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5216     // when the TC is less than or equal to the known number of lanes.
5217     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5218     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5219                          "exceeding the constant trip count: "
5220                       << ClampedConstTripCount << "\n");
5221     return ElementCount::getFixed(ClampedConstTripCount);
5222   }
5223 
5224   ElementCount MaxVF = MaxVectorElementCount;
5225   if (MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
5226                             TTI.shouldMaximizeVectorBandwidth())) {
5227     auto MaxVectorElementCountMaxBW = ElementCount::get(
5228         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5229         ComputeScalableMaxVF);
5230     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5231 
5232     // Collect all viable vectorization factors larger than the default MaxVF
5233     // (i.e. MaxVectorElementCount).
5234     SmallVector<ElementCount, 8> VFs;
5235     for (ElementCount VS = MaxVectorElementCount * 2;
5236          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5237       VFs.push_back(VS);
5238 
5239     // For each VF calculate its register usage.
5240     auto RUs = calculateRegisterUsage(VFs);
5241 
5242     // Select the largest VF which doesn't require more registers than existing
5243     // ones.
5244     for (int i = RUs.size() - 1; i >= 0; --i) {
5245       bool Selected = true;
5246       for (auto &pair : RUs[i].MaxLocalUsers) {
5247         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5248         if (pair.second > TargetNumRegisters)
5249           Selected = false;
5250       }
5251       if (Selected) {
5252         MaxVF = VFs[i];
5253         break;
5254       }
5255     }
5256     if (ElementCount MinVF =
5257             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5258       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5259         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5260                           << ") with target's minimum: " << MinVF << '\n');
5261         MaxVF = MinVF;
5262       }
5263     }
5264 
5265     // Invalidate any widening decisions we might have made, in case the loop
5266     // requires prediction (decided later), but we have already made some
5267     // load/store widening decisions.
5268     invalidateCostModelingDecisions();
5269   }
5270   return MaxVF;
5271 }
5272 
5273 Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
5274   if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5275     auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
5276     auto Min = Attr.getVScaleRangeMin();
5277     auto Max = Attr.getVScaleRangeMax();
5278     if (Max && Min == Max)
5279       return Max;
5280   }
5281 
5282   return TTI.getVScaleForTuning();
5283 }
5284 
5285 bool LoopVectorizationCostModel::isMoreProfitable(
5286     const VectorizationFactor &A, const VectorizationFactor &B) const {
5287   InstructionCost CostA = A.Cost;
5288   InstructionCost CostB = B.Cost;
5289 
5290   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5291 
5292   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5293       MaxTripCount) {
5294     // If we are folding the tail and the trip count is a known (possibly small)
5295     // constant, the trip count will be rounded up to an integer number of
5296     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5297     // which we compare directly. When not folding the tail, the total cost will
5298     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5299     // approximated with the per-lane cost below instead of using the tripcount
5300     // as here.
5301     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5302     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5303     return RTCostA < RTCostB;
5304   }
5305 
5306   // Improve estimate for the vector width if it is scalable.
5307   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5308   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5309   if (Optional<unsigned> VScale = getVScaleForTuning()) {
5310     if (A.Width.isScalable())
5311       EstimatedWidthA *= VScale.getValue();
5312     if (B.Width.isScalable())
5313       EstimatedWidthB *= VScale.getValue();
5314   }
5315 
5316   // Assume vscale may be larger than 1 (or the value being tuned for),
5317   // so that scalable vectorization is slightly favorable over fixed-width
5318   // vectorization.
5319   if (A.Width.isScalable() && !B.Width.isScalable())
5320     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5321 
5322   // To avoid the need for FP division:
5323   //      (CostA / A.Width) < (CostB / B.Width)
5324   // <=>  (CostA * B.Width) < (CostB * A.Width)
5325   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5326 }
5327 
5328 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5329     const ElementCountSet &VFCandidates) {
5330   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5331   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5332   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5333   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5334          "Expected Scalar VF to be a candidate");
5335 
5336   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5337   VectorizationFactor ChosenFactor = ScalarCost;
5338 
5339   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5340   if (ForceVectorization && VFCandidates.size() > 1) {
5341     // Ignore scalar width, because the user explicitly wants vectorization.
5342     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5343     // evaluation.
5344     ChosenFactor.Cost = InstructionCost::getMax();
5345   }
5346 
5347   SmallVector<InstructionVFPair> InvalidCosts;
5348   for (const auto &i : VFCandidates) {
5349     // The cost for scalar VF=1 is already calculated, so ignore it.
5350     if (i.isScalar())
5351       continue;
5352 
5353     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5354     VectorizationFactor Candidate(i, C.first);
5355 
5356 #ifndef NDEBUG
5357     unsigned AssumedMinimumVscale = 1;
5358     if (Optional<unsigned> VScale = getVScaleForTuning())
5359       AssumedMinimumVscale = VScale.getValue();
5360     unsigned Width =
5361         Candidate.Width.isScalable()
5362             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5363             : Candidate.Width.getFixedValue();
5364     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5365                       << " costs: " << (Candidate.Cost / Width));
5366     if (i.isScalable())
5367       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5368                         << AssumedMinimumVscale << ")");
5369     LLVM_DEBUG(dbgs() << ".\n");
5370 #endif
5371 
5372     if (!C.second && !ForceVectorization) {
5373       LLVM_DEBUG(
5374           dbgs() << "LV: Not considering vector loop of width " << i
5375                  << " because it will not generate any vector instructions.\n");
5376       continue;
5377     }
5378 
5379     // If profitable add it to ProfitableVF list.
5380     if (isMoreProfitable(Candidate, ScalarCost))
5381       ProfitableVFs.push_back(Candidate);
5382 
5383     if (isMoreProfitable(Candidate, ChosenFactor))
5384       ChosenFactor = Candidate;
5385   }
5386 
5387   // Emit a report of VFs with invalid costs in the loop.
5388   if (!InvalidCosts.empty()) {
5389     // Group the remarks per instruction, keeping the instruction order from
5390     // InvalidCosts.
5391     std::map<Instruction *, unsigned> Numbering;
5392     unsigned I = 0;
5393     for (auto &Pair : InvalidCosts)
5394       if (!Numbering.count(Pair.first))
5395         Numbering[Pair.first] = I++;
5396 
5397     // Sort the list, first on instruction(number) then on VF.
5398     llvm::sort(InvalidCosts,
5399                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5400                  if (Numbering[A.first] != Numbering[B.first])
5401                    return Numbering[A.first] < Numbering[B.first];
5402                  ElementCountComparator ECC;
5403                  return ECC(A.second, B.second);
5404                });
5405 
5406     // For a list of ordered instruction-vf pairs:
5407     //   [(load, vf1), (load, vf2), (store, vf1)]
5408     // Group the instructions together to emit separate remarks for:
5409     //   load  (vf1, vf2)
5410     //   store (vf1)
5411     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5412     auto Subset = ArrayRef<InstructionVFPair>();
5413     do {
5414       if (Subset.empty())
5415         Subset = Tail.take_front(1);
5416 
5417       Instruction *I = Subset.front().first;
5418 
5419       // If the next instruction is different, or if there are no other pairs,
5420       // emit a remark for the collated subset. e.g.
5421       //   [(load, vf1), (load, vf2))]
5422       // to emit:
5423       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5424       if (Subset == Tail || Tail[Subset.size()].first != I) {
5425         std::string OutString;
5426         raw_string_ostream OS(OutString);
5427         assert(!Subset.empty() && "Unexpected empty range");
5428         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5429         for (auto &Pair : Subset)
5430           OS << (Pair.second == Subset.front().second ? "" : ", ")
5431              << Pair.second;
5432         OS << "):";
5433         if (auto *CI = dyn_cast<CallInst>(I))
5434           OS << " call to " << CI->getCalledFunction()->getName();
5435         else
5436           OS << " " << I->getOpcodeName();
5437         OS.flush();
5438         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5439         Tail = Tail.drop_front(Subset.size());
5440         Subset = {};
5441       } else
5442         // Grow the subset by one element
5443         Subset = Tail.take_front(Subset.size() + 1);
5444     } while (!Tail.empty());
5445   }
5446 
5447   if (!EnableCondStoresVectorization && NumPredStores) {
5448     reportVectorizationFailure("There are conditional stores.",
5449         "store that is conditionally executed prevents vectorization",
5450         "ConditionalStore", ORE, TheLoop);
5451     ChosenFactor = ScalarCost;
5452   }
5453 
5454   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5455                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
5456              << "LV: Vectorization seems to be not beneficial, "
5457              << "but was forced by a user.\n");
5458   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5459   return ChosenFactor;
5460 }
5461 
5462 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5463     const Loop &L, ElementCount VF) const {
5464   // Cross iteration phis such as reductions need special handling and are
5465   // currently unsupported.
5466   if (any_of(L.getHeader()->phis(),
5467              [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
5468     return false;
5469 
5470   // Phis with uses outside of the loop require special handling and are
5471   // currently unsupported.
5472   for (auto &Entry : Legal->getInductionVars()) {
5473     // Look for uses of the value of the induction at the last iteration.
5474     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5475     for (User *U : PostInc->users())
5476       if (!L.contains(cast<Instruction>(U)))
5477         return false;
5478     // Look for uses of penultimate value of the induction.
5479     for (User *U : Entry.first->users())
5480       if (!L.contains(cast<Instruction>(U)))
5481         return false;
5482   }
5483 
5484   // Induction variables that are widened require special handling that is
5485   // currently not supported.
5486   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5487         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5488                  this->isProfitableToScalarize(Entry.first, VF));
5489       }))
5490     return false;
5491 
5492   // Epilogue vectorization code has not been auditted to ensure it handles
5493   // non-latch exits properly.  It may be fine, but it needs auditted and
5494   // tested.
5495   if (L.getExitingBlock() != L.getLoopLatch())
5496     return false;
5497 
5498   return true;
5499 }
5500 
5501 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5502     const ElementCount VF) const {
5503   // FIXME: We need a much better cost-model to take different parameters such
5504   // as register pressure, code size increase and cost of extra branches into
5505   // account. For now we apply a very crude heuristic and only consider loops
5506   // with vectorization factors larger than a certain value.
5507   // We also consider epilogue vectorization unprofitable for targets that don't
5508   // consider interleaving beneficial (eg. MVE).
5509   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5510     return false;
5511   // FIXME: We should consider changing the threshold for scalable
5512   // vectors to take VScaleForTuning into account.
5513   if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
5514     return true;
5515   return false;
5516 }
5517 
5518 VectorizationFactor
5519 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5520     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5521   VectorizationFactor Result = VectorizationFactor::Disabled();
5522   if (!EnableEpilogueVectorization) {
5523     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5524     return Result;
5525   }
5526 
5527   if (!isScalarEpilogueAllowed()) {
5528     LLVM_DEBUG(
5529         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5530                   "allowed.\n";);
5531     return Result;
5532   }
5533 
5534   // Not really a cost consideration, but check for unsupported cases here to
5535   // simplify the logic.
5536   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5537     LLVM_DEBUG(
5538         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5539                   "not a supported candidate.\n";);
5540     return Result;
5541   }
5542 
5543   if (EpilogueVectorizationForceVF > 1) {
5544     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5545     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5546     if (LVP.hasPlanWithVF(ForcedEC))
5547       return {ForcedEC, 0};
5548     else {
5549       LLVM_DEBUG(
5550           dbgs()
5551               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5552       return Result;
5553     }
5554   }
5555 
5556   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5557       TheLoop->getHeader()->getParent()->hasMinSize()) {
5558     LLVM_DEBUG(
5559         dbgs()
5560             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5561     return Result;
5562   }
5563 
5564   if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
5565     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5566                          "this loop\n");
5567     return Result;
5568   }
5569 
5570   // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
5571   // the main loop handles 8 lanes per iteration. We could still benefit from
5572   // vectorizing the epilogue loop with VF=4.
5573   ElementCount EstimatedRuntimeVF = MainLoopVF;
5574   if (MainLoopVF.isScalable()) {
5575     EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5576     if (Optional<unsigned> VScale = getVScaleForTuning())
5577       EstimatedRuntimeVF *= VScale.getValue();
5578   }
5579 
5580   for (auto &NextVF : ProfitableVFs)
5581     if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
5582           ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
5583          ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
5584         (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
5585         LVP.hasPlanWithVF(NextVF.Width))
5586       Result = NextVF;
5587 
5588   if (Result != VectorizationFactor::Disabled())
5589     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5590                       << Result.Width << "\n";);
5591   return Result;
5592 }
5593 
5594 std::pair<unsigned, unsigned>
5595 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5596   unsigned MinWidth = -1U;
5597   unsigned MaxWidth = 8;
5598   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5599   // For in-loop reductions, no element types are added to ElementTypesInLoop
5600   // if there are no loads/stores in the loop. In this case, check through the
5601   // reduction variables to determine the maximum width.
5602   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5603     // Reset MaxWidth so that we can find the smallest type used by recurrences
5604     // in the loop.
5605     MaxWidth = -1U;
5606     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5607       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5608       // When finding the min width used by the recurrence we need to account
5609       // for casts on the input operands of the recurrence.
5610       MaxWidth = std::min<unsigned>(
5611           MaxWidth, std::min<unsigned>(
5612                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5613                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5614     }
5615   } else {
5616     for (Type *T : ElementTypesInLoop) {
5617       MinWidth = std::min<unsigned>(
5618           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5619       MaxWidth = std::max<unsigned>(
5620           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5621     }
5622   }
5623   return {MinWidth, MaxWidth};
5624 }
5625 
5626 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5627   ElementTypesInLoop.clear();
5628   // For each block.
5629   for (BasicBlock *BB : TheLoop->blocks()) {
5630     // For each instruction in the loop.
5631     for (Instruction &I : BB->instructionsWithoutDebug()) {
5632       Type *T = I.getType();
5633 
5634       // Skip ignored values.
5635       if (ValuesToIgnore.count(&I))
5636         continue;
5637 
5638       // Only examine Loads, Stores and PHINodes.
5639       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5640         continue;
5641 
5642       // Examine PHI nodes that are reduction variables. Update the type to
5643       // account for the recurrence type.
5644       if (auto *PN = dyn_cast<PHINode>(&I)) {
5645         if (!Legal->isReductionVariable(PN))
5646           continue;
5647         const RecurrenceDescriptor &RdxDesc =
5648             Legal->getReductionVars().find(PN)->second;
5649         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
5650             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
5651                                       RdxDesc.getRecurrenceType(),
5652                                       TargetTransformInfo::ReductionFlags()))
5653           continue;
5654         T = RdxDesc.getRecurrenceType();
5655       }
5656 
5657       // Examine the stored values.
5658       if (auto *ST = dyn_cast<StoreInst>(&I))
5659         T = ST->getValueOperand()->getType();
5660 
5661       assert(T->isSized() &&
5662              "Expected the load/store/recurrence type to be sized");
5663 
5664       ElementTypesInLoop.insert(T);
5665     }
5666   }
5667 }
5668 
5669 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5670                                                            unsigned LoopCost) {
5671   // -- The interleave heuristics --
5672   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5673   // There are many micro-architectural considerations that we can't predict
5674   // at this level. For example, frontend pressure (on decode or fetch) due to
5675   // code size, or the number and capabilities of the execution ports.
5676   //
5677   // We use the following heuristics to select the interleave count:
5678   // 1. If the code has reductions, then we interleave to break the cross
5679   // iteration dependency.
5680   // 2. If the loop is really small, then we interleave to reduce the loop
5681   // overhead.
5682   // 3. We don't interleave if we think that we will spill registers to memory
5683   // due to the increased register pressure.
5684 
5685   if (!isScalarEpilogueAllowed())
5686     return 1;
5687 
5688   // We used the distance for the interleave count.
5689   if (Legal->getMaxSafeDepDistBytes() != -1U)
5690     return 1;
5691 
5692   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5693   const bool HasReductions = !Legal->getReductionVars().empty();
5694   // Do not interleave loops with a relatively small known or estimated trip
5695   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5696   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5697   // because with the above conditions interleaving can expose ILP and break
5698   // cross iteration dependences for reductions.
5699   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5700       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5701     return 1;
5702 
5703   // If we did not calculate the cost for VF (because the user selected the VF)
5704   // then we calculate the cost of VF here.
5705   if (LoopCost == 0) {
5706     InstructionCost C = expectedCost(VF).first;
5707     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
5708     LoopCost = *C.getValue();
5709 
5710     // Loop body is free and there is no need for interleaving.
5711     if (LoopCost == 0)
5712       return 1;
5713   }
5714 
5715   RegisterUsage R = calculateRegisterUsage({VF})[0];
5716   // We divide by these constants so assume that we have at least one
5717   // instruction that uses at least one register.
5718   for (auto& pair : R.MaxLocalUsers) {
5719     pair.second = std::max(pair.second, 1U);
5720   }
5721 
5722   // We calculate the interleave count using the following formula.
5723   // Subtract the number of loop invariants from the number of available
5724   // registers. These registers are used by all of the interleaved instances.
5725   // Next, divide the remaining registers by the number of registers that is
5726   // required by the loop, in order to estimate how many parallel instances
5727   // fit without causing spills. All of this is rounded down if necessary to be
5728   // a power of two. We want power of two interleave count to simplify any
5729   // addressing operations or alignment considerations.
5730   // We also want power of two interleave counts to ensure that the induction
5731   // variable of the vector loop wraps to zero, when tail is folded by masking;
5732   // this currently happens when OptForSize, in which case IC is set to 1 above.
5733   unsigned IC = UINT_MAX;
5734 
5735   for (auto& pair : R.MaxLocalUsers) {
5736     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5737     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5738                       << " registers of "
5739                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5740     if (VF.isScalar()) {
5741       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5742         TargetNumRegisters = ForceTargetNumScalarRegs;
5743     } else {
5744       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5745         TargetNumRegisters = ForceTargetNumVectorRegs;
5746     }
5747     unsigned MaxLocalUsers = pair.second;
5748     unsigned LoopInvariantRegs = 0;
5749     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5750       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5751 
5752     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5753     // Don't count the induction variable as interleaved.
5754     if (EnableIndVarRegisterHeur) {
5755       TmpIC =
5756           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5757                         std::max(1U, (MaxLocalUsers - 1)));
5758     }
5759 
5760     IC = std::min(IC, TmpIC);
5761   }
5762 
5763   // Clamp the interleave ranges to reasonable counts.
5764   unsigned MaxInterleaveCount =
5765       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5766 
5767   // Check if the user has overridden the max.
5768   if (VF.isScalar()) {
5769     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5770       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5771   } else {
5772     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5773       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5774   }
5775 
5776   // If trip count is known or estimated compile time constant, limit the
5777   // interleave count to be less than the trip count divided by VF, provided it
5778   // is at least 1.
5779   //
5780   // For scalable vectors we can't know if interleaving is beneficial. It may
5781   // not be beneficial for small loops if none of the lanes in the second vector
5782   // iterations is enabled. However, for larger loops, there is likely to be a
5783   // similar benefit as for fixed-width vectors. For now, we choose to leave
5784   // the InterleaveCount as if vscale is '1', although if some information about
5785   // the vector is known (e.g. min vector size), we can make a better decision.
5786   if (BestKnownTC) {
5787     MaxInterleaveCount =
5788         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5789     // Make sure MaxInterleaveCount is greater than 0.
5790     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5791   }
5792 
5793   assert(MaxInterleaveCount > 0 &&
5794          "Maximum interleave count must be greater than 0");
5795 
5796   // Clamp the calculated IC to be between the 1 and the max interleave count
5797   // that the target and trip count allows.
5798   if (IC > MaxInterleaveCount)
5799     IC = MaxInterleaveCount;
5800   else
5801     // Make sure IC is greater than 0.
5802     IC = std::max(1u, IC);
5803 
5804   assert(IC > 0 && "Interleave count must be greater than 0.");
5805 
5806   // Interleave if we vectorized this loop and there is a reduction that could
5807   // benefit from interleaving.
5808   if (VF.isVector() && HasReductions) {
5809     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5810     return IC;
5811   }
5812 
5813   // For any scalar loop that either requires runtime checks or predication we
5814   // are better off leaving this to the unroller. Note that if we've already
5815   // vectorized the loop we will have done the runtime check and so interleaving
5816   // won't require further checks.
5817   bool ScalarInterleavingRequiresPredication =
5818       (VF.isScalar() && any_of(TheLoop->blocks(), [this](BasicBlock *BB) {
5819          return Legal->blockNeedsPredication(BB);
5820        }));
5821   bool ScalarInterleavingRequiresRuntimePointerCheck =
5822       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5823 
5824   // We want to interleave small loops in order to reduce the loop overhead and
5825   // potentially expose ILP opportunities.
5826   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5827                     << "LV: IC is " << IC << '\n'
5828                     << "LV: VF is " << VF << '\n');
5829   const bool AggressivelyInterleaveReductions =
5830       TTI.enableAggressiveInterleaving(HasReductions);
5831   if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5832       !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
5833     // We assume that the cost overhead is 1 and we use the cost model
5834     // to estimate the cost of the loop and interleave until the cost of the
5835     // loop overhead is about 5% of the cost of the loop.
5836     unsigned SmallIC =
5837         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5838 
5839     // Interleave until store/load ports (estimated by max interleave count) are
5840     // saturated.
5841     unsigned NumStores = Legal->getNumStores();
5842     unsigned NumLoads = Legal->getNumLoads();
5843     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5844     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5845 
5846     // There is little point in interleaving for reductions containing selects
5847     // and compares when VF=1 since it may just create more overhead than it's
5848     // worth for loops with small trip counts. This is because we still have to
5849     // do the final reduction after the loop.
5850     bool HasSelectCmpReductions =
5851         HasReductions &&
5852         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5853           const RecurrenceDescriptor &RdxDesc = Reduction.second;
5854           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
5855               RdxDesc.getRecurrenceKind());
5856         });
5857     if (HasSelectCmpReductions) {
5858       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
5859       return 1;
5860     }
5861 
5862     // If we have a scalar reduction (vector reductions are already dealt with
5863     // by this point), we can increase the critical path length if the loop
5864     // we're interleaving is inside another loop. For tree-wise reductions
5865     // set the limit to 2, and for ordered reductions it's best to disable
5866     // interleaving entirely.
5867     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5868       bool HasOrderedReductions =
5869           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5870             const RecurrenceDescriptor &RdxDesc = Reduction.second;
5871             return RdxDesc.isOrdered();
5872           });
5873       if (HasOrderedReductions) {
5874         LLVM_DEBUG(
5875             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
5876         return 1;
5877       }
5878 
5879       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5880       SmallIC = std::min(SmallIC, F);
5881       StoresIC = std::min(StoresIC, F);
5882       LoadsIC = std::min(LoadsIC, F);
5883     }
5884 
5885     if (EnableLoadStoreRuntimeInterleave &&
5886         std::max(StoresIC, LoadsIC) > SmallIC) {
5887       LLVM_DEBUG(
5888           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5889       return std::max(StoresIC, LoadsIC);
5890     }
5891 
5892     // If there are scalar reductions and TTI has enabled aggressive
5893     // interleaving for reductions, we will interleave to expose ILP.
5894     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5895         AggressivelyInterleaveReductions) {
5896       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5897       // Interleave no less than SmallIC but not as aggressive as the normal IC
5898       // to satisfy the rare situation when resources are too limited.
5899       return std::max(IC / 2, SmallIC);
5900     } else {
5901       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5902       return SmallIC;
5903     }
5904   }
5905 
5906   // Interleave if this is a large loop (small loops are already dealt with by
5907   // this point) that could benefit from interleaving.
5908   if (AggressivelyInterleaveReductions) {
5909     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5910     return IC;
5911   }
5912 
5913   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5914   return 1;
5915 }
5916 
5917 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5918 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5919   // This function calculates the register usage by measuring the highest number
5920   // of values that are alive at a single location. Obviously, this is a very
5921   // rough estimation. We scan the loop in a topological order in order and
5922   // assign a number to each instruction. We use RPO to ensure that defs are
5923   // met before their users. We assume that each instruction that has in-loop
5924   // users starts an interval. We record every time that an in-loop value is
5925   // used, so we have a list of the first and last occurrences of each
5926   // instruction. Next, we transpose this data structure into a multi map that
5927   // holds the list of intervals that *end* at a specific location. This multi
5928   // map allows us to perform a linear search. We scan the instructions linearly
5929   // and record each time that a new interval starts, by placing it in a set.
5930   // If we find this value in the multi-map then we remove it from the set.
5931   // The max register usage is the maximum size of the set.
5932   // We also search for instructions that are defined outside the loop, but are
5933   // used inside the loop. We need this number separately from the max-interval
5934   // usage number because when we unroll, loop-invariant values do not take
5935   // more register.
5936   LoopBlocksDFS DFS(TheLoop);
5937   DFS.perform(LI);
5938 
5939   RegisterUsage RU;
5940 
5941   // Each 'key' in the map opens a new interval. The values
5942   // of the map are the index of the 'last seen' usage of the
5943   // instruction that is the key.
5944   using IntervalMap = DenseMap<Instruction *, unsigned>;
5945 
5946   // Maps instruction to its index.
5947   SmallVector<Instruction *, 64> IdxToInstr;
5948   // Marks the end of each interval.
5949   IntervalMap EndPoint;
5950   // Saves the list of instruction indices that are used in the loop.
5951   SmallPtrSet<Instruction *, 8> Ends;
5952   // Saves the list of values that are used in the loop but are
5953   // defined outside the loop, such as arguments and constants.
5954   SmallPtrSet<Value *, 8> LoopInvariants;
5955 
5956   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5957     for (Instruction &I : BB->instructionsWithoutDebug()) {
5958       IdxToInstr.push_back(&I);
5959 
5960       // Save the end location of each USE.
5961       for (Value *U : I.operands()) {
5962         auto *Instr = dyn_cast<Instruction>(U);
5963 
5964         // Ignore non-instruction values such as arguments, constants, etc.
5965         if (!Instr)
5966           continue;
5967 
5968         // If this instruction is outside the loop then record it and continue.
5969         if (!TheLoop->contains(Instr)) {
5970           LoopInvariants.insert(Instr);
5971           continue;
5972         }
5973 
5974         // Overwrite previous end points.
5975         EndPoint[Instr] = IdxToInstr.size();
5976         Ends.insert(Instr);
5977       }
5978     }
5979   }
5980 
5981   // Saves the list of intervals that end with the index in 'key'.
5982   using InstrList = SmallVector<Instruction *, 2>;
5983   DenseMap<unsigned, InstrList> TransposeEnds;
5984 
5985   // Transpose the EndPoints to a list of values that end at each index.
5986   for (auto &Interval : EndPoint)
5987     TransposeEnds[Interval.second].push_back(Interval.first);
5988 
5989   SmallPtrSet<Instruction *, 8> OpenIntervals;
5990   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5991   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5992 
5993   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5994 
5995   // A lambda that gets the register usage for the given type and VF.
5996   const auto &TTICapture = TTI;
5997   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
5998     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
5999       return 0;
6000     InstructionCost::CostType RegUsage =
6001         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6002     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6003            "Nonsensical values for register usage.");
6004     return RegUsage;
6005   };
6006 
6007   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6008     Instruction *I = IdxToInstr[i];
6009 
6010     // Remove all of the instructions that end at this location.
6011     InstrList &List = TransposeEnds[i];
6012     for (Instruction *ToRemove : List)
6013       OpenIntervals.erase(ToRemove);
6014 
6015     // Ignore instructions that are never used within the loop.
6016     if (!Ends.count(I))
6017       continue;
6018 
6019     // Skip ignored values.
6020     if (ValuesToIgnore.count(I))
6021       continue;
6022 
6023     // For each VF find the maximum usage of registers.
6024     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6025       // Count the number of live intervals.
6026       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6027 
6028       if (VFs[j].isScalar()) {
6029         for (auto Inst : OpenIntervals) {
6030           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6031           if (RegUsage.find(ClassID) == RegUsage.end())
6032             RegUsage[ClassID] = 1;
6033           else
6034             RegUsage[ClassID] += 1;
6035         }
6036       } else {
6037         collectUniformsAndScalars(VFs[j]);
6038         for (auto Inst : OpenIntervals) {
6039           // Skip ignored values for VF > 1.
6040           if (VecValuesToIgnore.count(Inst))
6041             continue;
6042           if (isScalarAfterVectorization(Inst, VFs[j])) {
6043             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6044             if (RegUsage.find(ClassID) == RegUsage.end())
6045               RegUsage[ClassID] = 1;
6046             else
6047               RegUsage[ClassID] += 1;
6048           } else {
6049             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6050             if (RegUsage.find(ClassID) == RegUsage.end())
6051               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6052             else
6053               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6054           }
6055         }
6056       }
6057 
6058       for (auto& pair : RegUsage) {
6059         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6060           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6061         else
6062           MaxUsages[j][pair.first] = pair.second;
6063       }
6064     }
6065 
6066     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6067                       << OpenIntervals.size() << '\n');
6068 
6069     // Add the current instruction to the list of open intervals.
6070     OpenIntervals.insert(I);
6071   }
6072 
6073   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6074     SmallMapVector<unsigned, unsigned, 4> Invariant;
6075 
6076     for (auto Inst : LoopInvariants) {
6077       unsigned Usage =
6078           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6079       unsigned ClassID =
6080           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6081       if (Invariant.find(ClassID) == Invariant.end())
6082         Invariant[ClassID] = Usage;
6083       else
6084         Invariant[ClassID] += Usage;
6085     }
6086 
6087     LLVM_DEBUG({
6088       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6089       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6090              << " item\n";
6091       for (const auto &pair : MaxUsages[i]) {
6092         dbgs() << "LV(REG): RegisterClass: "
6093                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6094                << " registers\n";
6095       }
6096       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6097              << " item\n";
6098       for (const auto &pair : Invariant) {
6099         dbgs() << "LV(REG): RegisterClass: "
6100                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6101                << " registers\n";
6102       }
6103     });
6104 
6105     RU.LoopInvariantRegs = Invariant;
6106     RU.MaxLocalUsers = MaxUsages[i];
6107     RUs[i] = RU;
6108   }
6109 
6110   return RUs;
6111 }
6112 
6113 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
6114                                                            ElementCount VF) {
6115   // TODO: Cost model for emulated masked load/store is completely
6116   // broken. This hack guides the cost model to use an artificially
6117   // high enough value to practically disable vectorization with such
6118   // operations, except where previously deployed legality hack allowed
6119   // using very low cost values. This is to avoid regressions coming simply
6120   // from moving "masked load/store" check from legality to cost model.
6121   // Masked Load/Gather emulation was previously never allowed.
6122   // Limited number of Masked Store/Scatter emulation was allowed.
6123   assert(isPredicatedInst(I, VF) && "Expecting a scalar emulated instruction");
6124   return isa<LoadInst>(I) ||
6125          (isa<StoreInst>(I) &&
6126           NumPredStores > NumberOfStoresToPredicate);
6127 }
6128 
6129 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6130   // If we aren't vectorizing the loop, or if we've already collected the
6131   // instructions to scalarize, there's nothing to do. Collection may already
6132   // have occurred if we have a user-selected VF and are now computing the
6133   // expected cost for interleaving.
6134   if (VF.isScalar() || VF.isZero() ||
6135       InstsToScalarize.find(VF) != InstsToScalarize.end())
6136     return;
6137 
6138   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6139   // not profitable to scalarize any instructions, the presence of VF in the
6140   // map will indicate that we've analyzed it already.
6141   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6142 
6143   // Find all the instructions that are scalar with predication in the loop and
6144   // determine if it would be better to not if-convert the blocks they are in.
6145   // If so, we also record the instructions to scalarize.
6146   for (BasicBlock *BB : TheLoop->blocks()) {
6147     if (!blockNeedsPredicationForAnyReason(BB))
6148       continue;
6149     for (Instruction &I : *BB)
6150       if (isScalarWithPredication(&I, VF)) {
6151         ScalarCostsTy ScalarCosts;
6152         // Do not apply discount if scalable, because that would lead to
6153         // invalid scalarization costs.
6154         // Do not apply discount logic if hacked cost is needed
6155         // for emulated masked memrefs.
6156         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
6157             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6158           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6159         // Remember that BB will remain after vectorization.
6160         PredicatedBBsAfterVectorization.insert(BB);
6161       }
6162   }
6163 }
6164 
6165 int LoopVectorizationCostModel::computePredInstDiscount(
6166     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6167   assert(!isUniformAfterVectorization(PredInst, VF) &&
6168          "Instruction marked uniform-after-vectorization will be predicated");
6169 
6170   // Initialize the discount to zero, meaning that the scalar version and the
6171   // vector version cost the same.
6172   InstructionCost Discount = 0;
6173 
6174   // Holds instructions to analyze. The instructions we visit are mapped in
6175   // ScalarCosts. Those instructions are the ones that would be scalarized if
6176   // we find that the scalar version costs less.
6177   SmallVector<Instruction *, 8> Worklist;
6178 
6179   // Returns true if the given instruction can be scalarized.
6180   auto canBeScalarized = [&](Instruction *I) -> bool {
6181     // We only attempt to scalarize instructions forming a single-use chain
6182     // from the original predicated block that would otherwise be vectorized.
6183     // Although not strictly necessary, we give up on instructions we know will
6184     // already be scalar to avoid traversing chains that are unlikely to be
6185     // beneficial.
6186     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6187         isScalarAfterVectorization(I, VF))
6188       return false;
6189 
6190     // If the instruction is scalar with predication, it will be analyzed
6191     // separately. We ignore it within the context of PredInst.
6192     if (isScalarWithPredication(I, VF))
6193       return false;
6194 
6195     // If any of the instruction's operands are uniform after vectorization,
6196     // the instruction cannot be scalarized. This prevents, for example, a
6197     // masked load from being scalarized.
6198     //
6199     // We assume we will only emit a value for lane zero of an instruction
6200     // marked uniform after vectorization, rather than VF identical values.
6201     // Thus, if we scalarize an instruction that uses a uniform, we would
6202     // create uses of values corresponding to the lanes we aren't emitting code
6203     // for. This behavior can be changed by allowing getScalarValue to clone
6204     // the lane zero values for uniforms rather than asserting.
6205     for (Use &U : I->operands())
6206       if (auto *J = dyn_cast<Instruction>(U.get()))
6207         if (isUniformAfterVectorization(J, VF))
6208           return false;
6209 
6210     // Otherwise, we can scalarize the instruction.
6211     return true;
6212   };
6213 
6214   // Compute the expected cost discount from scalarizing the entire expression
6215   // feeding the predicated instruction. We currently only consider expressions
6216   // that are single-use instruction chains.
6217   Worklist.push_back(PredInst);
6218   while (!Worklist.empty()) {
6219     Instruction *I = Worklist.pop_back_val();
6220 
6221     // If we've already analyzed the instruction, there's nothing to do.
6222     if (ScalarCosts.find(I) != ScalarCosts.end())
6223       continue;
6224 
6225     // Compute the cost of the vector instruction. Note that this cost already
6226     // includes the scalarization overhead of the predicated instruction.
6227     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6228 
6229     // Compute the cost of the scalarized instruction. This cost is the cost of
6230     // the instruction as if it wasn't if-converted and instead remained in the
6231     // predicated block. We will scale this cost by block probability after
6232     // computing the scalarization overhead.
6233     InstructionCost ScalarCost =
6234         VF.getFixedValue() *
6235         getInstructionCost(I, ElementCount::getFixed(1)).first;
6236 
6237     // Compute the scalarization overhead of needed insertelement instructions
6238     // and phi nodes.
6239     if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
6240       ScalarCost += TTI.getScalarizationOverhead(
6241           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6242           APInt::getAllOnes(VF.getFixedValue()), true, false);
6243       ScalarCost +=
6244           VF.getFixedValue() *
6245           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6246     }
6247 
6248     // Compute the scalarization overhead of needed extractelement
6249     // instructions. For each of the instruction's operands, if the operand can
6250     // be scalarized, add it to the worklist; otherwise, account for the
6251     // overhead.
6252     for (Use &U : I->operands())
6253       if (auto *J = dyn_cast<Instruction>(U.get())) {
6254         assert(VectorType::isValidElementType(J->getType()) &&
6255                "Instruction has non-scalar type");
6256         if (canBeScalarized(J))
6257           Worklist.push_back(J);
6258         else if (needsExtract(J, VF)) {
6259           ScalarCost += TTI.getScalarizationOverhead(
6260               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6261               APInt::getAllOnes(VF.getFixedValue()), false, true);
6262         }
6263       }
6264 
6265     // Scale the total scalar cost by block probability.
6266     ScalarCost /= getReciprocalPredBlockProb();
6267 
6268     // Compute the discount. A non-negative discount means the vector version
6269     // of the instruction costs more, and scalarizing would be beneficial.
6270     Discount += VectorCost - ScalarCost;
6271     ScalarCosts[I] = ScalarCost;
6272   }
6273 
6274   return *Discount.getValue();
6275 }
6276 
6277 LoopVectorizationCostModel::VectorizationCostTy
6278 LoopVectorizationCostModel::expectedCost(
6279     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6280   VectorizationCostTy Cost;
6281 
6282   // For each block.
6283   for (BasicBlock *BB : TheLoop->blocks()) {
6284     VectorizationCostTy BlockCost;
6285 
6286     // For each instruction in the old loop.
6287     for (Instruction &I : BB->instructionsWithoutDebug()) {
6288       // Skip ignored values.
6289       if (ValuesToIgnore.count(&I) ||
6290           (VF.isVector() && VecValuesToIgnore.count(&I)))
6291         continue;
6292 
6293       VectorizationCostTy C = getInstructionCost(&I, VF);
6294 
6295       // Check if we should override the cost.
6296       if (C.first.isValid() &&
6297           ForceTargetInstructionCost.getNumOccurrences() > 0)
6298         C.first = InstructionCost(ForceTargetInstructionCost);
6299 
6300       // Keep a list of instructions with invalid costs.
6301       if (Invalid && !C.first.isValid())
6302         Invalid->emplace_back(&I, VF);
6303 
6304       BlockCost.first += C.first;
6305       BlockCost.second |= C.second;
6306       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6307                         << " for VF " << VF << " For instruction: " << I
6308                         << '\n');
6309     }
6310 
6311     // If we are vectorizing a predicated block, it will have been
6312     // if-converted. This means that the block's instructions (aside from
6313     // stores and instructions that may divide by zero) will now be
6314     // unconditionally executed. For the scalar case, we may not always execute
6315     // the predicated block, if it is an if-else block. Thus, scale the block's
6316     // cost by the probability of executing it. blockNeedsPredication from
6317     // Legal is used so as to not include all blocks in tail folded loops.
6318     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6319       BlockCost.first /= getReciprocalPredBlockProb();
6320 
6321     Cost.first += BlockCost.first;
6322     Cost.second |= BlockCost.second;
6323   }
6324 
6325   return Cost;
6326 }
6327 
6328 /// Gets Address Access SCEV after verifying that the access pattern
6329 /// is loop invariant except the induction variable dependence.
6330 ///
6331 /// This SCEV can be sent to the Target in order to estimate the address
6332 /// calculation cost.
6333 static const SCEV *getAddressAccessSCEV(
6334               Value *Ptr,
6335               LoopVectorizationLegality *Legal,
6336               PredicatedScalarEvolution &PSE,
6337               const Loop *TheLoop) {
6338 
6339   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6340   if (!Gep)
6341     return nullptr;
6342 
6343   // We are looking for a gep with all loop invariant indices except for one
6344   // which should be an induction variable.
6345   auto SE = PSE.getSE();
6346   unsigned NumOperands = Gep->getNumOperands();
6347   for (unsigned i = 1; i < NumOperands; ++i) {
6348     Value *Opd = Gep->getOperand(i);
6349     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6350         !Legal->isInductionVariable(Opd))
6351       return nullptr;
6352   }
6353 
6354   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6355   return PSE.getSCEV(Ptr);
6356 }
6357 
6358 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6359   return Legal->hasStride(I->getOperand(0)) ||
6360          Legal->hasStride(I->getOperand(1));
6361 }
6362 
6363 InstructionCost
6364 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6365                                                         ElementCount VF) {
6366   assert(VF.isVector() &&
6367          "Scalarization cost of instruction implies vectorization.");
6368   if (VF.isScalable())
6369     return InstructionCost::getInvalid();
6370 
6371   Type *ValTy = getLoadStoreType(I);
6372   auto SE = PSE.getSE();
6373 
6374   unsigned AS = getLoadStoreAddressSpace(I);
6375   Value *Ptr = getLoadStorePointerOperand(I);
6376   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6377   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6378   //       that it is being called from this specific place.
6379 
6380   // Figure out whether the access is strided and get the stride value
6381   // if it's known in compile time
6382   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6383 
6384   // Get the cost of the scalar memory instruction and address computation.
6385   InstructionCost Cost =
6386       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6387 
6388   // Don't pass *I here, since it is scalar but will actually be part of a
6389   // vectorized loop where the user of it is a vectorized instruction.
6390   const Align Alignment = getLoadStoreAlignment(I);
6391   Cost += VF.getKnownMinValue() *
6392           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6393                               AS, TTI::TCK_RecipThroughput);
6394 
6395   // Get the overhead of the extractelement and insertelement instructions
6396   // we might create due to scalarization.
6397   Cost += getScalarizationOverhead(I, VF);
6398 
6399   // If we have a predicated load/store, it will need extra i1 extracts and
6400   // conditional branches, but may not be executed for each vector lane. Scale
6401   // the cost by the probability of executing the predicated block.
6402   if (isPredicatedInst(I, VF)) {
6403     Cost /= getReciprocalPredBlockProb();
6404 
6405     // Add the cost of an i1 extract and a branch
6406     auto *Vec_i1Ty =
6407         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6408     Cost += TTI.getScalarizationOverhead(
6409         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6410         /*Insert=*/false, /*Extract=*/true);
6411     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6412 
6413     if (useEmulatedMaskMemRefHack(I, VF))
6414       // Artificially setting to a high enough value to practically disable
6415       // vectorization with such operations.
6416       Cost = 3000000;
6417   }
6418 
6419   return Cost;
6420 }
6421 
6422 InstructionCost
6423 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6424                                                     ElementCount VF) {
6425   Type *ValTy = getLoadStoreType(I);
6426   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6427   Value *Ptr = getLoadStorePointerOperand(I);
6428   unsigned AS = getLoadStoreAddressSpace(I);
6429   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6430   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6431 
6432   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6433          "Stride should be 1 or -1 for consecutive memory access");
6434   const Align Alignment = getLoadStoreAlignment(I);
6435   InstructionCost Cost = 0;
6436   if (Legal->isMaskRequired(I))
6437     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6438                                       CostKind);
6439   else
6440     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6441                                 CostKind, I);
6442 
6443   bool Reverse = ConsecutiveStride < 0;
6444   if (Reverse)
6445     Cost +=
6446         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6447   return Cost;
6448 }
6449 
6450 InstructionCost
6451 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6452                                                 ElementCount VF) {
6453   assert(Legal->isUniformMemOp(*I));
6454 
6455   Type *ValTy = getLoadStoreType(I);
6456   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6457   const Align Alignment = getLoadStoreAlignment(I);
6458   unsigned AS = getLoadStoreAddressSpace(I);
6459   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6460   if (isa<LoadInst>(I)) {
6461     return TTI.getAddressComputationCost(ValTy) +
6462            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6463                                CostKind) +
6464            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6465   }
6466   StoreInst *SI = cast<StoreInst>(I);
6467 
6468   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6469   return TTI.getAddressComputationCost(ValTy) +
6470          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6471                              CostKind) +
6472          (isLoopInvariantStoreValue
6473               ? 0
6474               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6475                                        VF.getKnownMinValue() - 1));
6476 }
6477 
6478 InstructionCost
6479 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6480                                                  ElementCount VF) {
6481   Type *ValTy = getLoadStoreType(I);
6482   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6483   const Align Alignment = getLoadStoreAlignment(I);
6484   const Value *Ptr = getLoadStorePointerOperand(I);
6485 
6486   return TTI.getAddressComputationCost(VectorTy) +
6487          TTI.getGatherScatterOpCost(
6488              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6489              TargetTransformInfo::TCK_RecipThroughput, I);
6490 }
6491 
6492 InstructionCost
6493 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6494                                                    ElementCount VF) {
6495   // TODO: Once we have support for interleaving with scalable vectors
6496   // we can calculate the cost properly here.
6497   if (VF.isScalable())
6498     return InstructionCost::getInvalid();
6499 
6500   Type *ValTy = getLoadStoreType(I);
6501   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6502   unsigned AS = getLoadStoreAddressSpace(I);
6503 
6504   auto Group = getInterleavedAccessGroup(I);
6505   assert(Group && "Fail to get an interleaved access group.");
6506 
6507   unsigned InterleaveFactor = Group->getFactor();
6508   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6509 
6510   // Holds the indices of existing members in the interleaved group.
6511   SmallVector<unsigned, 4> Indices;
6512   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6513     if (Group->getMember(IF))
6514       Indices.push_back(IF);
6515 
6516   // Calculate the cost of the whole interleaved group.
6517   bool UseMaskForGaps =
6518       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6519       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6520   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6521       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6522       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6523 
6524   if (Group->isReverse()) {
6525     // TODO: Add support for reversed masked interleaved access.
6526     assert(!Legal->isMaskRequired(I) &&
6527            "Reverse masked interleaved access not supported.");
6528     Cost +=
6529         Group->getNumMembers() *
6530         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6531   }
6532   return Cost;
6533 }
6534 
6535 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6536     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6537   using namespace llvm::PatternMatch;
6538   // Early exit for no inloop reductions
6539   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6540     return None;
6541   auto *VectorTy = cast<VectorType>(Ty);
6542 
6543   // We are looking for a pattern of, and finding the minimal acceptable cost:
6544   //  reduce(mul(ext(A), ext(B))) or
6545   //  reduce(mul(A, B)) or
6546   //  reduce(ext(A)) or
6547   //  reduce(A).
6548   // The basic idea is that we walk down the tree to do that, finding the root
6549   // reduction instruction in InLoopReductionImmediateChains. From there we find
6550   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6551   // of the components. If the reduction cost is lower then we return it for the
6552   // reduction instruction and 0 for the other instructions in the pattern. If
6553   // it is not we return an invalid cost specifying the orignal cost method
6554   // should be used.
6555   Instruction *RetI = I;
6556   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6557     if (!RetI->hasOneUser())
6558       return None;
6559     RetI = RetI->user_back();
6560   }
6561   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6562       RetI->user_back()->getOpcode() == Instruction::Add) {
6563     if (!RetI->hasOneUser())
6564       return None;
6565     RetI = RetI->user_back();
6566   }
6567 
6568   // Test if the found instruction is a reduction, and if not return an invalid
6569   // cost specifying the parent to use the original cost modelling.
6570   if (!InLoopReductionImmediateChains.count(RetI))
6571     return None;
6572 
6573   // Find the reduction this chain is a part of and calculate the basic cost of
6574   // the reduction on its own.
6575   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6576   Instruction *ReductionPhi = LastChain;
6577   while (!isa<PHINode>(ReductionPhi))
6578     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6579 
6580   const RecurrenceDescriptor &RdxDesc =
6581       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6582 
6583   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6584       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6585 
6586   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6587   // normal fmul instruction to the cost of the fadd reduction.
6588   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6589     BaseCost +=
6590         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6591 
6592   // If we're using ordered reductions then we can just return the base cost
6593   // here, since getArithmeticReductionCost calculates the full ordered
6594   // reduction cost when FP reassociation is not allowed.
6595   if (useOrderedReductions(RdxDesc))
6596     return BaseCost;
6597 
6598   // Get the operand that was not the reduction chain and match it to one of the
6599   // patterns, returning the better cost if it is found.
6600   Instruction *RedOp = RetI->getOperand(1) == LastChain
6601                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6602                            : dyn_cast<Instruction>(RetI->getOperand(1));
6603 
6604   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6605 
6606   Instruction *Op0, *Op1;
6607   if (RedOp &&
6608       match(RedOp,
6609             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6610       match(Op0, m_ZExtOrSExt(m_Value())) &&
6611       Op0->getOpcode() == Op1->getOpcode() &&
6612       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6613       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6614       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6615 
6616     // Matched reduce(ext(mul(ext(A), ext(B)))
6617     // Note that the extend opcodes need to all match, or if A==B they will have
6618     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6619     // which is equally fine.
6620     bool IsUnsigned = isa<ZExtInst>(Op0);
6621     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6622     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6623 
6624     InstructionCost ExtCost =
6625         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6626                              TTI::CastContextHint::None, CostKind, Op0);
6627     InstructionCost MulCost =
6628         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6629     InstructionCost Ext2Cost =
6630         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6631                              TTI::CastContextHint::None, CostKind, RedOp);
6632 
6633     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6634         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6635         CostKind);
6636 
6637     if (RedCost.isValid() &&
6638         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6639       return I == RetI ? RedCost : 0;
6640   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
6641              !TheLoop->isLoopInvariant(RedOp)) {
6642     // Matched reduce(ext(A))
6643     bool IsUnsigned = isa<ZExtInst>(RedOp);
6644     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6645     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6646         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6647         CostKind);
6648 
6649     InstructionCost ExtCost =
6650         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6651                              TTI::CastContextHint::None, CostKind, RedOp);
6652     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6653       return I == RetI ? RedCost : 0;
6654   } else if (RedOp &&
6655              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
6656     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
6657         Op0->getOpcode() == Op1->getOpcode() &&
6658         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6659       bool IsUnsigned = isa<ZExtInst>(Op0);
6660       Type *Op0Ty = Op0->getOperand(0)->getType();
6661       Type *Op1Ty = Op1->getOperand(0)->getType();
6662       Type *LargestOpTy =
6663           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
6664                                                                     : Op0Ty;
6665       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
6666 
6667       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
6668       // different sizes. We take the largest type as the ext to reduce, and add
6669       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
6670       InstructionCost ExtCost0 = TTI.getCastInstrCost(
6671           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
6672           TTI::CastContextHint::None, CostKind, Op0);
6673       InstructionCost ExtCost1 = TTI.getCastInstrCost(
6674           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
6675           TTI::CastContextHint::None, CostKind, Op1);
6676       InstructionCost MulCost =
6677           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6678 
6679       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6680           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6681           CostKind);
6682       InstructionCost ExtraExtCost = 0;
6683       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6684         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6685         ExtraExtCost = TTI.getCastInstrCost(
6686             ExtraExtOp->getOpcode(), ExtType,
6687             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
6688             TTI::CastContextHint::None, CostKind, ExtraExtOp);
6689       }
6690 
6691       if (RedCost.isValid() &&
6692           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6693         return I == RetI ? RedCost : 0;
6694     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
6695       // Matched reduce(mul())
6696       InstructionCost MulCost =
6697           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6698 
6699       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6700           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6701           CostKind);
6702 
6703       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6704         return I == RetI ? RedCost : 0;
6705     }
6706   }
6707 
6708   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
6709 }
6710 
6711 InstructionCost
6712 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6713                                                      ElementCount VF) {
6714   // Calculate scalar cost only. Vectorization cost should be ready at this
6715   // moment.
6716   if (VF.isScalar()) {
6717     Type *ValTy = getLoadStoreType(I);
6718     const Align Alignment = getLoadStoreAlignment(I);
6719     unsigned AS = getLoadStoreAddressSpace(I);
6720 
6721     return TTI.getAddressComputationCost(ValTy) +
6722            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6723                                TTI::TCK_RecipThroughput, I);
6724   }
6725   return getWideningCost(I, VF);
6726 }
6727 
6728 LoopVectorizationCostModel::VectorizationCostTy
6729 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6730                                                ElementCount VF) {
6731   // If we know that this instruction will remain uniform, check the cost of
6732   // the scalar version.
6733   if (isUniformAfterVectorization(I, VF))
6734     VF = ElementCount::getFixed(1);
6735 
6736   if (VF.isVector() && isProfitableToScalarize(I, VF))
6737     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6738 
6739   // Forced scalars do not have any scalarization overhead.
6740   auto ForcedScalar = ForcedScalars.find(VF);
6741   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6742     auto InstSet = ForcedScalar->second;
6743     if (InstSet.count(I))
6744       return VectorizationCostTy(
6745           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6746            VF.getKnownMinValue()),
6747           false);
6748   }
6749 
6750   Type *VectorTy;
6751   InstructionCost C = getInstructionCost(I, VF, VectorTy);
6752 
6753   bool TypeNotScalarized = false;
6754   if (VF.isVector() && VectorTy->isVectorTy()) {
6755     unsigned NumParts = TTI.getNumberOfParts(VectorTy);
6756     if (NumParts)
6757       TypeNotScalarized = NumParts < VF.getKnownMinValue();
6758     else
6759       C = InstructionCost::getInvalid();
6760   }
6761   return VectorizationCostTy(C, TypeNotScalarized);
6762 }
6763 
6764 InstructionCost
6765 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6766                                                      ElementCount VF) const {
6767 
6768   // There is no mechanism yet to create a scalable scalarization loop,
6769   // so this is currently Invalid.
6770   if (VF.isScalable())
6771     return InstructionCost::getInvalid();
6772 
6773   if (VF.isScalar())
6774     return 0;
6775 
6776   InstructionCost Cost = 0;
6777   Type *RetTy = ToVectorTy(I->getType(), VF);
6778   if (!RetTy->isVoidTy() &&
6779       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6780     Cost += TTI.getScalarizationOverhead(
6781         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
6782         false);
6783 
6784   // Some targets keep addresses scalar.
6785   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6786     return Cost;
6787 
6788   // Some targets support efficient element stores.
6789   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6790     return Cost;
6791 
6792   // Collect operands to consider.
6793   CallInst *CI = dyn_cast<CallInst>(I);
6794   Instruction::op_range Ops = CI ? CI->args() : I->operands();
6795 
6796   // Skip operands that do not require extraction/scalarization and do not incur
6797   // any overhead.
6798   SmallVector<Type *> Tys;
6799   for (auto *V : filterExtractingOperands(Ops, VF))
6800     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
6801   return Cost + TTI.getOperandsScalarizationOverhead(
6802                     filterExtractingOperands(Ops, VF), Tys);
6803 }
6804 
6805 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6806   if (VF.isScalar())
6807     return;
6808   NumPredStores = 0;
6809   for (BasicBlock *BB : TheLoop->blocks()) {
6810     // For each instruction in the old loop.
6811     for (Instruction &I : *BB) {
6812       Value *Ptr =  getLoadStorePointerOperand(&I);
6813       if (!Ptr)
6814         continue;
6815 
6816       // TODO: We should generate better code and update the cost model for
6817       // predicated uniform stores. Today they are treated as any other
6818       // predicated store (see added test cases in
6819       // invariant-store-vectorization.ll).
6820       if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
6821         NumPredStores++;
6822 
6823       if (Legal->isUniformMemOp(I)) {
6824         // TODO: Avoid replicating loads and stores instead of
6825         // relying on instcombine to remove them.
6826         // Load: Scalar load + broadcast
6827         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6828         InstructionCost Cost;
6829         if (isa<StoreInst>(&I) && VF.isScalable() &&
6830             isLegalGatherOrScatter(&I, VF)) {
6831           Cost = getGatherScatterCost(&I, VF);
6832           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
6833         } else {
6834           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
6835                  "Cannot yet scalarize uniform stores");
6836           Cost = getUniformMemOpCost(&I, VF);
6837           setWideningDecision(&I, VF, CM_Scalarize, Cost);
6838         }
6839         continue;
6840       }
6841 
6842       // We assume that widening is the best solution when possible.
6843       if (memoryInstructionCanBeWidened(&I, VF)) {
6844         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
6845         int ConsecutiveStride = Legal->isConsecutivePtr(
6846             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
6847         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6848                "Expected consecutive stride.");
6849         InstWidening Decision =
6850             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6851         setWideningDecision(&I, VF, Decision, Cost);
6852         continue;
6853       }
6854 
6855       // Choose between Interleaving, Gather/Scatter or Scalarization.
6856       InstructionCost InterleaveCost = InstructionCost::getInvalid();
6857       unsigned NumAccesses = 1;
6858       if (isAccessInterleaved(&I)) {
6859         auto Group = getInterleavedAccessGroup(&I);
6860         assert(Group && "Fail to get an interleaved access group.");
6861 
6862         // Make one decision for the whole group.
6863         if (getWideningDecision(&I, VF) != CM_Unknown)
6864           continue;
6865 
6866         NumAccesses = Group->getNumMembers();
6867         if (interleavedAccessCanBeWidened(&I, VF))
6868           InterleaveCost = getInterleaveGroupCost(&I, VF);
6869       }
6870 
6871       InstructionCost GatherScatterCost =
6872           isLegalGatherOrScatter(&I, VF)
6873               ? getGatherScatterCost(&I, VF) * NumAccesses
6874               : InstructionCost::getInvalid();
6875 
6876       InstructionCost ScalarizationCost =
6877           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6878 
6879       // Choose better solution for the current VF,
6880       // write down this decision and use it during vectorization.
6881       InstructionCost Cost;
6882       InstWidening Decision;
6883       if (InterleaveCost <= GatherScatterCost &&
6884           InterleaveCost < ScalarizationCost) {
6885         Decision = CM_Interleave;
6886         Cost = InterleaveCost;
6887       } else if (GatherScatterCost < ScalarizationCost) {
6888         Decision = CM_GatherScatter;
6889         Cost = GatherScatterCost;
6890       } else {
6891         Decision = CM_Scalarize;
6892         Cost = ScalarizationCost;
6893       }
6894       // If the instructions belongs to an interleave group, the whole group
6895       // receives the same decision. The whole group receives the cost, but
6896       // the cost will actually be assigned to one instruction.
6897       if (auto Group = getInterleavedAccessGroup(&I))
6898         setWideningDecision(Group, VF, Decision, Cost);
6899       else
6900         setWideningDecision(&I, VF, Decision, Cost);
6901     }
6902   }
6903 
6904   // Make sure that any load of address and any other address computation
6905   // remains scalar unless there is gather/scatter support. This avoids
6906   // inevitable extracts into address registers, and also has the benefit of
6907   // activating LSR more, since that pass can't optimize vectorized
6908   // addresses.
6909   if (TTI.prefersVectorizedAddressing())
6910     return;
6911 
6912   // Start with all scalar pointer uses.
6913   SmallPtrSet<Instruction *, 8> AddrDefs;
6914   for (BasicBlock *BB : TheLoop->blocks())
6915     for (Instruction &I : *BB) {
6916       Instruction *PtrDef =
6917         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6918       if (PtrDef && TheLoop->contains(PtrDef) &&
6919           getWideningDecision(&I, VF) != CM_GatherScatter)
6920         AddrDefs.insert(PtrDef);
6921     }
6922 
6923   // Add all instructions used to generate the addresses.
6924   SmallVector<Instruction *, 4> Worklist;
6925   append_range(Worklist, AddrDefs);
6926   while (!Worklist.empty()) {
6927     Instruction *I = Worklist.pop_back_val();
6928     for (auto &Op : I->operands())
6929       if (auto *InstOp = dyn_cast<Instruction>(Op))
6930         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6931             AddrDefs.insert(InstOp).second)
6932           Worklist.push_back(InstOp);
6933   }
6934 
6935   for (auto *I : AddrDefs) {
6936     if (isa<LoadInst>(I)) {
6937       // Setting the desired widening decision should ideally be handled in
6938       // by cost functions, but since this involves the task of finding out
6939       // if the loaded register is involved in an address computation, it is
6940       // instead changed here when we know this is the case.
6941       InstWidening Decision = getWideningDecision(I, VF);
6942       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6943         // Scalarize a widened load of address.
6944         setWideningDecision(
6945             I, VF, CM_Scalarize,
6946             (VF.getKnownMinValue() *
6947              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6948       else if (auto Group = getInterleavedAccessGroup(I)) {
6949         // Scalarize an interleave group of address loads.
6950         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6951           if (Instruction *Member = Group->getMember(I))
6952             setWideningDecision(
6953                 Member, VF, CM_Scalarize,
6954                 (VF.getKnownMinValue() *
6955                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6956         }
6957       }
6958     } else
6959       // Make sure I gets scalarized and a cost estimate without
6960       // scalarization overhead.
6961       ForcedScalars[VF].insert(I);
6962   }
6963 }
6964 
6965 InstructionCost
6966 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
6967                                                Type *&VectorTy) {
6968   Type *RetTy = I->getType();
6969   if (canTruncateToMinimalBitwidth(I, VF))
6970     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6971   auto SE = PSE.getSE();
6972   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6973 
6974   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
6975                                                 ElementCount VF) -> bool {
6976     if (VF.isScalar())
6977       return true;
6978 
6979     auto Scalarized = InstsToScalarize.find(VF);
6980     assert(Scalarized != InstsToScalarize.end() &&
6981            "VF not yet analyzed for scalarization profitability");
6982     return !Scalarized->second.count(I) &&
6983            llvm::all_of(I->users(), [&](User *U) {
6984              auto *UI = cast<Instruction>(U);
6985              return !Scalarized->second.count(UI);
6986            });
6987   };
6988   (void) hasSingleCopyAfterVectorization;
6989 
6990   if (isScalarAfterVectorization(I, VF)) {
6991     // With the exception of GEPs and PHIs, after scalarization there should
6992     // only be one copy of the instruction generated in the loop. This is
6993     // because the VF is either 1, or any instructions that need scalarizing
6994     // have already been dealt with by the the time we get here. As a result,
6995     // it means we don't have to multiply the instruction cost by VF.
6996     assert(I->getOpcode() == Instruction::GetElementPtr ||
6997            I->getOpcode() == Instruction::PHI ||
6998            (I->getOpcode() == Instruction::BitCast &&
6999             I->getType()->isPointerTy()) ||
7000            hasSingleCopyAfterVectorization(I, VF));
7001     VectorTy = RetTy;
7002   } else
7003     VectorTy = ToVectorTy(RetTy, VF);
7004 
7005   // TODO: We need to estimate the cost of intrinsic calls.
7006   switch (I->getOpcode()) {
7007   case Instruction::GetElementPtr:
7008     // We mark this instruction as zero-cost because the cost of GEPs in
7009     // vectorized code depends on whether the corresponding memory instruction
7010     // is scalarized or not. Therefore, we handle GEPs with the memory
7011     // instruction cost.
7012     return 0;
7013   case Instruction::Br: {
7014     // In cases of scalarized and predicated instructions, there will be VF
7015     // predicated blocks in the vectorized loop. Each branch around these
7016     // blocks requires also an extract of its vector compare i1 element.
7017     bool ScalarPredicatedBB = false;
7018     BranchInst *BI = cast<BranchInst>(I);
7019     if (VF.isVector() && BI->isConditional() &&
7020         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7021          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7022       ScalarPredicatedBB = true;
7023 
7024     if (ScalarPredicatedBB) {
7025       // Not possible to scalarize scalable vector with predicated instructions.
7026       if (VF.isScalable())
7027         return InstructionCost::getInvalid();
7028       // Return cost for branches around scalarized and predicated blocks.
7029       auto *Vec_i1Ty =
7030           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7031       return (
7032           TTI.getScalarizationOverhead(
7033               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7034           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7035     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7036       // The back-edge branch will remain, as will all scalar branches.
7037       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7038     else
7039       // This branch will be eliminated by if-conversion.
7040       return 0;
7041     // Note: We currently assume zero cost for an unconditional branch inside
7042     // a predicated block since it will become a fall-through, although we
7043     // may decide in the future to call TTI for all branches.
7044   }
7045   case Instruction::PHI: {
7046     auto *Phi = cast<PHINode>(I);
7047 
7048     // First-order recurrences are replaced by vector shuffles inside the loop.
7049     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7050     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7051       return TTI.getShuffleCost(
7052           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7053           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7054 
7055     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7056     // converted into select instructions. We require N - 1 selects per phi
7057     // node, where N is the number of incoming values.
7058     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7059       return (Phi->getNumIncomingValues() - 1) *
7060              TTI.getCmpSelInstrCost(
7061                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7062                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7063                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7064 
7065     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7066   }
7067   case Instruction::UDiv:
7068   case Instruction::SDiv:
7069   case Instruction::URem:
7070   case Instruction::SRem:
7071     // If we have a predicated instruction, it may not be executed for each
7072     // vector lane. Get the scalarization cost and scale this amount by the
7073     // probability of executing the predicated block. If the instruction is not
7074     // predicated, we fall through to the next case.
7075     if (VF.isVector() && isScalarWithPredication(I, VF)) {
7076       InstructionCost Cost = 0;
7077 
7078       // These instructions have a non-void type, so account for the phi nodes
7079       // that we will create. This cost is likely to be zero. The phi node
7080       // cost, if any, should be scaled by the block probability because it
7081       // models a copy at the end of each predicated block.
7082       Cost += VF.getKnownMinValue() *
7083               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7084 
7085       // The cost of the non-predicated instruction.
7086       Cost += VF.getKnownMinValue() *
7087               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7088 
7089       // The cost of insertelement and extractelement instructions needed for
7090       // scalarization.
7091       Cost += getScalarizationOverhead(I, VF);
7092 
7093       // Scale the cost by the probability of executing the predicated blocks.
7094       // This assumes the predicated block for each vector lane is equally
7095       // likely.
7096       return Cost / getReciprocalPredBlockProb();
7097     }
7098     LLVM_FALLTHROUGH;
7099   case Instruction::Add:
7100   case Instruction::FAdd:
7101   case Instruction::Sub:
7102   case Instruction::FSub:
7103   case Instruction::Mul:
7104   case Instruction::FMul:
7105   case Instruction::FDiv:
7106   case Instruction::FRem:
7107   case Instruction::Shl:
7108   case Instruction::LShr:
7109   case Instruction::AShr:
7110   case Instruction::And:
7111   case Instruction::Or:
7112   case Instruction::Xor: {
7113     // Since we will replace the stride by 1 the multiplication should go away.
7114     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7115       return 0;
7116 
7117     // Detect reduction patterns
7118     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7119       return *RedCost;
7120 
7121     // Certain instructions can be cheaper to vectorize if they have a constant
7122     // second vector operand. One example of this are shifts on x86.
7123     Value *Op2 = I->getOperand(1);
7124     TargetTransformInfo::OperandValueProperties Op2VP;
7125     TargetTransformInfo::OperandValueKind Op2VK =
7126         TTI.getOperandInfo(Op2, Op2VP);
7127     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7128       Op2VK = TargetTransformInfo::OK_UniformValue;
7129 
7130     SmallVector<const Value *, 4> Operands(I->operand_values());
7131     return TTI.getArithmeticInstrCost(
7132         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7133         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7134   }
7135   case Instruction::FNeg: {
7136     return TTI.getArithmeticInstrCost(
7137         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7138         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7139         TargetTransformInfo::OP_None, I->getOperand(0), I);
7140   }
7141   case Instruction::Select: {
7142     SelectInst *SI = cast<SelectInst>(I);
7143     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7144     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7145 
7146     const Value *Op0, *Op1;
7147     using namespace llvm::PatternMatch;
7148     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7149                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7150       // select x, y, false --> x & y
7151       // select x, true, y --> x | y
7152       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7153       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7154       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7155       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7156       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7157               Op1->getType()->getScalarSizeInBits() == 1);
7158 
7159       SmallVector<const Value *, 2> Operands{Op0, Op1};
7160       return TTI.getArithmeticInstrCost(
7161           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7162           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7163     }
7164 
7165     Type *CondTy = SI->getCondition()->getType();
7166     if (!ScalarCond)
7167       CondTy = VectorType::get(CondTy, VF);
7168 
7169     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7170     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7171       Pred = Cmp->getPredicate();
7172     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7173                                   CostKind, I);
7174   }
7175   case Instruction::ICmp:
7176   case Instruction::FCmp: {
7177     Type *ValTy = I->getOperand(0)->getType();
7178     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7179     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7180       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7181     VectorTy = ToVectorTy(ValTy, VF);
7182     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7183                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7184                                   I);
7185   }
7186   case Instruction::Store:
7187   case Instruction::Load: {
7188     ElementCount Width = VF;
7189     if (Width.isVector()) {
7190       InstWidening Decision = getWideningDecision(I, Width);
7191       assert(Decision != CM_Unknown &&
7192              "CM decision should be taken at this point");
7193       if (Decision == CM_Scalarize)
7194         Width = ElementCount::getFixed(1);
7195     }
7196     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7197     return getMemoryInstructionCost(I, VF);
7198   }
7199   case Instruction::BitCast:
7200     if (I->getType()->isPointerTy())
7201       return 0;
7202     LLVM_FALLTHROUGH;
7203   case Instruction::ZExt:
7204   case Instruction::SExt:
7205   case Instruction::FPToUI:
7206   case Instruction::FPToSI:
7207   case Instruction::FPExt:
7208   case Instruction::PtrToInt:
7209   case Instruction::IntToPtr:
7210   case Instruction::SIToFP:
7211   case Instruction::UIToFP:
7212   case Instruction::Trunc:
7213   case Instruction::FPTrunc: {
7214     // Computes the CastContextHint from a Load/Store instruction.
7215     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7216       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7217              "Expected a load or a store!");
7218 
7219       if (VF.isScalar() || !TheLoop->contains(I))
7220         return TTI::CastContextHint::Normal;
7221 
7222       switch (getWideningDecision(I, VF)) {
7223       case LoopVectorizationCostModel::CM_GatherScatter:
7224         return TTI::CastContextHint::GatherScatter;
7225       case LoopVectorizationCostModel::CM_Interleave:
7226         return TTI::CastContextHint::Interleave;
7227       case LoopVectorizationCostModel::CM_Scalarize:
7228       case LoopVectorizationCostModel::CM_Widen:
7229         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7230                                         : TTI::CastContextHint::Normal;
7231       case LoopVectorizationCostModel::CM_Widen_Reverse:
7232         return TTI::CastContextHint::Reversed;
7233       case LoopVectorizationCostModel::CM_Unknown:
7234         llvm_unreachable("Instr did not go through cost modelling?");
7235       }
7236 
7237       llvm_unreachable("Unhandled case!");
7238     };
7239 
7240     unsigned Opcode = I->getOpcode();
7241     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7242     // For Trunc, the context is the only user, which must be a StoreInst.
7243     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7244       if (I->hasOneUse())
7245         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7246           CCH = ComputeCCH(Store);
7247     }
7248     // For Z/Sext, the context is the operand, which must be a LoadInst.
7249     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7250              Opcode == Instruction::FPExt) {
7251       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7252         CCH = ComputeCCH(Load);
7253     }
7254 
7255     // We optimize the truncation of induction variables having constant
7256     // integer steps. The cost of these truncations is the same as the scalar
7257     // operation.
7258     if (isOptimizableIVTruncate(I, VF)) {
7259       auto *Trunc = cast<TruncInst>(I);
7260       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7261                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7262     }
7263 
7264     // Detect reduction patterns
7265     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7266       return *RedCost;
7267 
7268     Type *SrcScalarTy = I->getOperand(0)->getType();
7269     Type *SrcVecTy =
7270         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7271     if (canTruncateToMinimalBitwidth(I, VF)) {
7272       // This cast is going to be shrunk. This may remove the cast or it might
7273       // turn it into slightly different cast. For example, if MinBW == 16,
7274       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7275       //
7276       // Calculate the modified src and dest types.
7277       Type *MinVecTy = VectorTy;
7278       if (Opcode == Instruction::Trunc) {
7279         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7280         VectorTy =
7281             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7282       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7283         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7284         VectorTy =
7285             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7286       }
7287     }
7288 
7289     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7290   }
7291   case Instruction::Call: {
7292     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7293       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7294         return *RedCost;
7295     bool NeedToScalarize;
7296     CallInst *CI = cast<CallInst>(I);
7297     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7298     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7299       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7300       return std::min(CallCost, IntrinsicCost);
7301     }
7302     return CallCost;
7303   }
7304   case Instruction::ExtractValue:
7305     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7306   case Instruction::Alloca:
7307     // We cannot easily widen alloca to a scalable alloca, as
7308     // the result would need to be a vector of pointers.
7309     if (VF.isScalable())
7310       return InstructionCost::getInvalid();
7311     LLVM_FALLTHROUGH;
7312   default:
7313     // This opcode is unknown. Assume that it is the same as 'mul'.
7314     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7315   } // end of switch.
7316 }
7317 
7318 char LoopVectorize::ID = 0;
7319 
7320 static const char lv_name[] = "Loop Vectorization";
7321 
7322 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7323 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7324 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7325 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7326 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7327 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7328 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7329 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7330 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7331 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7332 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7333 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7334 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7335 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7336 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7337 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7338 
7339 namespace llvm {
7340 
7341 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7342 
7343 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7344                               bool VectorizeOnlyWhenForced) {
7345   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7346 }
7347 
7348 } // end namespace llvm
7349 
7350 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7351   // Check if the pointer operand of a load or store instruction is
7352   // consecutive.
7353   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7354     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7355   return false;
7356 }
7357 
7358 void LoopVectorizationCostModel::collectValuesToIgnore() {
7359   // Ignore ephemeral values.
7360   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7361 
7362   // Ignore type-promoting instructions we identified during reduction
7363   // detection.
7364   for (auto &Reduction : Legal->getReductionVars()) {
7365     const RecurrenceDescriptor &RedDes = Reduction.second;
7366     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7367     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7368   }
7369   // Ignore type-casting instructions we identified during induction
7370   // detection.
7371   for (auto &Induction : Legal->getInductionVars()) {
7372     const InductionDescriptor &IndDes = Induction.second;
7373     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7374     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7375   }
7376 }
7377 
7378 void LoopVectorizationCostModel::collectInLoopReductions() {
7379   for (auto &Reduction : Legal->getReductionVars()) {
7380     PHINode *Phi = Reduction.first;
7381     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7382 
7383     // We don't collect reductions that are type promoted (yet).
7384     if (RdxDesc.getRecurrenceType() != Phi->getType())
7385       continue;
7386 
7387     // If the target would prefer this reduction to happen "in-loop", then we
7388     // want to record it as such.
7389     unsigned Opcode = RdxDesc.getOpcode();
7390     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7391         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7392                                    TargetTransformInfo::ReductionFlags()))
7393       continue;
7394 
7395     // Check that we can correctly put the reductions into the loop, by
7396     // finding the chain of operations that leads from the phi to the loop
7397     // exit value.
7398     SmallVector<Instruction *, 4> ReductionOperations =
7399         RdxDesc.getReductionOpChain(Phi, TheLoop);
7400     bool InLoop = !ReductionOperations.empty();
7401     if (InLoop) {
7402       InLoopReductionChains[Phi] = ReductionOperations;
7403       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7404       Instruction *LastChain = Phi;
7405       for (auto *I : ReductionOperations) {
7406         InLoopReductionImmediateChains[I] = LastChain;
7407         LastChain = I;
7408       }
7409     }
7410     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7411                       << " reduction for phi: " << *Phi << "\n");
7412   }
7413 }
7414 
7415 // TODO: we could return a pair of values that specify the max VF and
7416 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7417 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7418 // doesn't have a cost model that can choose which plan to execute if
7419 // more than one is generated.
7420 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7421                                  LoopVectorizationCostModel &CM) {
7422   unsigned WidestType;
7423   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7424   return WidestVectorRegBits / WidestType;
7425 }
7426 
7427 VectorizationFactor
7428 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7429   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7430   ElementCount VF = UserVF;
7431   // Outer loop handling: They may require CFG and instruction level
7432   // transformations before even evaluating whether vectorization is profitable.
7433   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7434   // the vectorization pipeline.
7435   if (!OrigLoop->isInnermost()) {
7436     // If the user doesn't provide a vectorization factor, determine a
7437     // reasonable one.
7438     if (UserVF.isZero()) {
7439       VF = ElementCount::getFixed(determineVPlanVF(
7440           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7441               .getFixedSize(),
7442           CM));
7443       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7444 
7445       // Make sure we have a VF > 1 for stress testing.
7446       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7447         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7448                           << "overriding computed VF.\n");
7449         VF = ElementCount::getFixed(4);
7450       }
7451     }
7452     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7453     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7454            "VF needs to be a power of two");
7455     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7456                       << "VF " << VF << " to build VPlans.\n");
7457     buildVPlans(VF, VF);
7458 
7459     // For VPlan build stress testing, we bail out after VPlan construction.
7460     if (VPlanBuildStressTest)
7461       return VectorizationFactor::Disabled();
7462 
7463     return {VF, 0 /*Cost*/};
7464   }
7465 
7466   LLVM_DEBUG(
7467       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7468                 "VPlan-native path.\n");
7469   return VectorizationFactor::Disabled();
7470 }
7471 
7472 Optional<VectorizationFactor>
7473 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7474   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7475   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7476   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7477     return None;
7478 
7479   // Invalidate interleave groups if all blocks of loop will be predicated.
7480   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7481       !useMaskedInterleavedAccesses(*TTI)) {
7482     LLVM_DEBUG(
7483         dbgs()
7484         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7485            "which requires masked-interleaved support.\n");
7486     if (CM.InterleaveInfo.invalidateGroups())
7487       // Invalidating interleave groups also requires invalidating all decisions
7488       // based on them, which includes widening decisions and uniform and scalar
7489       // values.
7490       CM.invalidateCostModelingDecisions();
7491   }
7492 
7493   ElementCount MaxUserVF =
7494       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7495   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7496   if (!UserVF.isZero() && UserVFIsLegal) {
7497     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7498            "VF needs to be a power of two");
7499     // Collect the instructions (and their associated costs) that will be more
7500     // profitable to scalarize.
7501     if (CM.selectUserVectorizationFactor(UserVF)) {
7502       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7503       CM.collectInLoopReductions();
7504       buildVPlansWithVPRecipes(UserVF, UserVF);
7505       LLVM_DEBUG(printPlans(dbgs()));
7506       return {{UserVF, 0}};
7507     } else
7508       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7509                               "InvalidCost", ORE, OrigLoop);
7510   }
7511 
7512   // Populate the set of Vectorization Factor Candidates.
7513   ElementCountSet VFCandidates;
7514   for (auto VF = ElementCount::getFixed(1);
7515        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7516     VFCandidates.insert(VF);
7517   for (auto VF = ElementCount::getScalable(1);
7518        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7519     VFCandidates.insert(VF);
7520 
7521   for (const auto &VF : VFCandidates) {
7522     // Collect Uniform and Scalar instructions after vectorization with VF.
7523     CM.collectUniformsAndScalars(VF);
7524 
7525     // Collect the instructions (and their associated costs) that will be more
7526     // profitable to scalarize.
7527     if (VF.isVector())
7528       CM.collectInstsToScalarize(VF);
7529   }
7530 
7531   CM.collectInLoopReductions();
7532   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7533   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7534 
7535   LLVM_DEBUG(printPlans(dbgs()));
7536   if (!MaxFactors.hasVector())
7537     return VectorizationFactor::Disabled();
7538 
7539   // Select the optimal vectorization factor.
7540   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
7541 
7542   // Check if it is profitable to vectorize with runtime checks.
7543   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7544   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
7545     bool PragmaThresholdReached =
7546         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7547     bool ThresholdReached =
7548         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
7549     if ((ThresholdReached && !Hints.allowReordering()) ||
7550         PragmaThresholdReached) {
7551       ORE->emit([&]() {
7552         return OptimizationRemarkAnalysisAliasing(
7553                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
7554                    OrigLoop->getHeader())
7555                << "loop not vectorized: cannot prove it is safe to reorder "
7556                   "memory operations";
7557       });
7558       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7559       Hints.emitRemarkWithHints();
7560       return VectorizationFactor::Disabled();
7561     }
7562   }
7563   return SelectedVF;
7564 }
7565 
7566 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7567   assert(count_if(VPlans,
7568                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7569              1 &&
7570          "Best VF has not a single VPlan.");
7571 
7572   for (const VPlanPtr &Plan : VPlans) {
7573     if (Plan->hasVF(VF))
7574       return *Plan.get();
7575   }
7576   llvm_unreachable("No plan found!");
7577 }
7578 
7579 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7580   SmallVector<Metadata *, 4> MDs;
7581   // Reserve first location for self reference to the LoopID metadata node.
7582   MDs.push_back(nullptr);
7583   bool IsUnrollMetadata = false;
7584   MDNode *LoopID = L->getLoopID();
7585   if (LoopID) {
7586     // First find existing loop unrolling disable metadata.
7587     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7588       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7589       if (MD) {
7590         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7591         IsUnrollMetadata =
7592             S && S->getString().startswith("llvm.loop.unroll.disable");
7593       }
7594       MDs.push_back(LoopID->getOperand(i));
7595     }
7596   }
7597 
7598   if (!IsUnrollMetadata) {
7599     // Add runtime unroll disable metadata.
7600     LLVMContext &Context = L->getHeader()->getContext();
7601     SmallVector<Metadata *, 1> DisableOperands;
7602     DisableOperands.push_back(
7603         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7604     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7605     MDs.push_back(DisableNode);
7606     MDNode *NewLoopID = MDNode::get(Context, MDs);
7607     // Set operand 0 to refer to the loop id itself.
7608     NewLoopID->replaceOperandWith(0, NewLoopID);
7609     L->setLoopID(NewLoopID);
7610   }
7611 }
7612 
7613 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7614                                            VPlan &BestVPlan,
7615                                            InnerLoopVectorizer &ILV,
7616                                            DominatorTree *DT) {
7617   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7618                     << '\n');
7619 
7620   // Perform the actual loop transformation.
7621 
7622   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7623   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7624   Value *CanonicalIVStartValue;
7625   std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
7626       ILV.createVectorizedLoopSkeleton();
7627   ILV.collectPoisonGeneratingRecipes(State);
7628 
7629   ILV.printDebugTracesAtStart();
7630 
7631   //===------------------------------------------------===//
7632   //
7633   // Notice: any optimization or new instruction that go
7634   // into the code below should also be implemented in
7635   // the cost-model.
7636   //
7637   //===------------------------------------------------===//
7638 
7639   // 2. Copy and widen instructions from the old loop into the new loop.
7640   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
7641                              ILV.getOrCreateVectorTripCount(nullptr),
7642                              CanonicalIVStartValue, State);
7643   BestVPlan.execute(&State);
7644 
7645   // Keep all loop hints from the original loop on the vector loop (we'll
7646   // replace the vectorizer-specific hints below).
7647   MDNode *OrigLoopID = OrigLoop->getLoopID();
7648 
7649   Optional<MDNode *> VectorizedLoopID =
7650       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7651                                       LLVMLoopVectorizeFollowupVectorized});
7652 
7653   Loop *L = LI->getLoopFor(State.CFG.PrevBB);
7654   if (VectorizedLoopID.hasValue())
7655     L->setLoopID(VectorizedLoopID.getValue());
7656   else {
7657     // Keep all loop hints from the original loop on the vector loop (we'll
7658     // replace the vectorizer-specific hints below).
7659     if (MDNode *LID = OrigLoop->getLoopID())
7660       L->setLoopID(LID);
7661 
7662     LoopVectorizeHints Hints(L, true, *ORE);
7663     Hints.setAlreadyVectorized();
7664   }
7665   // Disable runtime unrolling when vectorizing the epilogue loop.
7666   if (CanonicalIVStartValue)
7667     AddRuntimeUnrollDisableMetaData(L);
7668 
7669   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7670   //    predication, updating analyses.
7671   ILV.fixVectorizedLoop(State);
7672 
7673   ILV.printDebugTracesAtEnd();
7674 }
7675 
7676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7677 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7678   for (const auto &Plan : VPlans)
7679     if (PrintVPlansInDotFormat)
7680       Plan->printDOT(O);
7681     else
7682       Plan->print(O);
7683 }
7684 #endif
7685 
7686 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7687     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7688 
7689   // We create new control-flow for the vectorized loop, so the original exit
7690   // conditions will be dead after vectorization if it's only used by the
7691   // terminator
7692   SmallVector<BasicBlock*> ExitingBlocks;
7693   OrigLoop->getExitingBlocks(ExitingBlocks);
7694   for (auto *BB : ExitingBlocks) {
7695     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
7696     if (!Cmp || !Cmp->hasOneUse())
7697       continue;
7698 
7699     // TODO: we should introduce a getUniqueExitingBlocks on Loop
7700     if (!DeadInstructions.insert(Cmp).second)
7701       continue;
7702 
7703     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7704     // TODO: can recurse through operands in general
7705     for (Value *Op : Cmp->operands()) {
7706       if (isa<TruncInst>(Op) && Op->hasOneUse())
7707           DeadInstructions.insert(cast<Instruction>(Op));
7708     }
7709   }
7710 
7711   // We create new "steps" for induction variable updates to which the original
7712   // induction variables map. An original update instruction will be dead if
7713   // all its users except the induction variable are dead.
7714   auto *Latch = OrigLoop->getLoopLatch();
7715   for (auto &Induction : Legal->getInductionVars()) {
7716     PHINode *Ind = Induction.first;
7717     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7718 
7719     // If the tail is to be folded by masking, the primary induction variable,
7720     // if exists, isn't dead: it will be used for masking. Don't kill it.
7721     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
7722       continue;
7723 
7724     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7725           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7726         }))
7727       DeadInstructions.insert(IndUpdate);
7728   }
7729 }
7730 
7731 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7732 
7733 //===--------------------------------------------------------------------===//
7734 // EpilogueVectorizerMainLoop
7735 //===--------------------------------------------------------------------===//
7736 
7737 /// This function is partially responsible for generating the control flow
7738 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7739 std::pair<BasicBlock *, Value *>
7740 EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7741   MDNode *OrigLoopID = OrigLoop->getLoopID();
7742   Loop *Lp = createVectorLoopSkeleton("");
7743 
7744   // Generate the code to check the minimum iteration count of the vector
7745   // epilogue (see below).
7746   EPI.EpilogueIterationCountCheck =
7747       emitMinimumIterationCountCheck(LoopScalarPreHeader, true);
7748   EPI.EpilogueIterationCountCheck->setName("iter.check");
7749 
7750   // Generate the code to check any assumptions that we've made for SCEV
7751   // expressions.
7752   EPI.SCEVSafetyCheck = emitSCEVChecks(LoopScalarPreHeader);
7753 
7754   // Generate the code that checks at runtime if arrays overlap. We put the
7755   // checks into a separate block to make the more common case of few elements
7756   // faster.
7757   EPI.MemSafetyCheck = emitMemRuntimeChecks(LoopScalarPreHeader);
7758 
7759   // Generate the iteration count check for the main loop, *after* the check
7760   // for the epilogue loop, so that the path-length is shorter for the case
7761   // that goes directly through the vector epilogue. The longer-path length for
7762   // the main loop is compensated for, by the gain from vectorizing the larger
7763   // trip count. Note: the branch will get updated later on when we vectorize
7764   // the epilogue.
7765   EPI.MainLoopIterationCountCheck =
7766       emitMinimumIterationCountCheck(LoopScalarPreHeader, false);
7767 
7768   // Generate the induction variable.
7769   Value *CountRoundDown = getOrCreateVectorTripCount(LoopVectorPreHeader);
7770   EPI.VectorTripCount = CountRoundDown;
7771   createHeaderBranch(Lp);
7772 
7773   // Skip induction resume value creation here because they will be created in
7774   // the second pass. If we created them here, they wouldn't be used anyway,
7775   // because the vplan in the second pass still contains the inductions from the
7776   // original loop.
7777 
7778   return {completeLoopSkeleton(OrigLoopID), nullptr};
7779 }
7780 
7781 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7782   LLVM_DEBUG({
7783     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7784            << "Main Loop VF:" << EPI.MainLoopVF
7785            << ", Main Loop UF:" << EPI.MainLoopUF
7786            << ", Epilogue Loop VF:" << EPI.EpilogueVF
7787            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7788   });
7789 }
7790 
7791 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7792   DEBUG_WITH_TYPE(VerboseDebug, {
7793     dbgs() << "intermediate fn:\n"
7794            << *OrigLoop->getHeader()->getParent() << "\n";
7795   });
7796 }
7797 
7798 BasicBlock *
7799 EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(BasicBlock *Bypass,
7800                                                            bool ForEpilogue) {
7801   assert(Bypass && "Expected valid bypass basic block.");
7802   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
7803   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
7804   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
7805   // Reuse existing vector loop preheader for TC checks.
7806   // Note that new preheader block is generated for vector loop.
7807   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7808   IRBuilder<> Builder(TCCheckBlock->getTerminator());
7809 
7810   // Generate code to check if the loop's trip count is less than VF * UF of the
7811   // main vector loop.
7812   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
7813       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7814 
7815   Value *CheckMinIters = Builder.CreateICmp(
7816       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
7817       "min.iters.check");
7818 
7819   if (!ForEpilogue)
7820     TCCheckBlock->setName("vector.main.loop.iter.check");
7821 
7822   // Create new preheader for vector loop.
7823   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7824                                    DT, LI, nullptr, "vector.ph");
7825 
7826   if (ForEpilogue) {
7827     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
7828                                  DT->getNode(Bypass)->getIDom()) &&
7829            "TC check is expected to dominate Bypass");
7830 
7831     // Update dominator for Bypass & LoopExit.
7832     DT->changeImmediateDominator(Bypass, TCCheckBlock);
7833     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7834       // For loops with multiple exits, there's no edge from the middle block
7835       // to exit blocks (as the epilogue must run) and thus no need to update
7836       // the immediate dominator of the exit blocks.
7837       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
7838 
7839     LoopBypassBlocks.push_back(TCCheckBlock);
7840 
7841     // Save the trip count so we don't have to regenerate it in the
7842     // vec.epilog.iter.check. This is safe to do because the trip count
7843     // generated here dominates the vector epilog iter check.
7844     EPI.TripCount = Count;
7845   }
7846 
7847   ReplaceInstWithInst(
7848       TCCheckBlock->getTerminator(),
7849       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7850 
7851   return TCCheckBlock;
7852 }
7853 
7854 //===--------------------------------------------------------------------===//
7855 // EpilogueVectorizerEpilogueLoop
7856 //===--------------------------------------------------------------------===//
7857 
7858 /// This function is partially responsible for generating the control flow
7859 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7860 std::pair<BasicBlock *, Value *>
7861 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
7862   MDNode *OrigLoopID = OrigLoop->getLoopID();
7863   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
7864 
7865   // Now, compare the remaining count and if there aren't enough iterations to
7866   // execute the vectorized epilogue skip to the scalar part.
7867   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
7868   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
7869   LoopVectorPreHeader =
7870       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
7871                  LI, nullptr, "vec.epilog.ph");
7872   emitMinimumVectorEpilogueIterCountCheck(LoopScalarPreHeader,
7873                                           VecEpilogueIterationCountCheck);
7874 
7875   // Adjust the control flow taking the state info from the main loop
7876   // vectorization into account.
7877   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
7878          "expected this to be saved from the previous pass.");
7879   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
7880       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7881 
7882   DT->changeImmediateDominator(LoopVectorPreHeader,
7883                                EPI.MainLoopIterationCountCheck);
7884 
7885   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
7886       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7887 
7888   if (EPI.SCEVSafetyCheck)
7889     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
7890         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7891   if (EPI.MemSafetyCheck)
7892     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
7893         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7894 
7895   DT->changeImmediateDominator(
7896       VecEpilogueIterationCountCheck,
7897       VecEpilogueIterationCountCheck->getSinglePredecessor());
7898 
7899   DT->changeImmediateDominator(LoopScalarPreHeader,
7900                                EPI.EpilogueIterationCountCheck);
7901   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7902     // If there is an epilogue which must run, there's no edge from the
7903     // middle block to exit blocks  and thus no need to update the immediate
7904     // dominator of the exit blocks.
7905     DT->changeImmediateDominator(LoopExitBlock,
7906                                  EPI.EpilogueIterationCountCheck);
7907 
7908   // Keep track of bypass blocks, as they feed start values to the induction
7909   // phis in the scalar loop preheader.
7910   if (EPI.SCEVSafetyCheck)
7911     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
7912   if (EPI.MemSafetyCheck)
7913     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
7914   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
7915 
7916   // The vec.epilog.iter.check block may contain Phi nodes from reductions which
7917   // merge control-flow from the latch block and the middle block. Update the
7918   // incoming values here and move the Phi into the preheader.
7919   SmallVector<PHINode *, 4> PhisInBlock;
7920   for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
7921     PhisInBlock.push_back(&Phi);
7922 
7923   for (PHINode *Phi : PhisInBlock) {
7924     Phi->replaceIncomingBlockWith(
7925         VecEpilogueIterationCountCheck->getSinglePredecessor(),
7926         VecEpilogueIterationCountCheck);
7927     Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7928     if (EPI.SCEVSafetyCheck)
7929       Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
7930     if (EPI.MemSafetyCheck)
7931       Phi->removeIncomingValue(EPI.MemSafetyCheck);
7932     Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
7933   }
7934 
7935   // Generate a resume induction for the vector epilogue and put it in the
7936   // vector epilogue preheader
7937   Type *IdxTy = Legal->getWidestInductionType();
7938   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
7939                                          LoopVectorPreHeader->getFirstNonPHI());
7940   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
7941   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
7942                            EPI.MainLoopIterationCountCheck);
7943 
7944   // Generate the induction variable.
7945   createHeaderBranch(Lp);
7946 
7947   // Generate induction resume values. These variables save the new starting
7948   // indexes for the scalar loop. They are used to test if there are any tail
7949   // iterations left once the vector loop has completed.
7950   // Note that when the vectorized epilogue is skipped due to iteration count
7951   // check, then the resume value for the induction variable comes from
7952   // the trip count of the main vector loop, hence passing the AdditionalBypass
7953   // argument.
7954   createInductionResumeValues({VecEpilogueIterationCountCheck,
7955                                EPI.VectorTripCount} /* AdditionalBypass */);
7956 
7957   return {completeLoopSkeleton(OrigLoopID), EPResumeVal};
7958 }
7959 
7960 BasicBlock *
7961 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
7962     BasicBlock *Bypass, BasicBlock *Insert) {
7963 
7964   assert(EPI.TripCount &&
7965          "Expected trip count to have been safed in the first pass.");
7966   assert(
7967       (!isa<Instruction>(EPI.TripCount) ||
7968        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
7969       "saved trip count does not dominate insertion point.");
7970   Value *TC = EPI.TripCount;
7971   IRBuilder<> Builder(Insert->getTerminator());
7972   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7973 
7974   // Generate code to check if the loop's trip count is less than VF * UF of the
7975   // vector epilogue loop.
7976   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
7977       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7978 
7979   Value *CheckMinIters =
7980       Builder.CreateICmp(P, Count,
7981                          createStepForVF(Builder, Count->getType(),
7982                                          EPI.EpilogueVF, EPI.EpilogueUF),
7983                          "min.epilog.iters.check");
7984 
7985   ReplaceInstWithInst(
7986       Insert->getTerminator(),
7987       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7988 
7989   LoopBypassBlocks.push_back(Insert);
7990   return Insert;
7991 }
7992 
7993 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
7994   LLVM_DEBUG({
7995     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7996            << "Epilogue Loop VF:" << EPI.EpilogueVF
7997            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7998   });
7999 }
8000 
8001 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8002   DEBUG_WITH_TYPE(VerboseDebug, {
8003     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
8004   });
8005 }
8006 
8007 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8008     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8009   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8010   bool PredicateAtRangeStart = Predicate(Range.Start);
8011 
8012   for (ElementCount TmpVF = Range.Start * 2;
8013        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8014     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8015       Range.End = TmpVF;
8016       break;
8017     }
8018 
8019   return PredicateAtRangeStart;
8020 }
8021 
8022 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8023 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8024 /// of VF's starting at a given VF and extending it as much as possible. Each
8025 /// vectorization decision can potentially shorten this sub-range during
8026 /// buildVPlan().
8027 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8028                                            ElementCount MaxVF) {
8029   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8030   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8031     VFRange SubRange = {VF, MaxVFPlusOne};
8032     VPlans.push_back(buildVPlan(SubRange));
8033     VF = SubRange.End;
8034   }
8035 }
8036 
8037 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8038                                          VPlanPtr &Plan) {
8039   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8040 
8041   // Look for cached value.
8042   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8043   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8044   if (ECEntryIt != EdgeMaskCache.end())
8045     return ECEntryIt->second;
8046 
8047   VPValue *SrcMask = createBlockInMask(Src, Plan);
8048 
8049   // The terminator has to be a branch inst!
8050   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8051   assert(BI && "Unexpected terminator found");
8052 
8053   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8054     return EdgeMaskCache[Edge] = SrcMask;
8055 
8056   // If source is an exiting block, we know the exit edge is dynamically dead
8057   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8058   // adding uses of an otherwise potentially dead instruction.
8059   if (OrigLoop->isLoopExiting(Src))
8060     return EdgeMaskCache[Edge] = SrcMask;
8061 
8062   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8063   assert(EdgeMask && "No Edge Mask found for condition");
8064 
8065   if (BI->getSuccessor(0) != Dst)
8066     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8067 
8068   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8069     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8070     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8071     // The select version does not introduce new UB if SrcMask is false and
8072     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8073     VPValue *False = Plan->getOrAddVPValue(
8074         ConstantInt::getFalse(BI->getCondition()->getType()));
8075     EdgeMask =
8076         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8077   }
8078 
8079   return EdgeMaskCache[Edge] = EdgeMask;
8080 }
8081 
8082 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8083   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8084 
8085   // Look for cached value.
8086   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8087   if (BCEntryIt != BlockMaskCache.end())
8088     return BCEntryIt->second;
8089 
8090   // All-one mask is modelled as no-mask following the convention for masked
8091   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8092   VPValue *BlockMask = nullptr;
8093 
8094   if (OrigLoop->getHeader() == BB) {
8095     if (!CM.blockNeedsPredicationForAnyReason(BB))
8096       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8097 
8098     // Introduce the early-exit compare IV <= BTC to form header block mask.
8099     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8100     // constructing the desired canonical IV in the header block as its first
8101     // non-phi instructions.
8102     assert(CM.foldTailByMasking() && "must fold the tail");
8103     VPBasicBlock *HeaderVPBB =
8104         Plan->getVectorLoopRegion()->getEntryBasicBlock();
8105     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8106     auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
8107     HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
8108 
8109     VPBuilder::InsertPointGuard Guard(Builder);
8110     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8111     if (CM.TTI.emitGetActiveLaneMask()) {
8112       VPValue *TC = Plan->getOrCreateTripCount();
8113       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC});
8114     } else {
8115       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8116       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8117     }
8118     return BlockMaskCache[BB] = BlockMask;
8119   }
8120 
8121   // This is the block mask. We OR all incoming edges.
8122   for (auto *Predecessor : predecessors(BB)) {
8123     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8124     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8125       return BlockMaskCache[BB] = EdgeMask;
8126 
8127     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8128       BlockMask = EdgeMask;
8129       continue;
8130     }
8131 
8132     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8133   }
8134 
8135   return BlockMaskCache[BB] = BlockMask;
8136 }
8137 
8138 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8139                                                 ArrayRef<VPValue *> Operands,
8140                                                 VFRange &Range,
8141                                                 VPlanPtr &Plan) {
8142   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8143          "Must be called with either a load or store");
8144 
8145   auto willWiden = [&](ElementCount VF) -> bool {
8146     if (VF.isScalar())
8147       return false;
8148     LoopVectorizationCostModel::InstWidening Decision =
8149         CM.getWideningDecision(I, VF);
8150     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8151            "CM decision should be taken at this point.");
8152     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8153       return true;
8154     if (CM.isScalarAfterVectorization(I, VF) ||
8155         CM.isProfitableToScalarize(I, VF))
8156       return false;
8157     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8158   };
8159 
8160   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8161     return nullptr;
8162 
8163   VPValue *Mask = nullptr;
8164   if (Legal->isMaskRequired(I))
8165     Mask = createBlockInMask(I->getParent(), Plan);
8166 
8167   // Determine if the pointer operand of the access is either consecutive or
8168   // reverse consecutive.
8169   LoopVectorizationCostModel::InstWidening Decision =
8170       CM.getWideningDecision(I, Range.Start);
8171   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8172   bool Consecutive =
8173       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8174 
8175   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8176     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8177                                               Consecutive, Reverse);
8178 
8179   StoreInst *Store = cast<StoreInst>(I);
8180   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8181                                             Mask, Consecutive, Reverse);
8182 }
8183 
8184 static VPWidenIntOrFpInductionRecipe *
8185 createWidenInductionRecipe(PHINode *Phi, Instruction *PhiOrTrunc,
8186                            VPValue *Start, const InductionDescriptor &IndDesc,
8187                            LoopVectorizationCostModel &CM, ScalarEvolution &SE,
8188                            Loop &OrigLoop, VFRange &Range) {
8189   // Returns true if an instruction \p I should be scalarized instead of
8190   // vectorized for the chosen vectorization factor.
8191   auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
8192     return CM.isScalarAfterVectorization(I, VF) ||
8193            CM.isProfitableToScalarize(I, VF);
8194   };
8195 
8196   bool NeedsScalarIV = LoopVectorizationPlanner::getDecisionAndClampRange(
8197       [&](ElementCount VF) {
8198         // Returns true if we should generate a scalar version of \p IV.
8199         if (ShouldScalarizeInstruction(PhiOrTrunc, VF))
8200           return true;
8201         auto isScalarInst = [&](User *U) -> bool {
8202           auto *I = cast<Instruction>(U);
8203           return OrigLoop.contains(I) && ShouldScalarizeInstruction(I, VF);
8204         };
8205         return any_of(PhiOrTrunc->users(), isScalarInst);
8206       },
8207       Range);
8208   bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
8209       [&](ElementCount VF) {
8210         return ShouldScalarizeInstruction(PhiOrTrunc, VF);
8211       },
8212       Range);
8213   assert(IndDesc.getStartValue() ==
8214          Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
8215   assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
8216          "step must be loop invariant");
8217   if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8218     return new VPWidenIntOrFpInductionRecipe(
8219         Phi, Start, IndDesc, TruncI, NeedsScalarIV, !NeedsScalarIVOnly, SE);
8220   }
8221   assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
8222   return new VPWidenIntOrFpInductionRecipe(Phi, Start, IndDesc, NeedsScalarIV,
8223                                            !NeedsScalarIVOnly, SE);
8224 }
8225 
8226 VPRecipeBase *VPRecipeBuilder::tryToOptimizeInductionPHI(
8227     PHINode *Phi, ArrayRef<VPValue *> Operands, VFRange &Range) const {
8228 
8229   // Check if this is an integer or fp induction. If so, build the recipe that
8230   // produces its scalar and vector values.
8231   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
8232     return createWidenInductionRecipe(Phi, Phi, Operands[0], *II, CM,
8233                                       *PSE.getSE(), *OrigLoop, Range);
8234 
8235   // Check if this is pointer induction. If so, build the recipe for it.
8236   if (auto *II = Legal->getPointerInductionDescriptor(Phi))
8237     return new VPWidenPointerInductionRecipe(Phi, Operands[0], *II,
8238                                              *PSE.getSE());
8239   return nullptr;
8240 }
8241 
8242 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8243     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8244     VPlan &Plan) const {
8245   // Optimize the special case where the source is a constant integer
8246   // induction variable. Notice that we can only optimize the 'trunc' case
8247   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8248   // (c) other casts depend on pointer size.
8249 
8250   // Determine whether \p K is a truncation based on an induction variable that
8251   // can be optimized.
8252   auto isOptimizableIVTruncate =
8253       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8254     return [=](ElementCount VF) -> bool {
8255       return CM.isOptimizableIVTruncate(K, VF);
8256     };
8257   };
8258 
8259   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8260           isOptimizableIVTruncate(I), Range)) {
8261 
8262     auto *Phi = cast<PHINode>(I->getOperand(0));
8263     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8264     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8265     return createWidenInductionRecipe(Phi, I, Start, II, CM, *PSE.getSE(),
8266                                       *OrigLoop, Range);
8267   }
8268   return nullptr;
8269 }
8270 
8271 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8272                                                 ArrayRef<VPValue *> Operands,
8273                                                 VPlanPtr &Plan) {
8274   // If all incoming values are equal, the incoming VPValue can be used directly
8275   // instead of creating a new VPBlendRecipe.
8276   VPValue *FirstIncoming = Operands[0];
8277   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8278         return FirstIncoming == Inc;
8279       })) {
8280     return Operands[0];
8281   }
8282 
8283   unsigned NumIncoming = Phi->getNumIncomingValues();
8284   // For in-loop reductions, we do not need to create an additional select.
8285   VPValue *InLoopVal = nullptr;
8286   for (unsigned In = 0; In < NumIncoming; In++) {
8287     PHINode *PhiOp =
8288         dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
8289     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
8290       assert(!InLoopVal && "Found more than one in-loop reduction!");
8291       InLoopVal = Operands[In];
8292     }
8293   }
8294 
8295   assert((!InLoopVal || NumIncoming == 2) &&
8296          "Found an in-loop reduction for PHI with unexpected number of "
8297          "incoming values");
8298   if (InLoopVal)
8299     return Operands[Operands[0] == InLoopVal ? 1 : 0];
8300 
8301   // We know that all PHIs in non-header blocks are converted into selects, so
8302   // we don't have to worry about the insertion order and we can just use the
8303   // builder. At this point we generate the predication tree. There may be
8304   // duplications since this is a simple recursive scan, but future
8305   // optimizations will clean it up.
8306   SmallVector<VPValue *, 2> OperandsWithMask;
8307 
8308   for (unsigned In = 0; In < NumIncoming; In++) {
8309     VPValue *EdgeMask =
8310       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8311     assert((EdgeMask || NumIncoming == 1) &&
8312            "Multiple predecessors with one having a full mask");
8313     OperandsWithMask.push_back(Operands[In]);
8314     if (EdgeMask)
8315       OperandsWithMask.push_back(EdgeMask);
8316   }
8317   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8318 }
8319 
8320 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8321                                                    ArrayRef<VPValue *> Operands,
8322                                                    VFRange &Range) const {
8323 
8324   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8325       [this, CI](ElementCount VF) {
8326         return CM.isScalarWithPredication(CI, VF);
8327       },
8328       Range);
8329 
8330   if (IsPredicated)
8331     return nullptr;
8332 
8333   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8334   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8335              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8336              ID == Intrinsic::pseudoprobe ||
8337              ID == Intrinsic::experimental_noalias_scope_decl))
8338     return nullptr;
8339 
8340   auto willWiden = [&](ElementCount VF) -> bool {
8341     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8342     // The following case may be scalarized depending on the VF.
8343     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8344     // version of the instruction.
8345     // Is it beneficial to perform intrinsic call compared to lib call?
8346     bool NeedToScalarize = false;
8347     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8348     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8349     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8350     return UseVectorIntrinsic || !NeedToScalarize;
8351   };
8352 
8353   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8354     return nullptr;
8355 
8356   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8357   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8358 }
8359 
8360 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8361   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8362          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8363   // Instruction should be widened, unless it is scalar after vectorization,
8364   // scalarization is profitable or it is predicated.
8365   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8366     return CM.isScalarAfterVectorization(I, VF) ||
8367            CM.isProfitableToScalarize(I, VF) ||
8368            CM.isScalarWithPredication(I, VF);
8369   };
8370   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8371                                                              Range);
8372 }
8373 
8374 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8375                                            ArrayRef<VPValue *> Operands) const {
8376   auto IsVectorizableOpcode = [](unsigned Opcode) {
8377     switch (Opcode) {
8378     case Instruction::Add:
8379     case Instruction::And:
8380     case Instruction::AShr:
8381     case Instruction::BitCast:
8382     case Instruction::FAdd:
8383     case Instruction::FCmp:
8384     case Instruction::FDiv:
8385     case Instruction::FMul:
8386     case Instruction::FNeg:
8387     case Instruction::FPExt:
8388     case Instruction::FPToSI:
8389     case Instruction::FPToUI:
8390     case Instruction::FPTrunc:
8391     case Instruction::FRem:
8392     case Instruction::FSub:
8393     case Instruction::ICmp:
8394     case Instruction::IntToPtr:
8395     case Instruction::LShr:
8396     case Instruction::Mul:
8397     case Instruction::Or:
8398     case Instruction::PtrToInt:
8399     case Instruction::SDiv:
8400     case Instruction::Select:
8401     case Instruction::SExt:
8402     case Instruction::Shl:
8403     case Instruction::SIToFP:
8404     case Instruction::SRem:
8405     case Instruction::Sub:
8406     case Instruction::Trunc:
8407     case Instruction::UDiv:
8408     case Instruction::UIToFP:
8409     case Instruction::URem:
8410     case Instruction::Xor:
8411     case Instruction::ZExt:
8412       return true;
8413     }
8414     return false;
8415   };
8416 
8417   if (!IsVectorizableOpcode(I->getOpcode()))
8418     return nullptr;
8419 
8420   // Success: widen this instruction.
8421   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8422 }
8423 
8424 void VPRecipeBuilder::fixHeaderPhis() {
8425   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8426   for (VPHeaderPHIRecipe *R : PhisToFix) {
8427     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8428     VPRecipeBase *IncR =
8429         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8430     R->addOperand(IncR->getVPSingleValue());
8431   }
8432 }
8433 
8434 VPBasicBlock *VPRecipeBuilder::handleReplication(
8435     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8436     VPlanPtr &Plan) {
8437   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8438       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8439       Range);
8440 
8441   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8442       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF, IsUniform); },
8443       Range);
8444 
8445   // Even if the instruction is not marked as uniform, there are certain
8446   // intrinsic calls that can be effectively treated as such, so we check for
8447   // them here. Conservatively, we only do this for scalable vectors, since
8448   // for fixed-width VFs we can always fall back on full scalarization.
8449   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8450     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8451     case Intrinsic::assume:
8452     case Intrinsic::lifetime_start:
8453     case Intrinsic::lifetime_end:
8454       // For scalable vectors if one of the operands is variant then we still
8455       // want to mark as uniform, which will generate one instruction for just
8456       // the first lane of the vector. We can't scalarize the call in the same
8457       // way as for fixed-width vectors because we don't know how many lanes
8458       // there are.
8459       //
8460       // The reasons for doing it this way for scalable vectors are:
8461       //   1. For the assume intrinsic generating the instruction for the first
8462       //      lane is still be better than not generating any at all. For
8463       //      example, the input may be a splat across all lanes.
8464       //   2. For the lifetime start/end intrinsics the pointer operand only
8465       //      does anything useful when the input comes from a stack object,
8466       //      which suggests it should always be uniform. For non-stack objects
8467       //      the effect is to poison the object, which still allows us to
8468       //      remove the call.
8469       IsUniform = true;
8470       break;
8471     default:
8472       break;
8473     }
8474   }
8475 
8476   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8477                                        IsUniform, IsPredicated);
8478   setRecipe(I, Recipe);
8479   Plan->addVPValue(I, Recipe);
8480 
8481   // Find if I uses a predicated instruction. If so, it will use its scalar
8482   // value. Avoid hoisting the insert-element which packs the scalar value into
8483   // a vector value, as that happens iff all users use the vector value.
8484   for (VPValue *Op : Recipe->operands()) {
8485     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8486     if (!PredR)
8487       continue;
8488     auto *RepR =
8489         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8490     assert(RepR->isPredicated() &&
8491            "expected Replicate recipe to be predicated");
8492     RepR->setAlsoPack(false);
8493   }
8494 
8495   // Finalize the recipe for Instr, first if it is not predicated.
8496   if (!IsPredicated) {
8497     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8498     VPBB->appendRecipe(Recipe);
8499     return VPBB;
8500   }
8501   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8502 
8503   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8504   assert(SingleSucc && "VPBB must have a single successor when handling "
8505                        "predicated replication.");
8506   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8507   // Record predicated instructions for above packing optimizations.
8508   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8509   VPBlockUtils::insertBlockAfter(Region, VPBB);
8510   auto *RegSucc = new VPBasicBlock();
8511   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8512   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8513   return RegSucc;
8514 }
8515 
8516 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8517                                                       VPRecipeBase *PredRecipe,
8518                                                       VPlanPtr &Plan) {
8519   // Instructions marked for predication are replicated and placed under an
8520   // if-then construct to prevent side-effects.
8521 
8522   // Generate recipes to compute the block mask for this region.
8523   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8524 
8525   // Build the triangular if-then region.
8526   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8527   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8528   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8529   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8530   auto *PHIRecipe = Instr->getType()->isVoidTy()
8531                         ? nullptr
8532                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8533   if (PHIRecipe) {
8534     Plan->removeVPValueFor(Instr);
8535     Plan->addVPValue(Instr, PHIRecipe);
8536   }
8537   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8538   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8539   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8540 
8541   // Note: first set Entry as region entry and then connect successors starting
8542   // from it in order, to propagate the "parent" of each VPBasicBlock.
8543   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8544   VPBlockUtils::connectBlocks(Pred, Exit);
8545 
8546   return Region;
8547 }
8548 
8549 VPRecipeOrVPValueTy
8550 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8551                                         ArrayRef<VPValue *> Operands,
8552                                         VFRange &Range, VPlanPtr &Plan) {
8553   // First, check for specific widening recipes that deal with calls, memory
8554   // operations, inductions and Phi nodes.
8555   if (auto *CI = dyn_cast<CallInst>(Instr))
8556     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8557 
8558   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8559     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8560 
8561   VPRecipeBase *Recipe;
8562   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8563     if (Phi->getParent() != OrigLoop->getHeader())
8564       return tryToBlend(Phi, Operands, Plan);
8565     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, Range)))
8566       return toVPRecipeResult(Recipe);
8567 
8568     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8569     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
8570       VPValue *StartV = Operands[0];
8571       if (Legal->isReductionVariable(Phi)) {
8572         const RecurrenceDescriptor &RdxDesc =
8573             Legal->getReductionVars().find(Phi)->second;
8574         assert(RdxDesc.getRecurrenceStartValue() ==
8575                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8576         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8577                                              CM.isInLoopReduction(Phi),
8578                                              CM.useOrderedReductions(RdxDesc));
8579       } else {
8580         PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8581       }
8582 
8583       // Record the incoming value from the backedge, so we can add the incoming
8584       // value from the backedge after all recipes have been created.
8585       recordRecipeOf(cast<Instruction>(
8586           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8587       PhisToFix.push_back(PhiRecipe);
8588     } else {
8589       // TODO: record backedge value for remaining pointer induction phis.
8590       assert(Phi->getType()->isPointerTy() &&
8591              "only pointer phis should be handled here");
8592       assert(Legal->getInductionVars().count(Phi) &&
8593              "Not an induction variable");
8594       InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8595       VPValue *Start = Plan->getOrAddVPValue(II.getStartValue());
8596       PhiRecipe = new VPWidenPHIRecipe(Phi, Start);
8597     }
8598 
8599     return toVPRecipeResult(PhiRecipe);
8600   }
8601 
8602   if (isa<TruncInst>(Instr) &&
8603       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8604                                                Range, *Plan)))
8605     return toVPRecipeResult(Recipe);
8606 
8607   if (!shouldWiden(Instr, Range))
8608     return nullptr;
8609 
8610   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8611     return toVPRecipeResult(new VPWidenGEPRecipe(
8612         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8613 
8614   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8615     bool InvariantCond =
8616         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8617     return toVPRecipeResult(new VPWidenSelectRecipe(
8618         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8619   }
8620 
8621   return toVPRecipeResult(tryToWiden(Instr, Operands));
8622 }
8623 
8624 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8625                                                         ElementCount MaxVF) {
8626   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8627 
8628   // Collect instructions from the original loop that will become trivially dead
8629   // in the vectorized loop. We don't need to vectorize these instructions. For
8630   // example, original induction update instructions can become dead because we
8631   // separately emit induction "steps" when generating code for the new loop.
8632   // Similarly, we create a new latch condition when setting up the structure
8633   // of the new loop, so the old one can become dead.
8634   SmallPtrSet<Instruction *, 4> DeadInstructions;
8635   collectTriviallyDeadInstructions(DeadInstructions);
8636 
8637   // Add assume instructions we need to drop to DeadInstructions, to prevent
8638   // them from being added to the VPlan.
8639   // TODO: We only need to drop assumes in blocks that get flattend. If the
8640   // control flow is preserved, we should keep them.
8641   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8642   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8643 
8644   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8645   // Dead instructions do not need sinking. Remove them from SinkAfter.
8646   for (Instruction *I : DeadInstructions)
8647     SinkAfter.erase(I);
8648 
8649   // Cannot sink instructions after dead instructions (there won't be any
8650   // recipes for them). Instead, find the first non-dead previous instruction.
8651   for (auto &P : Legal->getSinkAfter()) {
8652     Instruction *SinkTarget = P.second;
8653     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8654     (void)FirstInst;
8655     while (DeadInstructions.contains(SinkTarget)) {
8656       assert(
8657           SinkTarget != FirstInst &&
8658           "Must find a live instruction (at least the one feeding the "
8659           "first-order recurrence PHI) before reaching beginning of the block");
8660       SinkTarget = SinkTarget->getPrevNode();
8661       assert(SinkTarget != P.first &&
8662              "sink source equals target, no sinking required");
8663     }
8664     P.second = SinkTarget;
8665   }
8666 
8667   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8668   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8669     VFRange SubRange = {VF, MaxVFPlusOne};
8670     VPlans.push_back(
8671         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8672     VF = SubRange.End;
8673   }
8674 }
8675 
8676 // Add a VPCanonicalIVPHIRecipe starting at 0 to the header, a
8677 // CanonicalIVIncrement{NUW} VPInstruction to increment it by VF * UF and a
8678 // BranchOnCount VPInstruction to the latch.
8679 static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
8680                                   bool HasNUW, bool IsVPlanNative) {
8681   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8682   auto *StartV = Plan.getOrAddVPValue(StartIdx);
8683 
8684   auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
8685   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
8686   VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
8687   if (IsVPlanNative)
8688     Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
8689   Header->insert(CanonicalIVPHI, Header->begin());
8690 
8691   auto *CanonicalIVIncrement =
8692       new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
8693                                : VPInstruction::CanonicalIVIncrement,
8694                         {CanonicalIVPHI}, DL);
8695   CanonicalIVPHI->addOperand(CanonicalIVIncrement);
8696 
8697   VPBasicBlock *EB = TopRegion->getExitBasicBlock();
8698   if (IsVPlanNative) {
8699     EB = cast<VPBasicBlock>(EB->getSinglePredecessor());
8700     EB->setCondBit(nullptr);
8701   }
8702   EB->appendRecipe(CanonicalIVIncrement);
8703 
8704   auto *BranchOnCount =
8705       new VPInstruction(VPInstruction::BranchOnCount,
8706                         {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
8707   EB->appendRecipe(BranchOnCount);
8708 }
8709 
8710 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8711     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8712     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8713 
8714   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8715 
8716   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8717 
8718   // ---------------------------------------------------------------------------
8719   // Pre-construction: record ingredients whose recipes we'll need to further
8720   // process after constructing the initial VPlan.
8721   // ---------------------------------------------------------------------------
8722 
8723   // Mark instructions we'll need to sink later and their targets as
8724   // ingredients whose recipe we'll need to record.
8725   for (auto &Entry : SinkAfter) {
8726     RecipeBuilder.recordRecipeOf(Entry.first);
8727     RecipeBuilder.recordRecipeOf(Entry.second);
8728   }
8729   for (auto &Reduction : CM.getInLoopReductionChains()) {
8730     PHINode *Phi = Reduction.first;
8731     RecurKind Kind =
8732         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8733     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8734 
8735     RecipeBuilder.recordRecipeOf(Phi);
8736     for (auto &R : ReductionOperations) {
8737       RecipeBuilder.recordRecipeOf(R);
8738       // For min/max reductions, where we have a pair of icmp/select, we also
8739       // need to record the ICmp recipe, so it can be removed later.
8740       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
8741              "Only min/max recurrences allowed for inloop reductions");
8742       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8743         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8744     }
8745   }
8746 
8747   // For each interleave group which is relevant for this (possibly trimmed)
8748   // Range, add it to the set of groups to be later applied to the VPlan and add
8749   // placeholders for its members' Recipes which we'll be replacing with a
8750   // single VPInterleaveRecipe.
8751   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8752     auto applyIG = [IG, this](ElementCount VF) -> bool {
8753       return (VF.isVector() && // Query is illegal for VF == 1
8754               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8755                   LoopVectorizationCostModel::CM_Interleave);
8756     };
8757     if (!getDecisionAndClampRange(applyIG, Range))
8758       continue;
8759     InterleaveGroups.insert(IG);
8760     for (unsigned i = 0; i < IG->getFactor(); i++)
8761       if (Instruction *Member = IG->getMember(i))
8762         RecipeBuilder.recordRecipeOf(Member);
8763   };
8764 
8765   // ---------------------------------------------------------------------------
8766   // Build initial VPlan: Scan the body of the loop in a topological order to
8767   // visit each basic block after having visited its predecessor basic blocks.
8768   // ---------------------------------------------------------------------------
8769 
8770   // Create initial VPlan skeleton, with separate header and latch blocks.
8771   VPBasicBlock *HeaderVPBB = new VPBasicBlock();
8772   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
8773   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
8774   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
8775   auto Plan = std::make_unique<VPlan>(TopRegion);
8776 
8777   Instruction *DLInst =
8778       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
8779   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
8780                         DLInst ? DLInst->getDebugLoc() : DebugLoc(),
8781                         !CM.foldTailByMasking(), false);
8782 
8783   // Scan the body of the loop in a topological order to visit each basic block
8784   // after having visited its predecessor basic blocks.
8785   LoopBlocksDFS DFS(OrigLoop);
8786   DFS.perform(LI);
8787 
8788   VPBasicBlock *VPBB = HeaderVPBB;
8789   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
8790   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8791     // Relevant instructions from basic block BB will be grouped into VPRecipe
8792     // ingredients and fill a new VPBasicBlock.
8793     unsigned VPBBsForBB = 0;
8794     VPBB->setName(BB->getName());
8795     Builder.setInsertPoint(VPBB);
8796 
8797     // Introduce each ingredient into VPlan.
8798     // TODO: Model and preserve debug instrinsics in VPlan.
8799     for (Instruction &I : BB->instructionsWithoutDebug()) {
8800       Instruction *Instr = &I;
8801 
8802       // First filter out irrelevant instructions, to ensure no recipes are
8803       // built for them.
8804       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8805         continue;
8806 
8807       SmallVector<VPValue *, 4> Operands;
8808       auto *Phi = dyn_cast<PHINode>(Instr);
8809       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8810         Operands.push_back(Plan->getOrAddVPValue(
8811             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8812       } else {
8813         auto OpRange = Plan->mapToVPValues(Instr->operands());
8814         Operands = {OpRange.begin(), OpRange.end()};
8815       }
8816       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8817               Instr, Operands, Range, Plan)) {
8818         // If Instr can be simplified to an existing VPValue, use it.
8819         if (RecipeOrValue.is<VPValue *>()) {
8820           auto *VPV = RecipeOrValue.get<VPValue *>();
8821           Plan->addVPValue(Instr, VPV);
8822           // If the re-used value is a recipe, register the recipe for the
8823           // instruction, in case the recipe for Instr needs to be recorded.
8824           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
8825             RecipeBuilder.setRecipe(Instr, R);
8826           continue;
8827         }
8828         // Otherwise, add the new recipe.
8829         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8830         for (auto *Def : Recipe->definedValues()) {
8831           auto *UV = Def->getUnderlyingValue();
8832           Plan->addVPValue(UV, Def);
8833         }
8834 
8835         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
8836             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
8837           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
8838           // of the header block. That can happen for truncates of induction
8839           // variables. Those recipes are moved to the phi section of the header
8840           // block after applying SinkAfter, which relies on the original
8841           // position of the trunc.
8842           assert(isa<TruncInst>(Instr));
8843           InductionsToMove.push_back(
8844               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
8845         }
8846         RecipeBuilder.setRecipe(Instr, Recipe);
8847         VPBB->appendRecipe(Recipe);
8848         continue;
8849       }
8850 
8851       // Otherwise, if all widening options failed, Instruction is to be
8852       // replicated. This may create a successor for VPBB.
8853       VPBasicBlock *NextVPBB =
8854           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8855       if (NextVPBB != VPBB) {
8856         VPBB = NextVPBB;
8857         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8858                                     : "");
8859       }
8860     }
8861 
8862     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
8863     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
8864   }
8865 
8866   // Fold the last, empty block into its predecessor.
8867   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
8868   assert(VPBB && "expected to fold last (empty) block");
8869   // After here, VPBB should not be used.
8870   VPBB = nullptr;
8871 
8872   assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8873          !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8874          "entry block must be set to a VPRegionBlock having a non-empty entry "
8875          "VPBasicBlock");
8876   RecipeBuilder.fixHeaderPhis();
8877 
8878   // ---------------------------------------------------------------------------
8879   // Transform initial VPlan: Apply previously taken decisions, in order, to
8880   // bring the VPlan to its final state.
8881   // ---------------------------------------------------------------------------
8882 
8883   // Apply Sink-After legal constraints.
8884   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
8885     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
8886     if (Region && Region->isReplicator()) {
8887       assert(Region->getNumSuccessors() == 1 &&
8888              Region->getNumPredecessors() == 1 && "Expected SESE region!");
8889       assert(R->getParent()->size() == 1 &&
8890              "A recipe in an original replicator region must be the only "
8891              "recipe in its block");
8892       return Region;
8893     }
8894     return nullptr;
8895   };
8896   for (auto &Entry : SinkAfter) {
8897     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8898     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8899 
8900     auto *TargetRegion = GetReplicateRegion(Target);
8901     auto *SinkRegion = GetReplicateRegion(Sink);
8902     if (!SinkRegion) {
8903       // If the sink source is not a replicate region, sink the recipe directly.
8904       if (TargetRegion) {
8905         // The target is in a replication region, make sure to move Sink to
8906         // the block after it, not into the replication region itself.
8907         VPBasicBlock *NextBlock =
8908             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
8909         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8910       } else
8911         Sink->moveAfter(Target);
8912       continue;
8913     }
8914 
8915     // The sink source is in a replicate region. Unhook the region from the CFG.
8916     auto *SinkPred = SinkRegion->getSinglePredecessor();
8917     auto *SinkSucc = SinkRegion->getSingleSuccessor();
8918     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
8919     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
8920     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
8921 
8922     if (TargetRegion) {
8923       // The target recipe is also in a replicate region, move the sink region
8924       // after the target region.
8925       auto *TargetSucc = TargetRegion->getSingleSuccessor();
8926       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
8927       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
8928       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
8929     } else {
8930       // The sink source is in a replicate region, we need to move the whole
8931       // replicate region, which should only contain a single recipe in the
8932       // main block.
8933       auto *SplitBlock =
8934           Target->getParent()->splitAt(std::next(Target->getIterator()));
8935 
8936       auto *SplitPred = SplitBlock->getSinglePredecessor();
8937 
8938       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
8939       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
8940       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
8941     }
8942   }
8943 
8944   VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
8945   VPlanTransforms::removeRedundantInductionCasts(*Plan);
8946 
8947   // Now that sink-after is done, move induction recipes for optimized truncates
8948   // to the phi section of the header block.
8949   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
8950     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8951 
8952   // Adjust the recipes for any inloop reductions.
8953   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExit()), Plan,
8954                              RecipeBuilder, Range.Start);
8955 
8956   // Introduce a recipe to combine the incoming and previous values of a
8957   // first-order recurrence.
8958   for (VPRecipeBase &R :
8959        Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8960     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
8961     if (!RecurPhi)
8962       continue;
8963 
8964     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
8965     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
8966     auto *Region = GetReplicateRegion(PrevRecipe);
8967     if (Region)
8968       InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
8969     if (Region || PrevRecipe->isPhi())
8970       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
8971     else
8972       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
8973 
8974     auto *RecurSplice = cast<VPInstruction>(
8975         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
8976                              {RecurPhi, RecurPhi->getBackedgeValue()}));
8977 
8978     RecurPhi->replaceAllUsesWith(RecurSplice);
8979     // Set the first operand of RecurSplice to RecurPhi again, after replacing
8980     // all users.
8981     RecurSplice->setOperand(0, RecurPhi);
8982   }
8983 
8984   // Interleave memory: for each Interleave Group we marked earlier as relevant
8985   // for this VPlan, replace the Recipes widening its memory instructions with a
8986   // single VPInterleaveRecipe at its insertion point.
8987   for (auto IG : InterleaveGroups) {
8988     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
8989         RecipeBuilder.getRecipe(IG->getInsertPos()));
8990     SmallVector<VPValue *, 4> StoredValues;
8991     for (unsigned i = 0; i < IG->getFactor(); ++i)
8992       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
8993         auto *StoreR =
8994             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
8995         StoredValues.push_back(StoreR->getStoredValue());
8996       }
8997 
8998     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
8999                                         Recipe->getMask());
9000     VPIG->insertBefore(Recipe);
9001     unsigned J = 0;
9002     for (unsigned i = 0; i < IG->getFactor(); ++i)
9003       if (Instruction *Member = IG->getMember(i)) {
9004         if (!Member->getType()->isVoidTy()) {
9005           VPValue *OriginalV = Plan->getVPValue(Member);
9006           Plan->removeVPValueFor(Member);
9007           Plan->addVPValue(Member, VPIG->getVPValue(J));
9008           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9009           J++;
9010         }
9011         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9012       }
9013   }
9014 
9015   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9016   // in ways that accessing values using original IR values is incorrect.
9017   Plan->disableValue2VPValue();
9018 
9019   VPlanTransforms::optimizeInductions(*Plan, *PSE.getSE());
9020   VPlanTransforms::sinkScalarOperands(*Plan);
9021   VPlanTransforms::mergeReplicateRegions(*Plan);
9022   VPlanTransforms::removeDeadRecipes(*Plan, *OrigLoop);
9023 
9024   std::string PlanName;
9025   raw_string_ostream RSO(PlanName);
9026   ElementCount VF = Range.Start;
9027   Plan->addVF(VF);
9028   RSO << "Initial VPlan for VF={" << VF;
9029   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9030     Plan->addVF(VF);
9031     RSO << "," << VF;
9032   }
9033   RSO << "},UF>=1";
9034   RSO.flush();
9035   Plan->setName(PlanName);
9036 
9037   // Fold Exit block into its predecessor if possible.
9038   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9039   // VPBasicBlock as exit.
9040   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExit());
9041 
9042   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9043   return Plan;
9044 }
9045 
9046 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9047   // Outer loop handling: They may require CFG and instruction level
9048   // transformations before even evaluating whether vectorization is profitable.
9049   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9050   // the vectorization pipeline.
9051   assert(!OrigLoop->isInnermost());
9052   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9053 
9054   // Create new empty VPlan
9055   auto Plan = std::make_unique<VPlan>();
9056 
9057   // Build hierarchical CFG
9058   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9059   HCFGBuilder.buildHierarchicalCFG();
9060 
9061   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9062        VF *= 2)
9063     Plan->addVF(VF);
9064 
9065   if (EnableVPlanPredication) {
9066     VPlanPredicator VPP(*Plan);
9067     VPP.predicate();
9068 
9069     // Avoid running transformation to recipes until masked code generation in
9070     // VPlan-native path is in place.
9071     return Plan;
9072   }
9073 
9074   SmallPtrSet<Instruction *, 1> DeadInstructions;
9075   VPlanTransforms::VPInstructionsToVPRecipes(
9076       OrigLoop, Plan,
9077       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9078       DeadInstructions, *PSE.getSE());
9079 
9080   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
9081                         true, true);
9082   return Plan;
9083 }
9084 
9085 // Adjust the recipes for reductions. For in-loop reductions the chain of
9086 // instructions leading from the loop exit instr to the phi need to be converted
9087 // to reductions, with one operand being vector and the other being the scalar
9088 // reduction chain. For other reductions, a select is introduced between the phi
9089 // and live-out recipes when folding the tail.
9090 void LoopVectorizationPlanner::adjustRecipesForReductions(
9091     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9092     ElementCount MinVF) {
9093   for (auto &Reduction : CM.getInLoopReductionChains()) {
9094     PHINode *Phi = Reduction.first;
9095     const RecurrenceDescriptor &RdxDesc =
9096         Legal->getReductionVars().find(Phi)->second;
9097     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9098 
9099     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9100       continue;
9101 
9102     // ReductionOperations are orders top-down from the phi's use to the
9103     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9104     // which of the two operands will remain scalar and which will be reduced.
9105     // For minmax the chain will be the select instructions.
9106     Instruction *Chain = Phi;
9107     for (Instruction *R : ReductionOperations) {
9108       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9109       RecurKind Kind = RdxDesc.getRecurrenceKind();
9110 
9111       VPValue *ChainOp = Plan->getVPValue(Chain);
9112       unsigned FirstOpId;
9113       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9114              "Only min/max recurrences allowed for inloop reductions");
9115       // Recognize a call to the llvm.fmuladd intrinsic.
9116       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9117       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9118              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9119       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9120         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9121                "Expected to replace a VPWidenSelectSC");
9122         FirstOpId = 1;
9123       } else {
9124         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9125                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9126                "Expected to replace a VPWidenSC");
9127         FirstOpId = 0;
9128       }
9129       unsigned VecOpId =
9130           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9131       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9132 
9133       auto *CondOp = CM.blockNeedsPredicationForAnyReason(R->getParent())
9134                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9135                          : nullptr;
9136 
9137       if (IsFMulAdd) {
9138         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9139         // need to create an fmul recipe to use as the vector operand for the
9140         // fadd reduction.
9141         VPInstruction *FMulRecipe = new VPInstruction(
9142             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9143         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9144         WidenRecipe->getParent()->insert(FMulRecipe,
9145                                          WidenRecipe->getIterator());
9146         VecOp = FMulRecipe;
9147       }
9148       VPReductionRecipe *RedRecipe =
9149           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9150       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9151       Plan->removeVPValueFor(R);
9152       Plan->addVPValue(R, RedRecipe);
9153       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9154       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9155       WidenRecipe->eraseFromParent();
9156 
9157       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9158         VPRecipeBase *CompareRecipe =
9159             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9160         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9161                "Expected to replace a VPWidenSC");
9162         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9163                "Expected no remaining users");
9164         CompareRecipe->eraseFromParent();
9165       }
9166       Chain = R;
9167     }
9168   }
9169 
9170   // If tail is folded by masking, introduce selects between the phi
9171   // and the live-out instruction of each reduction, at the beginning of the
9172   // dedicated latch block.
9173   if (CM.foldTailByMasking()) {
9174     Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
9175     for (VPRecipeBase &R :
9176          Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9177       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9178       if (!PhiR || PhiR->isInLoop())
9179         continue;
9180       VPValue *Cond =
9181           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9182       VPValue *Red = PhiR->getBackedgeValue();
9183       assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
9184              "reduction recipe must be defined before latch");
9185       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9186     }
9187   }
9188 }
9189 
9190 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9191 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9192                                VPSlotTracker &SlotTracker) const {
9193   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9194   IG->getInsertPos()->printAsOperand(O, false);
9195   O << ", ";
9196   getAddr()->printAsOperand(O, SlotTracker);
9197   VPValue *Mask = getMask();
9198   if (Mask) {
9199     O << ", ";
9200     Mask->printAsOperand(O, SlotTracker);
9201   }
9202 
9203   unsigned OpIdx = 0;
9204   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9205     if (!IG->getMember(i))
9206       continue;
9207     if (getNumStoreOperands() > 0) {
9208       O << "\n" << Indent << "  store ";
9209       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9210       O << " to index " << i;
9211     } else {
9212       O << "\n" << Indent << "  ";
9213       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9214       O << " = load from index " << i;
9215     }
9216     ++OpIdx;
9217   }
9218 }
9219 #endif
9220 
9221 void VPWidenCallRecipe::execute(VPTransformState &State) {
9222   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9223                                   *this, State);
9224 }
9225 
9226 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9227   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9228   State.ILV->setDebugLocFromInst(&I);
9229 
9230   // The condition can be loop invariant  but still defined inside the
9231   // loop. This means that we can't just use the original 'cond' value.
9232   // We have to take the 'vectorized' value and pick the first lane.
9233   // Instcombine will make this a no-op.
9234   auto *InvarCond =
9235       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9236 
9237   for (unsigned Part = 0; Part < State.UF; ++Part) {
9238     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9239     Value *Op0 = State.get(getOperand(1), Part);
9240     Value *Op1 = State.get(getOperand(2), Part);
9241     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9242     State.set(this, Sel, Part);
9243     State.ILV->addMetadata(Sel, &I);
9244   }
9245 }
9246 
9247 void VPWidenRecipe::execute(VPTransformState &State) {
9248   auto &I = *cast<Instruction>(getUnderlyingValue());
9249   auto &Builder = State.Builder;
9250   switch (I.getOpcode()) {
9251   case Instruction::Call:
9252   case Instruction::Br:
9253   case Instruction::PHI:
9254   case Instruction::GetElementPtr:
9255   case Instruction::Select:
9256     llvm_unreachable("This instruction is handled by a different recipe.");
9257   case Instruction::UDiv:
9258   case Instruction::SDiv:
9259   case Instruction::SRem:
9260   case Instruction::URem:
9261   case Instruction::Add:
9262   case Instruction::FAdd:
9263   case Instruction::Sub:
9264   case Instruction::FSub:
9265   case Instruction::FNeg:
9266   case Instruction::Mul:
9267   case Instruction::FMul:
9268   case Instruction::FDiv:
9269   case Instruction::FRem:
9270   case Instruction::Shl:
9271   case Instruction::LShr:
9272   case Instruction::AShr:
9273   case Instruction::And:
9274   case Instruction::Or:
9275   case Instruction::Xor: {
9276     // Just widen unops and binops.
9277     State.ILV->setDebugLocFromInst(&I);
9278 
9279     for (unsigned Part = 0; Part < State.UF; ++Part) {
9280       SmallVector<Value *, 2> Ops;
9281       for (VPValue *VPOp : operands())
9282         Ops.push_back(State.get(VPOp, Part));
9283 
9284       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9285 
9286       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9287         VecOp->copyIRFlags(&I);
9288 
9289         // If the instruction is vectorized and was in a basic block that needed
9290         // predication, we can't propagate poison-generating flags (nuw/nsw,
9291         // exact, etc.). The control flow has been linearized and the
9292         // instruction is no longer guarded by the predicate, which could make
9293         // the flag properties to no longer hold.
9294         if (State.MayGeneratePoisonRecipes.contains(this))
9295           VecOp->dropPoisonGeneratingFlags();
9296       }
9297 
9298       // Use this vector value for all users of the original instruction.
9299       State.set(this, V, Part);
9300       State.ILV->addMetadata(V, &I);
9301     }
9302 
9303     break;
9304   }
9305   case Instruction::ICmp:
9306   case Instruction::FCmp: {
9307     // Widen compares. Generate vector compares.
9308     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9309     auto *Cmp = cast<CmpInst>(&I);
9310     State.ILV->setDebugLocFromInst(Cmp);
9311     for (unsigned Part = 0; Part < State.UF; ++Part) {
9312       Value *A = State.get(getOperand(0), Part);
9313       Value *B = State.get(getOperand(1), Part);
9314       Value *C = nullptr;
9315       if (FCmp) {
9316         // Propagate fast math flags.
9317         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9318         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9319         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9320       } else {
9321         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9322       }
9323       State.set(this, C, Part);
9324       State.ILV->addMetadata(C, &I);
9325     }
9326 
9327     break;
9328   }
9329 
9330   case Instruction::ZExt:
9331   case Instruction::SExt:
9332   case Instruction::FPToUI:
9333   case Instruction::FPToSI:
9334   case Instruction::FPExt:
9335   case Instruction::PtrToInt:
9336   case Instruction::IntToPtr:
9337   case Instruction::SIToFP:
9338   case Instruction::UIToFP:
9339   case Instruction::Trunc:
9340   case Instruction::FPTrunc:
9341   case Instruction::BitCast: {
9342     auto *CI = cast<CastInst>(&I);
9343     State.ILV->setDebugLocFromInst(CI);
9344 
9345     /// Vectorize casts.
9346     Type *DestTy = (State.VF.isScalar())
9347                        ? CI->getType()
9348                        : VectorType::get(CI->getType(), State.VF);
9349 
9350     for (unsigned Part = 0; Part < State.UF; ++Part) {
9351       Value *A = State.get(getOperand(0), Part);
9352       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9353       State.set(this, Cast, Part);
9354       State.ILV->addMetadata(Cast, &I);
9355     }
9356     break;
9357   }
9358   default:
9359     // This instruction is not vectorized by simple widening.
9360     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9361     llvm_unreachable("Unhandled instruction!");
9362   } // end of switch.
9363 }
9364 
9365 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9366   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9367   // Construct a vector GEP by widening the operands of the scalar GEP as
9368   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9369   // results in a vector of pointers when at least one operand of the GEP
9370   // is vector-typed. Thus, to keep the representation compact, we only use
9371   // vector-typed operands for loop-varying values.
9372 
9373   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9374     // If we are vectorizing, but the GEP has only loop-invariant operands,
9375     // the GEP we build (by only using vector-typed operands for
9376     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9377     // produce a vector of pointers, we need to either arbitrarily pick an
9378     // operand to broadcast, or broadcast a clone of the original GEP.
9379     // Here, we broadcast a clone of the original.
9380     //
9381     // TODO: If at some point we decide to scalarize instructions having
9382     //       loop-invariant operands, this special case will no longer be
9383     //       required. We would add the scalarization decision to
9384     //       collectLoopScalars() and teach getVectorValue() to broadcast
9385     //       the lane-zero scalar value.
9386     auto *Clone = State.Builder.Insert(GEP->clone());
9387     for (unsigned Part = 0; Part < State.UF; ++Part) {
9388       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9389       State.set(this, EntryPart, Part);
9390       State.ILV->addMetadata(EntryPart, GEP);
9391     }
9392   } else {
9393     // If the GEP has at least one loop-varying operand, we are sure to
9394     // produce a vector of pointers. But if we are only unrolling, we want
9395     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9396     // produce with the code below will be scalar (if VF == 1) or vector
9397     // (otherwise). Note that for the unroll-only case, we still maintain
9398     // values in the vector mapping with initVector, as we do for other
9399     // instructions.
9400     for (unsigned Part = 0; Part < State.UF; ++Part) {
9401       // The pointer operand of the new GEP. If it's loop-invariant, we
9402       // won't broadcast it.
9403       auto *Ptr = IsPtrLoopInvariant
9404                       ? State.get(getOperand(0), VPIteration(0, 0))
9405                       : State.get(getOperand(0), Part);
9406 
9407       // Collect all the indices for the new GEP. If any index is
9408       // loop-invariant, we won't broadcast it.
9409       SmallVector<Value *, 4> Indices;
9410       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9411         VPValue *Operand = getOperand(I);
9412         if (IsIndexLoopInvariant[I - 1])
9413           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9414         else
9415           Indices.push_back(State.get(Operand, Part));
9416       }
9417 
9418       // If the GEP instruction is vectorized and was in a basic block that
9419       // needed predication, we can't propagate the poison-generating 'inbounds'
9420       // flag. The control flow has been linearized and the GEP is no longer
9421       // guarded by the predicate, which could make the 'inbounds' properties to
9422       // no longer hold.
9423       bool IsInBounds =
9424           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9425 
9426       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9427       // but it should be a vector, otherwise.
9428       auto *NewGEP = IsInBounds
9429                          ? State.Builder.CreateInBoundsGEP(
9430                                GEP->getSourceElementType(), Ptr, Indices)
9431                          : State.Builder.CreateGEP(GEP->getSourceElementType(),
9432                                                    Ptr, Indices);
9433       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9434              "NewGEP is not a pointer vector");
9435       State.set(this, NewGEP, Part);
9436       State.ILV->addMetadata(NewGEP, GEP);
9437     }
9438   }
9439 }
9440 
9441 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9442   assert(!State.Instance && "Int or FP induction being replicated.");
9443 
9444   Value *Start = getStartValue()->getLiveInIRValue();
9445   const InductionDescriptor &ID = getInductionDescriptor();
9446   TruncInst *Trunc = getTruncInst();
9447   IRBuilderBase &Builder = State.Builder;
9448   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
9449   assert(State.VF.isVector() && "must have vector VF");
9450 
9451   // The value from the original loop to which we are mapping the new induction
9452   // variable.
9453   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
9454 
9455   auto &DL = EntryVal->getModule()->getDataLayout();
9456 
9457   // Generate code for the induction step. Note that induction steps are
9458   // required to be loop-invariant
9459   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
9460     if (SE.isSCEVable(IV->getType())) {
9461       SCEVExpander Exp(SE, DL, "induction");
9462       return Exp.expandCodeFor(Step, Step->getType(),
9463                                State.CFG.VectorPreHeader->getTerminator());
9464     }
9465     return cast<SCEVUnknown>(Step)->getValue();
9466   };
9467 
9468   // Fast-math-flags propagate from the original induction instruction.
9469   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9470   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
9471     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
9472 
9473   // Now do the actual transformations, and start with creating the step value.
9474   Value *Step = CreateStepValue(ID.getStep());
9475 
9476   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
9477          "Expected either an induction phi-node or a truncate of it!");
9478 
9479   // Construct the initial value of the vector IV in the vector loop preheader
9480   auto CurrIP = Builder.saveIP();
9481   Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
9482   if (isa<TruncInst>(EntryVal)) {
9483     assert(Start->getType()->isIntegerTy() &&
9484            "Truncation requires an integer type");
9485     auto *TruncType = cast<IntegerType>(EntryVal->getType());
9486     Step = Builder.CreateTrunc(Step, TruncType);
9487     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
9488   }
9489 
9490   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
9491   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
9492   Value *SteppedStart = getStepVector(
9493       SplatStart, Zero, Step, ID.getInductionOpcode(), State.VF, State.Builder);
9494 
9495   // We create vector phi nodes for both integer and floating-point induction
9496   // variables. Here, we determine the kind of arithmetic we will perform.
9497   Instruction::BinaryOps AddOp;
9498   Instruction::BinaryOps MulOp;
9499   if (Step->getType()->isIntegerTy()) {
9500     AddOp = Instruction::Add;
9501     MulOp = Instruction::Mul;
9502   } else {
9503     AddOp = ID.getInductionOpcode();
9504     MulOp = Instruction::FMul;
9505   }
9506 
9507   // Multiply the vectorization factor by the step using integer or
9508   // floating-point arithmetic as appropriate.
9509   Type *StepType = Step->getType();
9510   Value *RuntimeVF;
9511   if (Step->getType()->isFloatingPointTy())
9512     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
9513   else
9514     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
9515   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
9516 
9517   // Create a vector splat to use in the induction update.
9518   //
9519   // FIXME: If the step is non-constant, we create the vector splat with
9520   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
9521   //        handle a constant vector splat.
9522   Value *SplatVF = isa<Constant>(Mul)
9523                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
9524                        : Builder.CreateVectorSplat(State.VF, Mul);
9525   Builder.restoreIP(CurrIP);
9526 
9527   // We may need to add the step a number of times, depending on the unroll
9528   // factor. The last of those goes into the PHI.
9529   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
9530                                     &*State.CFG.PrevBB->getFirstInsertionPt());
9531   VecInd->setDebugLoc(EntryVal->getDebugLoc());
9532   Instruction *LastInduction = VecInd;
9533   for (unsigned Part = 0; Part < State.UF; ++Part) {
9534     State.set(this, LastInduction, Part);
9535 
9536     if (isa<TruncInst>(EntryVal))
9537       State.ILV->addMetadata(LastInduction, EntryVal);
9538 
9539     LastInduction = cast<Instruction>(
9540         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
9541     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
9542   }
9543 
9544   LastInduction->setName("vec.ind.next");
9545   VecInd->addIncoming(SteppedStart, State.CFG.VectorPreHeader);
9546   // Add induction update using an incorrect block temporarily. The phi node
9547   // will be fixed after VPlan execution. Note that at this point the latch
9548   // block cannot be used, as it does not exist yet.
9549   // TODO: Model increment value in VPlan, by turning the recipe into a
9550   // multi-def and a subclass of VPHeaderPHIRecipe.
9551   VecInd->addIncoming(LastInduction, State.CFG.VectorPreHeader);
9552 }
9553 
9554 void VPWidenPointerInductionRecipe::execute(VPTransformState &State) {
9555   assert(IndDesc.getKind() == InductionDescriptor::IK_PtrInduction &&
9556          "Not a pointer induction according to InductionDescriptor!");
9557   assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
9558          "Unexpected type.");
9559 
9560   auto *IVR = getParent()->getPlan()->getCanonicalIV();
9561   PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
9562 
9563   if (all_of(users(), [this](const VPUser *U) {
9564         return cast<VPRecipeBase>(U)->usesScalars(this);
9565       })) {
9566     // This is the normalized GEP that starts counting at zero.
9567     Value *PtrInd = State.Builder.CreateSExtOrTrunc(
9568         CanonicalIV, IndDesc.getStep()->getType());
9569     // Determine the number of scalars we need to generate for each unroll
9570     // iteration. If the instruction is uniform, we only need to generate the
9571     // first lane. Otherwise, we generate all VF values.
9572     bool IsUniform = vputils::onlyFirstLaneUsed(this);
9573     assert((IsUniform || !State.VF.isScalable()) &&
9574            "Cannot scalarize a scalable VF");
9575     unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
9576 
9577     for (unsigned Part = 0; Part < State.UF; ++Part) {
9578       Value *PartStart =
9579           createStepForVF(State.Builder, PtrInd->getType(), State.VF, Part);
9580 
9581       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
9582         Value *Idx = State.Builder.CreateAdd(
9583             PartStart, ConstantInt::get(PtrInd->getType(), Lane));
9584         Value *GlobalIdx = State.Builder.CreateAdd(PtrInd, Idx);
9585 
9586         Value *Step = CreateStepValue(IndDesc.getStep(), SE,
9587                                       State.CFG.PrevBB->getTerminator());
9588         Value *SclrGep = emitTransformedIndex(
9589             State.Builder, GlobalIdx, IndDesc.getStartValue(), Step, IndDesc);
9590         SclrGep->setName("next.gep");
9591         State.set(this, SclrGep, VPIteration(Part, Lane));
9592       }
9593     }
9594     return;
9595   }
9596 
9597   assert(isa<SCEVConstant>(IndDesc.getStep()) &&
9598          "Induction step not a SCEV constant!");
9599   Type *PhiType = IndDesc.getStep()->getType();
9600 
9601   // Build a pointer phi
9602   Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
9603   Type *ScStValueType = ScalarStartValue->getType();
9604   PHINode *NewPointerPhi =
9605       PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
9606   NewPointerPhi->addIncoming(ScalarStartValue, State.CFG.VectorPreHeader);
9607 
9608   // A pointer induction, performed by using a gep
9609   const DataLayout &DL = NewPointerPhi->getModule()->getDataLayout();
9610   Instruction *InductionLoc = &*State.Builder.GetInsertPoint();
9611 
9612   const SCEV *ScalarStep = IndDesc.getStep();
9613   SCEVExpander Exp(SE, DL, "induction");
9614   Value *ScalarStepValue = Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
9615   Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
9616   Value *NumUnrolledElems =
9617       State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
9618   Value *InductionGEP = GetElementPtrInst::Create(
9619       IndDesc.getElementType(), NewPointerPhi,
9620       State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
9621       InductionLoc);
9622   // Add induction update using an incorrect block temporarily. The phi node
9623   // will be fixed after VPlan execution. Note that at this point the latch
9624   // block cannot be used, as it does not exist yet.
9625   // TODO: Model increment value in VPlan, by turning the recipe into a
9626   // multi-def and a subclass of VPHeaderPHIRecipe.
9627   NewPointerPhi->addIncoming(InductionGEP, State.CFG.VectorPreHeader);
9628 
9629   // Create UF many actual address geps that use the pointer
9630   // phi as base and a vectorized version of the step value
9631   // (<step*0, ..., step*N>) as offset.
9632   for (unsigned Part = 0; Part < State.UF; ++Part) {
9633     Type *VecPhiType = VectorType::get(PhiType, State.VF);
9634     Value *StartOffsetScalar =
9635         State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
9636     Value *StartOffset =
9637         State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
9638     // Create a vector of consecutive numbers from zero to VF.
9639     StartOffset = State.Builder.CreateAdd(
9640         StartOffset, State.Builder.CreateStepVector(VecPhiType));
9641 
9642     Value *GEP = State.Builder.CreateGEP(
9643         IndDesc.getElementType(), NewPointerPhi,
9644         State.Builder.CreateMul(
9645             StartOffset,
9646             State.Builder.CreateVectorSplat(State.VF, ScalarStepValue),
9647             "vector.gep"));
9648     State.set(this, GEP, Part);
9649   }
9650 }
9651 
9652 void VPScalarIVStepsRecipe::execute(VPTransformState &State) {
9653   assert(!State.Instance && "VPScalarIVStepsRecipe being replicated.");
9654 
9655   // Fast-math-flags propagate from the original induction instruction.
9656   IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9657   if (IndDesc.getInductionBinOp() &&
9658       isa<FPMathOperator>(IndDesc.getInductionBinOp()))
9659     State.Builder.setFastMathFlags(
9660         IndDesc.getInductionBinOp()->getFastMathFlags());
9661 
9662   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9663   auto CreateScalarIV = [&](Value *&Step) -> Value * {
9664     Value *ScalarIV = State.get(getCanonicalIV(), VPIteration(0, 0));
9665     auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
9666     if (!isCanonical() || CanonicalIV->getType() != Ty) {
9667       ScalarIV =
9668           Ty->isIntegerTy()
9669               ? State.Builder.CreateSExtOrTrunc(ScalarIV, Ty)
9670               : State.Builder.CreateCast(Instruction::SIToFP, ScalarIV, Ty);
9671       ScalarIV = emitTransformedIndex(State.Builder, ScalarIV,
9672                                       getStartValue()->getLiveInIRValue(), Step,
9673                                       IndDesc);
9674       ScalarIV->setName("offset.idx");
9675     }
9676     if (TruncToTy) {
9677       assert(Step->getType()->isIntegerTy() &&
9678              "Truncation requires an integer step");
9679       ScalarIV = State.Builder.CreateTrunc(ScalarIV, TruncToTy);
9680       Step = State.Builder.CreateTrunc(Step, TruncToTy);
9681     }
9682     return ScalarIV;
9683   };
9684 
9685   Value *ScalarIV = CreateScalarIV(Step);
9686   if (State.VF.isVector()) {
9687     buildScalarSteps(ScalarIV, Step, IndDesc, this, State);
9688     return;
9689   }
9690 
9691   for (unsigned Part = 0; Part < State.UF; ++Part) {
9692     assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
9693     Value *EntryPart;
9694     if (Step->getType()->isFloatingPointTy()) {
9695       Value *StartIdx =
9696           getRuntimeVFAsFloat(State.Builder, Step->getType(), State.VF * Part);
9697       // Floating-point operations inherit FMF via the builder's flags.
9698       Value *MulOp = State.Builder.CreateFMul(StartIdx, Step);
9699       EntryPart = State.Builder.CreateBinOp(IndDesc.getInductionOpcode(),
9700                                             ScalarIV, MulOp);
9701     } else {
9702       Value *StartIdx =
9703           getRuntimeVF(State.Builder, Step->getType(), State.VF * Part);
9704       EntryPart = State.Builder.CreateAdd(
9705           ScalarIV, State.Builder.CreateMul(StartIdx, Step), "induction");
9706     }
9707     State.set(this, EntryPart, Part);
9708   }
9709 }
9710 
9711 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9712   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9713                                  State);
9714 }
9715 
9716 void VPBlendRecipe::execute(VPTransformState &State) {
9717   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9718   // We know that all PHIs in non-header blocks are converted into
9719   // selects, so we don't have to worry about the insertion order and we
9720   // can just use the builder.
9721   // At this point we generate the predication tree. There may be
9722   // duplications since this is a simple recursive scan, but future
9723   // optimizations will clean it up.
9724 
9725   unsigned NumIncoming = getNumIncomingValues();
9726 
9727   // Generate a sequence of selects of the form:
9728   // SELECT(Mask3, In3,
9729   //        SELECT(Mask2, In2,
9730   //               SELECT(Mask1, In1,
9731   //                      In0)))
9732   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9733   // are essentially undef are taken from In0.
9734   InnerLoopVectorizer::VectorParts Entry(State.UF);
9735   for (unsigned In = 0; In < NumIncoming; ++In) {
9736     for (unsigned Part = 0; Part < State.UF; ++Part) {
9737       // We might have single edge PHIs (blocks) - use an identity
9738       // 'select' for the first PHI operand.
9739       Value *In0 = State.get(getIncomingValue(In), Part);
9740       if (In == 0)
9741         Entry[Part] = In0; // Initialize with the first incoming value.
9742       else {
9743         // Select between the current value and the previous incoming edge
9744         // based on the incoming mask.
9745         Value *Cond = State.get(getMask(In), Part);
9746         Entry[Part] =
9747             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9748       }
9749     }
9750   }
9751   for (unsigned Part = 0; Part < State.UF; ++Part)
9752     State.set(this, Entry[Part], Part);
9753 }
9754 
9755 void VPInterleaveRecipe::execute(VPTransformState &State) {
9756   assert(!State.Instance && "Interleave group being replicated.");
9757   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9758                                       getStoredValues(), getMask());
9759 }
9760 
9761 void VPReductionRecipe::execute(VPTransformState &State) {
9762   assert(!State.Instance && "Reduction being replicated.");
9763   Value *PrevInChain = State.get(getChainOp(), 0);
9764   RecurKind Kind = RdxDesc->getRecurrenceKind();
9765   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9766   // Propagate the fast-math flags carried by the underlying instruction.
9767   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9768   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9769   for (unsigned Part = 0; Part < State.UF; ++Part) {
9770     Value *NewVecOp = State.get(getVecOp(), Part);
9771     if (VPValue *Cond = getCondOp()) {
9772       Value *NewCond = State.get(Cond, Part);
9773       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9774       Value *Iden = RdxDesc->getRecurrenceIdentity(
9775           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9776       Value *IdenVec =
9777           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9778       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9779       NewVecOp = Select;
9780     }
9781     Value *NewRed;
9782     Value *NextInChain;
9783     if (IsOrdered) {
9784       if (State.VF.isVector())
9785         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9786                                         PrevInChain);
9787       else
9788         NewRed = State.Builder.CreateBinOp(
9789             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9790             NewVecOp);
9791       PrevInChain = NewRed;
9792     } else {
9793       PrevInChain = State.get(getChainOp(), Part);
9794       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9795     }
9796     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9797       NextInChain =
9798           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9799                          NewRed, PrevInChain);
9800     } else if (IsOrdered)
9801       NextInChain = NewRed;
9802     else
9803       NextInChain = State.Builder.CreateBinOp(
9804           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9805           PrevInChain);
9806     State.set(this, NextInChain, Part);
9807   }
9808 }
9809 
9810 void VPReplicateRecipe::execute(VPTransformState &State) {
9811   if (State.Instance) { // Generate a single instance.
9812     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9813     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9814                                     IsPredicated, State);
9815     // Insert scalar instance packing it into a vector.
9816     if (AlsoPack && State.VF.isVector()) {
9817       // If we're constructing lane 0, initialize to start from poison.
9818       if (State.Instance->Lane.isFirstLane()) {
9819         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9820         Value *Poison = PoisonValue::get(
9821             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9822         State.set(this, Poison, State.Instance->Part);
9823       }
9824       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9825     }
9826     return;
9827   }
9828 
9829   // Generate scalar instances for all VF lanes of all UF parts, unless the
9830   // instruction is uniform inwhich case generate only the first lane for each
9831   // of the UF parts.
9832   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9833   assert((!State.VF.isScalable() || IsUniform) &&
9834          "Can't scalarize a scalable vector");
9835   for (unsigned Part = 0; Part < State.UF; ++Part)
9836     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9837       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9838                                       VPIteration(Part, Lane), IsPredicated,
9839                                       State);
9840 }
9841 
9842 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9843   assert(State.Instance && "Branch on Mask works only on single instance.");
9844 
9845   unsigned Part = State.Instance->Part;
9846   unsigned Lane = State.Instance->Lane.getKnownLane();
9847 
9848   Value *ConditionBit = nullptr;
9849   VPValue *BlockInMask = getMask();
9850   if (BlockInMask) {
9851     ConditionBit = State.get(BlockInMask, Part);
9852     if (ConditionBit->getType()->isVectorTy())
9853       ConditionBit = State.Builder.CreateExtractElement(
9854           ConditionBit, State.Builder.getInt32(Lane));
9855   } else // Block in mask is all-one.
9856     ConditionBit = State.Builder.getTrue();
9857 
9858   // Replace the temporary unreachable terminator with a new conditional branch,
9859   // whose two destinations will be set later when they are created.
9860   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9861   assert(isa<UnreachableInst>(CurrentTerminator) &&
9862          "Expected to replace unreachable terminator with conditional branch.");
9863   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9864   CondBr->setSuccessor(0, nullptr);
9865   ReplaceInstWithInst(CurrentTerminator, CondBr);
9866 }
9867 
9868 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9869   assert(State.Instance && "Predicated instruction PHI works per instance.");
9870   Instruction *ScalarPredInst =
9871       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9872   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9873   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9874   assert(PredicatingBB && "Predicated block has no single predecessor.");
9875   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9876          "operand must be VPReplicateRecipe");
9877 
9878   // By current pack/unpack logic we need to generate only a single phi node: if
9879   // a vector value for the predicated instruction exists at this point it means
9880   // the instruction has vector users only, and a phi for the vector value is
9881   // needed. In this case the recipe of the predicated instruction is marked to
9882   // also do that packing, thereby "hoisting" the insert-element sequence.
9883   // Otherwise, a phi node for the scalar value is needed.
9884   unsigned Part = State.Instance->Part;
9885   if (State.hasVectorValue(getOperand(0), Part)) {
9886     Value *VectorValue = State.get(getOperand(0), Part);
9887     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9888     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9889     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9890     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9891     if (State.hasVectorValue(this, Part))
9892       State.reset(this, VPhi, Part);
9893     else
9894       State.set(this, VPhi, Part);
9895     // NOTE: Currently we need to update the value of the operand, so the next
9896     // predicated iteration inserts its generated value in the correct vector.
9897     State.reset(getOperand(0), VPhi, Part);
9898   } else {
9899     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9900     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9901     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9902                      PredicatingBB);
9903     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9904     if (State.hasScalarValue(this, *State.Instance))
9905       State.reset(this, Phi, *State.Instance);
9906     else
9907       State.set(this, Phi, *State.Instance);
9908     // NOTE: Currently we need to update the value of the operand, so the next
9909     // predicated iteration inserts its generated value in the correct vector.
9910     State.reset(getOperand(0), Phi, *State.Instance);
9911   }
9912 }
9913 
9914 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9915   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9916 
9917   // Attempt to issue a wide load.
9918   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9919   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9920 
9921   assert((LI || SI) && "Invalid Load/Store instruction");
9922   assert((!SI || StoredValue) && "No stored value provided for widened store");
9923   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9924 
9925   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9926 
9927   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9928   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9929   bool CreateGatherScatter = !Consecutive;
9930 
9931   auto &Builder = State.Builder;
9932   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9933   bool isMaskRequired = getMask();
9934   if (isMaskRequired)
9935     for (unsigned Part = 0; Part < State.UF; ++Part)
9936       BlockInMaskParts[Part] = State.get(getMask(), Part);
9937 
9938   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9939     // Calculate the pointer for the specific unroll-part.
9940     GetElementPtrInst *PartPtr = nullptr;
9941 
9942     bool InBounds = false;
9943     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9944       InBounds = gep->isInBounds();
9945     if (Reverse) {
9946       // If the address is consecutive but reversed, then the
9947       // wide store needs to start at the last vector element.
9948       // RunTimeVF =  VScale * VF.getKnownMinValue()
9949       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9950       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9951       // NumElt = -Part * RunTimeVF
9952       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9953       // LastLane = 1 - RunTimeVF
9954       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9955       PartPtr =
9956           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9957       PartPtr->setIsInBounds(InBounds);
9958       PartPtr = cast<GetElementPtrInst>(
9959           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9960       PartPtr->setIsInBounds(InBounds);
9961       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
9962         BlockInMaskParts[Part] =
9963             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
9964     } else {
9965       Value *Increment =
9966           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
9967       PartPtr = cast<GetElementPtrInst>(
9968           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
9969       PartPtr->setIsInBounds(InBounds);
9970     }
9971 
9972     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
9973     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
9974   };
9975 
9976   // Handle Stores:
9977   if (SI) {
9978     State.ILV->setDebugLocFromInst(SI);
9979 
9980     for (unsigned Part = 0; Part < State.UF; ++Part) {
9981       Instruction *NewSI = nullptr;
9982       Value *StoredVal = State.get(StoredValue, Part);
9983       if (CreateGatherScatter) {
9984         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9985         Value *VectorGep = State.get(getAddr(), Part);
9986         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
9987                                             MaskPart);
9988       } else {
9989         if (Reverse) {
9990           // If we store to reverse consecutive memory locations, then we need
9991           // to reverse the order of elements in the stored value.
9992           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
9993           // We don't want to update the value in the map as it might be used in
9994           // another expression. So don't call resetVectorValue(StoredVal).
9995         }
9996         auto *VecPtr =
9997             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9998         if (isMaskRequired)
9999           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
10000                                             BlockInMaskParts[Part]);
10001         else
10002           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
10003       }
10004       State.ILV->addMetadata(NewSI, SI);
10005     }
10006     return;
10007   }
10008 
10009   // Handle loads.
10010   assert(LI && "Must have a load instruction");
10011   State.ILV->setDebugLocFromInst(LI);
10012   for (unsigned Part = 0; Part < State.UF; ++Part) {
10013     Value *NewLI;
10014     if (CreateGatherScatter) {
10015       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10016       Value *VectorGep = State.get(getAddr(), Part);
10017       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
10018                                          nullptr, "wide.masked.gather");
10019       State.ILV->addMetadata(NewLI, LI);
10020     } else {
10021       auto *VecPtr =
10022           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10023       if (isMaskRequired)
10024         NewLI = Builder.CreateMaskedLoad(
10025             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
10026             PoisonValue::get(DataTy), "wide.masked.load");
10027       else
10028         NewLI =
10029             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
10030 
10031       // Add metadata to the load, but setVectorValue to the reverse shuffle.
10032       State.ILV->addMetadata(NewLI, LI);
10033       if (Reverse)
10034         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
10035     }
10036 
10037     State.set(this, NewLI, Part);
10038   }
10039 }
10040 
10041 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10042 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10043 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10044 // for predication.
10045 static ScalarEpilogueLowering getScalarEpilogueLowering(
10046     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10047     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10048     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10049     LoopVectorizationLegality &LVL) {
10050   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10051   // don't look at hints or options, and don't request a scalar epilogue.
10052   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10053   // LoopAccessInfo (due to code dependency and not being able to reliably get
10054   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10055   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10056   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10057   // back to the old way and vectorize with versioning when forced. See D81345.)
10058   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10059                                                       PGSOQueryType::IRPass) &&
10060                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10061     return CM_ScalarEpilogueNotAllowedOptSize;
10062 
10063   // 2) If set, obey the directives
10064   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10065     switch (PreferPredicateOverEpilogue) {
10066     case PreferPredicateTy::ScalarEpilogue:
10067       return CM_ScalarEpilogueAllowed;
10068     case PreferPredicateTy::PredicateElseScalarEpilogue:
10069       return CM_ScalarEpilogueNotNeededUsePredicate;
10070     case PreferPredicateTy::PredicateOrDontVectorize:
10071       return CM_ScalarEpilogueNotAllowedUsePredicate;
10072     };
10073   }
10074 
10075   // 3) If set, obey the hints
10076   switch (Hints.getPredicate()) {
10077   case LoopVectorizeHints::FK_Enabled:
10078     return CM_ScalarEpilogueNotNeededUsePredicate;
10079   case LoopVectorizeHints::FK_Disabled:
10080     return CM_ScalarEpilogueAllowed;
10081   };
10082 
10083   // 4) if the TTI hook indicates this is profitable, request predication.
10084   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10085                                        LVL.getLAI()))
10086     return CM_ScalarEpilogueNotNeededUsePredicate;
10087 
10088   return CM_ScalarEpilogueAllowed;
10089 }
10090 
10091 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10092   // If Values have been set for this Def return the one relevant for \p Part.
10093   if (hasVectorValue(Def, Part))
10094     return Data.PerPartOutput[Def][Part];
10095 
10096   if (!hasScalarValue(Def, {Part, 0})) {
10097     Value *IRV = Def->getLiveInIRValue();
10098     Value *B = ILV->getBroadcastInstrs(IRV);
10099     set(Def, B, Part);
10100     return B;
10101   }
10102 
10103   Value *ScalarValue = get(Def, {Part, 0});
10104   // If we aren't vectorizing, we can just copy the scalar map values over
10105   // to the vector map.
10106   if (VF.isScalar()) {
10107     set(Def, ScalarValue, Part);
10108     return ScalarValue;
10109   }
10110 
10111   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10112   bool IsUniform = RepR && RepR->isUniform();
10113 
10114   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10115   // Check if there is a scalar value for the selected lane.
10116   if (!hasScalarValue(Def, {Part, LastLane})) {
10117     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10118     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) ||
10119             isa<VPScalarIVStepsRecipe>(Def->getDef())) &&
10120            "unexpected recipe found to be invariant");
10121     IsUniform = true;
10122     LastLane = 0;
10123   }
10124 
10125   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10126   // Set the insert point after the last scalarized instruction or after the
10127   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10128   // will directly follow the scalar definitions.
10129   auto OldIP = Builder.saveIP();
10130   auto NewIP =
10131       isa<PHINode>(LastInst)
10132           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10133           : std::next(BasicBlock::iterator(LastInst));
10134   Builder.SetInsertPoint(&*NewIP);
10135 
10136   // However, if we are vectorizing, we need to construct the vector values.
10137   // If the value is known to be uniform after vectorization, we can just
10138   // broadcast the scalar value corresponding to lane zero for each unroll
10139   // iteration. Otherwise, we construct the vector values using
10140   // insertelement instructions. Since the resulting vectors are stored in
10141   // State, we will only generate the insertelements once.
10142   Value *VectorValue = nullptr;
10143   if (IsUniform) {
10144     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10145     set(Def, VectorValue, Part);
10146   } else {
10147     // Initialize packing with insertelements to start from undef.
10148     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10149     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10150     set(Def, Undef, Part);
10151     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10152       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10153     VectorValue = get(Def, Part);
10154   }
10155   Builder.restoreIP(OldIP);
10156   return VectorValue;
10157 }
10158 
10159 // Process the loop in the VPlan-native vectorization path. This path builds
10160 // VPlan upfront in the vectorization pipeline, which allows to apply
10161 // VPlan-to-VPlan transformations from the very beginning without modifying the
10162 // input LLVM IR.
10163 static bool processLoopInVPlanNativePath(
10164     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10165     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10166     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10167     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10168     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10169     LoopVectorizationRequirements &Requirements) {
10170 
10171   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10172     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10173     return false;
10174   }
10175   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10176   Function *F = L->getHeader()->getParent();
10177   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10178 
10179   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10180       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10181 
10182   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10183                                 &Hints, IAI);
10184   // Use the planner for outer loop vectorization.
10185   // TODO: CM is not used at this point inside the planner. Turn CM into an
10186   // optional argument if we don't need it in the future.
10187   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10188                                Requirements, ORE);
10189 
10190   // Get user vectorization factor.
10191   ElementCount UserVF = Hints.getWidth();
10192 
10193   CM.collectElementTypesForWidening();
10194 
10195   // Plan how to best vectorize, return the best VF and its cost.
10196   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10197 
10198   // If we are stress testing VPlan builds, do not attempt to generate vector
10199   // code. Masked vector code generation support will follow soon.
10200   // Also, do not attempt to vectorize if no vector code will be produced.
10201   if (VPlanBuildStressTest || EnableVPlanPredication ||
10202       VectorizationFactor::Disabled() == VF)
10203     return false;
10204 
10205   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10206 
10207   {
10208     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10209                              F->getParent()->getDataLayout());
10210     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10211                            &CM, BFI, PSI, Checks);
10212     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10213                       << L->getHeader()->getParent()->getName() << "\"\n");
10214     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10215   }
10216 
10217   // Mark the loop as already vectorized to avoid vectorizing again.
10218   Hints.setAlreadyVectorized();
10219   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10220   return true;
10221 }
10222 
10223 // Emit a remark if there are stores to floats that required a floating point
10224 // extension. If the vectorized loop was generated with floating point there
10225 // will be a performance penalty from the conversion overhead and the change in
10226 // the vector width.
10227 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10228   SmallVector<Instruction *, 4> Worklist;
10229   for (BasicBlock *BB : L->getBlocks()) {
10230     for (Instruction &Inst : *BB) {
10231       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10232         if (S->getValueOperand()->getType()->isFloatTy())
10233           Worklist.push_back(S);
10234       }
10235     }
10236   }
10237 
10238   // Traverse the floating point stores upwards searching, for floating point
10239   // conversions.
10240   SmallPtrSet<const Instruction *, 4> Visited;
10241   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10242   while (!Worklist.empty()) {
10243     auto *I = Worklist.pop_back_val();
10244     if (!L->contains(I))
10245       continue;
10246     if (!Visited.insert(I).second)
10247       continue;
10248 
10249     // Emit a remark if the floating point store required a floating
10250     // point conversion.
10251     // TODO: More work could be done to identify the root cause such as a
10252     // constant or a function return type and point the user to it.
10253     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10254       ORE->emit([&]() {
10255         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10256                                           I->getDebugLoc(), L->getHeader())
10257                << "floating point conversion changes vector width. "
10258                << "Mixed floating point precision requires an up/down "
10259                << "cast that will negatively impact performance.";
10260       });
10261 
10262     for (Use &Op : I->operands())
10263       if (auto *OpI = dyn_cast<Instruction>(Op))
10264         Worklist.push_back(OpI);
10265   }
10266 }
10267 
10268 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10269     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10270                                !EnableLoopInterleaving),
10271       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10272                               !EnableLoopVectorization) {}
10273 
10274 bool LoopVectorizePass::processLoop(Loop *L) {
10275   assert((EnableVPlanNativePath || L->isInnermost()) &&
10276          "VPlan-native path is not enabled. Only process inner loops.");
10277 
10278 #ifndef NDEBUG
10279   const std::string DebugLocStr = getDebugLocString(L);
10280 #endif /* NDEBUG */
10281 
10282   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
10283                     << L->getHeader()->getParent()->getName() << "' from "
10284                     << DebugLocStr << "\n");
10285 
10286   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10287 
10288   LLVM_DEBUG(
10289       dbgs() << "LV: Loop hints:"
10290              << " force="
10291              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10292                      ? "disabled"
10293                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10294                             ? "enabled"
10295                             : "?"))
10296              << " width=" << Hints.getWidth()
10297              << " interleave=" << Hints.getInterleave() << "\n");
10298 
10299   // Function containing loop
10300   Function *F = L->getHeader()->getParent();
10301 
10302   // Looking at the diagnostic output is the only way to determine if a loop
10303   // was vectorized (other than looking at the IR or machine code), so it
10304   // is important to generate an optimization remark for each loop. Most of
10305   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10306   // generated as OptimizationRemark and OptimizationRemarkMissed are
10307   // less verbose reporting vectorized loops and unvectorized loops that may
10308   // benefit from vectorization, respectively.
10309 
10310   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10311     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10312     return false;
10313   }
10314 
10315   PredicatedScalarEvolution PSE(*SE, *L);
10316 
10317   // Check if it is legal to vectorize the loop.
10318   LoopVectorizationRequirements Requirements;
10319   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10320                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10321   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10322     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10323     Hints.emitRemarkWithHints();
10324     return false;
10325   }
10326 
10327   // Check the function attributes and profiles to find out if this function
10328   // should be optimized for size.
10329   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10330       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10331 
10332   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10333   // here. They may require CFG and instruction level transformations before
10334   // even evaluating whether vectorization is profitable. Since we cannot modify
10335   // the incoming IR, we need to build VPlan upfront in the vectorization
10336   // pipeline.
10337   if (!L->isInnermost())
10338     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10339                                         ORE, BFI, PSI, Hints, Requirements);
10340 
10341   assert(L->isInnermost() && "Inner loop expected.");
10342 
10343   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10344   // count by optimizing for size, to minimize overheads.
10345   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10346   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10347     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10348                       << "This loop is worth vectorizing only if no scalar "
10349                       << "iteration overheads are incurred.");
10350     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10351       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10352     else {
10353       LLVM_DEBUG(dbgs() << "\n");
10354       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10355     }
10356   }
10357 
10358   // Check the function attributes to see if implicit floats are allowed.
10359   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10360   // an integer loop and the vector instructions selected are purely integer
10361   // vector instructions?
10362   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10363     reportVectorizationFailure(
10364         "Can't vectorize when the NoImplicitFloat attribute is used",
10365         "loop not vectorized due to NoImplicitFloat attribute",
10366         "NoImplicitFloat", ORE, L);
10367     Hints.emitRemarkWithHints();
10368     return false;
10369   }
10370 
10371   // Check if the target supports potentially unsafe FP vectorization.
10372   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10373   // for the target we're vectorizing for, to make sure none of the
10374   // additional fp-math flags can help.
10375   if (Hints.isPotentiallyUnsafe() &&
10376       TTI->isFPVectorizationPotentiallyUnsafe()) {
10377     reportVectorizationFailure(
10378         "Potentially unsafe FP op prevents vectorization",
10379         "loop not vectorized due to unsafe FP support.",
10380         "UnsafeFP", ORE, L);
10381     Hints.emitRemarkWithHints();
10382     return false;
10383   }
10384 
10385   bool AllowOrderedReductions;
10386   // If the flag is set, use that instead and override the TTI behaviour.
10387   if (ForceOrderedReductions.getNumOccurrences() > 0)
10388     AllowOrderedReductions = ForceOrderedReductions;
10389   else
10390     AllowOrderedReductions = TTI->enableOrderedReductions();
10391   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10392     ORE->emit([&]() {
10393       auto *ExactFPMathInst = Requirements.getExactFPInst();
10394       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10395                                                  ExactFPMathInst->getDebugLoc(),
10396                                                  ExactFPMathInst->getParent())
10397              << "loop not vectorized: cannot prove it is safe to reorder "
10398                 "floating-point operations";
10399     });
10400     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10401                          "reorder floating-point operations\n");
10402     Hints.emitRemarkWithHints();
10403     return false;
10404   }
10405 
10406   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10407   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10408 
10409   // If an override option has been passed in for interleaved accesses, use it.
10410   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10411     UseInterleaved = EnableInterleavedMemAccesses;
10412 
10413   // Analyze interleaved memory accesses.
10414   if (UseInterleaved) {
10415     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10416   }
10417 
10418   // Use the cost model.
10419   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10420                                 F, &Hints, IAI);
10421   CM.collectValuesToIgnore();
10422   CM.collectElementTypesForWidening();
10423 
10424   // Use the planner for vectorization.
10425   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10426                                Requirements, ORE);
10427 
10428   // Get user vectorization factor and interleave count.
10429   ElementCount UserVF = Hints.getWidth();
10430   unsigned UserIC = Hints.getInterleave();
10431 
10432   // Plan how to best vectorize, return the best VF and its cost.
10433   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10434 
10435   VectorizationFactor VF = VectorizationFactor::Disabled();
10436   unsigned IC = 1;
10437 
10438   if (MaybeVF) {
10439     VF = *MaybeVF;
10440     // Select the interleave count.
10441     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10442   }
10443 
10444   // Identify the diagnostic messages that should be produced.
10445   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10446   bool VectorizeLoop = true, InterleaveLoop = true;
10447   if (VF.Width.isScalar()) {
10448     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10449     VecDiagMsg = std::make_pair(
10450         "VectorizationNotBeneficial",
10451         "the cost-model indicates that vectorization is not beneficial");
10452     VectorizeLoop = false;
10453   }
10454 
10455   if (!MaybeVF && UserIC > 1) {
10456     // Tell the user interleaving was avoided up-front, despite being explicitly
10457     // requested.
10458     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10459                          "interleaving should be avoided up front\n");
10460     IntDiagMsg = std::make_pair(
10461         "InterleavingAvoided",
10462         "Ignoring UserIC, because interleaving was avoided up front");
10463     InterleaveLoop = false;
10464   } else if (IC == 1 && UserIC <= 1) {
10465     // Tell the user interleaving is not beneficial.
10466     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10467     IntDiagMsg = std::make_pair(
10468         "InterleavingNotBeneficial",
10469         "the cost-model indicates that interleaving is not beneficial");
10470     InterleaveLoop = false;
10471     if (UserIC == 1) {
10472       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10473       IntDiagMsg.second +=
10474           " and is explicitly disabled or interleave count is set to 1";
10475     }
10476   } else if (IC > 1 && UserIC == 1) {
10477     // Tell the user interleaving is beneficial, but it explicitly disabled.
10478     LLVM_DEBUG(
10479         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10480     IntDiagMsg = std::make_pair(
10481         "InterleavingBeneficialButDisabled",
10482         "the cost-model indicates that interleaving is beneficial "
10483         "but is explicitly disabled or interleave count is set to 1");
10484     InterleaveLoop = false;
10485   }
10486 
10487   // Override IC if user provided an interleave count.
10488   IC = UserIC > 0 ? UserIC : IC;
10489 
10490   // Emit diagnostic messages, if any.
10491   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10492   if (!VectorizeLoop && !InterleaveLoop) {
10493     // Do not vectorize or interleaving the loop.
10494     ORE->emit([&]() {
10495       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10496                                       L->getStartLoc(), L->getHeader())
10497              << VecDiagMsg.second;
10498     });
10499     ORE->emit([&]() {
10500       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10501                                       L->getStartLoc(), L->getHeader())
10502              << IntDiagMsg.second;
10503     });
10504     return false;
10505   } else if (!VectorizeLoop && InterleaveLoop) {
10506     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10507     ORE->emit([&]() {
10508       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10509                                         L->getStartLoc(), L->getHeader())
10510              << VecDiagMsg.second;
10511     });
10512   } else if (VectorizeLoop && !InterleaveLoop) {
10513     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10514                       << ") in " << DebugLocStr << '\n');
10515     ORE->emit([&]() {
10516       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10517                                         L->getStartLoc(), L->getHeader())
10518              << IntDiagMsg.second;
10519     });
10520   } else if (VectorizeLoop && InterleaveLoop) {
10521     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10522                       << ") in " << DebugLocStr << '\n');
10523     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10524   }
10525 
10526   bool DisableRuntimeUnroll = false;
10527   MDNode *OrigLoopID = L->getLoopID();
10528   {
10529     // Optimistically generate runtime checks. Drop them if they turn out to not
10530     // be profitable. Limit the scope of Checks, so the cleanup happens
10531     // immediately after vector codegeneration is done.
10532     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10533                              F->getParent()->getDataLayout());
10534     if (!VF.Width.isScalar() || IC > 1)
10535       Checks.Create(L, *LVL.getLAI(), PSE.getPredicate());
10536 
10537     using namespace ore;
10538     if (!VectorizeLoop) {
10539       assert(IC > 1 && "interleave count should not be 1 or 0");
10540       // If we decided that it is not legal to vectorize the loop, then
10541       // interleave it.
10542       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10543                                  &CM, BFI, PSI, Checks);
10544 
10545       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10546       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10547 
10548       ORE->emit([&]() {
10549         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10550                                   L->getHeader())
10551                << "interleaved loop (interleaved count: "
10552                << NV("InterleaveCount", IC) << ")";
10553       });
10554     } else {
10555       // If we decided that it is *legal* to vectorize the loop, then do it.
10556 
10557       // Consider vectorizing the epilogue too if it's profitable.
10558       VectorizationFactor EpilogueVF =
10559           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10560       if (EpilogueVF.Width.isVector()) {
10561 
10562         // The first pass vectorizes the main loop and creates a scalar epilogue
10563         // to be vectorized by executing the plan (potentially with a different
10564         // factor) again shortly afterwards.
10565         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10566         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10567                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10568 
10569         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10570         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10571                         DT);
10572         ++LoopsVectorized;
10573 
10574         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10575         formLCSSARecursively(*L, *DT, LI, SE);
10576 
10577         // Second pass vectorizes the epilogue and adjusts the control flow
10578         // edges from the first pass.
10579         EPI.MainLoopVF = EPI.EpilogueVF;
10580         EPI.MainLoopUF = EPI.EpilogueUF;
10581         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10582                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10583                                                  Checks);
10584 
10585         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10586 
10587         // Ensure that the start values for any VPReductionPHIRecipes are
10588         // updated before vectorising the epilogue loop.
10589         VPBasicBlock *Header =
10590             BestEpiPlan.getVectorLoopRegion()->getEntryBasicBlock();
10591         for (VPRecipeBase &R : Header->phis()) {
10592           if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10593             if (auto *Resume = MainILV.getReductionResumeValue(
10594                     ReductionPhi->getRecurrenceDescriptor())) {
10595               VPValue *StartVal = new VPValue(Resume);
10596               BestEpiPlan.addExternalDef(StartVal);
10597               ReductionPhi->setOperand(0, StartVal);
10598             }
10599           }
10600         }
10601 
10602         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10603                         DT);
10604         ++LoopsEpilogueVectorized;
10605 
10606         if (!MainILV.areSafetyChecksAdded())
10607           DisableRuntimeUnroll = true;
10608       } else {
10609         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10610                                &LVL, &CM, BFI, PSI, Checks);
10611 
10612         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10613         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10614         ++LoopsVectorized;
10615 
10616         // Add metadata to disable runtime unrolling a scalar loop when there
10617         // are no runtime checks about strides and memory. A scalar loop that is
10618         // rarely used is not worth unrolling.
10619         if (!LB.areSafetyChecksAdded())
10620           DisableRuntimeUnroll = true;
10621       }
10622       // Report the vectorization decision.
10623       ORE->emit([&]() {
10624         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10625                                   L->getHeader())
10626                << "vectorized loop (vectorization width: "
10627                << NV("VectorizationFactor", VF.Width)
10628                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10629       });
10630     }
10631 
10632     if (ORE->allowExtraAnalysis(LV_NAME))
10633       checkMixedPrecision(L, ORE);
10634   }
10635 
10636   Optional<MDNode *> RemainderLoopID =
10637       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10638                                       LLVMLoopVectorizeFollowupEpilogue});
10639   if (RemainderLoopID.hasValue()) {
10640     L->setLoopID(RemainderLoopID.getValue());
10641   } else {
10642     if (DisableRuntimeUnroll)
10643       AddRuntimeUnrollDisableMetaData(L);
10644 
10645     // Mark the loop as already vectorized to avoid vectorizing again.
10646     Hints.setAlreadyVectorized();
10647   }
10648 
10649   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10650   return true;
10651 }
10652 
10653 LoopVectorizeResult LoopVectorizePass::runImpl(
10654     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10655     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10656     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10657     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10658     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10659   SE = &SE_;
10660   LI = &LI_;
10661   TTI = &TTI_;
10662   DT = &DT_;
10663   BFI = &BFI_;
10664   TLI = TLI_;
10665   AA = &AA_;
10666   AC = &AC_;
10667   GetLAA = &GetLAA_;
10668   DB = &DB_;
10669   ORE = &ORE_;
10670   PSI = PSI_;
10671 
10672   // Don't attempt if
10673   // 1. the target claims to have no vector registers, and
10674   // 2. interleaving won't help ILP.
10675   //
10676   // The second condition is necessary because, even if the target has no
10677   // vector registers, loop vectorization may still enable scalar
10678   // interleaving.
10679   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10680       TTI->getMaxInterleaveFactor(1) < 2)
10681     return LoopVectorizeResult(false, false);
10682 
10683   bool Changed = false, CFGChanged = false;
10684 
10685   // The vectorizer requires loops to be in simplified form.
10686   // Since simplification may add new inner loops, it has to run before the
10687   // legality and profitability checks. This means running the loop vectorizer
10688   // will simplify all loops, regardless of whether anything end up being
10689   // vectorized.
10690   for (auto &L : *LI)
10691     Changed |= CFGChanged |=
10692         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10693 
10694   // Build up a worklist of inner-loops to vectorize. This is necessary as
10695   // the act of vectorizing or partially unrolling a loop creates new loops
10696   // and can invalidate iterators across the loops.
10697   SmallVector<Loop *, 8> Worklist;
10698 
10699   for (Loop *L : *LI)
10700     collectSupportedLoops(*L, LI, ORE, Worklist);
10701 
10702   LoopsAnalyzed += Worklist.size();
10703 
10704   // Now walk the identified inner loops.
10705   while (!Worklist.empty()) {
10706     Loop *L = Worklist.pop_back_val();
10707 
10708     // For the inner loops we actually process, form LCSSA to simplify the
10709     // transform.
10710     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10711 
10712     Changed |= CFGChanged |= processLoop(L);
10713   }
10714 
10715   // Process each loop nest in the function.
10716   return LoopVectorizeResult(Changed, CFGChanged);
10717 }
10718 
10719 PreservedAnalyses LoopVectorizePass::run(Function &F,
10720                                          FunctionAnalysisManager &AM) {
10721     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10722     auto &LI = AM.getResult<LoopAnalysis>(F);
10723     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10724     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10725     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10726     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10727     auto &AA = AM.getResult<AAManager>(F);
10728     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10729     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10730     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10731 
10732     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10733     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10734         [&](Loop &L) -> const LoopAccessInfo & {
10735       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10736                                         TLI, TTI, nullptr, nullptr, nullptr};
10737       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10738     };
10739     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10740     ProfileSummaryInfo *PSI =
10741         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10742     LoopVectorizeResult Result =
10743         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10744     if (!Result.MadeAnyChange)
10745       return PreservedAnalyses::all();
10746     PreservedAnalyses PA;
10747 
10748     // We currently do not preserve loopinfo/dominator analyses with outer loop
10749     // vectorization. Until this is addressed, mark these analyses as preserved
10750     // only for non-VPlan-native path.
10751     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10752     if (!EnableVPlanNativePath) {
10753       PA.preserve<LoopAnalysis>();
10754       PA.preserve<DominatorTreeAnalysis>();
10755     }
10756 
10757     if (Result.MadeCFGChange) {
10758       // Making CFG changes likely means a loop got vectorized. Indicate that
10759       // extra simplification passes should be run.
10760       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10761       // be run if runtime checks have been added.
10762       AM.getResult<ShouldRunExtraVectorPasses>(F);
10763       PA.preserve<ShouldRunExtraVectorPasses>();
10764     } else {
10765       PA.preserveSet<CFGAnalyses>();
10766     }
10767     return PA;
10768 }
10769 
10770 void LoopVectorizePass::printPipeline(
10771     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10772   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10773       OS, MapClassName2PassName);
10774 
10775   OS << "<";
10776   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10777   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10778   OS << ">";
10779 }
10780