1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10 // and generates target-independent LLVM-IR.
11 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12 // of instructions in order to estimate the profitability of vectorization.
13 //
14 // The loop vectorizer combines consecutive loop iterations into a single
15 // 'wide' iteration. After this transformation the index is incremented
16 // by the SIMD vector width, and not by one.
17 //
18 // This pass has three parts:
19 // 1. The main loop pass that drives the different parts.
20 // 2. LoopVectorizationLegality - A unit that checks for the legality
21 //    of the vectorization.
22 // 3. InnerLoopVectorizer - A unit that performs the actual
23 //    widening of instructions.
24 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
25 //    of vectorization. It decides on the optimal vector width, which
26 //    can be one, if vectorization is not profitable.
27 //
28 // There is a development effort going on to migrate loop vectorizer to the
29 // VPlan infrastructure and to introduce outer loop vectorization support (see
30 // docs/Proposal/VectorizationPlan.rst and
31 // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32 // purpose, we temporarily introduced the VPlan-native vectorization path: an
33 // alternative vectorization path that is natively implemented on top of the
34 // VPlan infrastructure. See EnableVPlanNativePath for enabling.
35 //
36 //===----------------------------------------------------------------------===//
37 //
38 // The reduction-variable vectorization is based on the paper:
39 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40 //
41 // Variable uniformity checks are inspired by:
42 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
43 //
44 // The interleaved access vectorization is based on the paper:
45 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
46 //  Data for SIMD
47 //
48 // Other ideas/concepts are from:
49 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50 //
51 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
52 //  Vectorizing Compilers.
53 //
54 //===----------------------------------------------------------------------===//
55 
56 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
57 #include "LoopVectorizationPlanner.h"
58 #include "VPRecipeBuilder.h"
59 #include "VPlan.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "VPlanPredicator.h"
62 #include "VPlanTransforms.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/ArrayRef.h"
65 #include "llvm/ADT/DenseMap.h"
66 #include "llvm/ADT/DenseMapInfo.h"
67 #include "llvm/ADT/Hashing.h"
68 #include "llvm/ADT/MapVector.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallPtrSet.h"
73 #include "llvm/ADT/SmallSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/Statistic.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Twine.h"
78 #include "llvm/ADT/iterator_range.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/BasicAliasAnalysis.h"
81 #include "llvm/Analysis/BlockFrequencyInfo.h"
82 #include "llvm/Analysis/CFG.h"
83 #include "llvm/Analysis/CodeMetrics.h"
84 #include "llvm/Analysis/DemandedBits.h"
85 #include "llvm/Analysis/GlobalsModRef.h"
86 #include "llvm/Analysis/LoopAccessAnalysis.h"
87 #include "llvm/Analysis/LoopAnalysisManager.h"
88 #include "llvm/Analysis/LoopInfo.h"
89 #include "llvm/Analysis/LoopIterator.h"
90 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
91 #include "llvm/Analysis/ProfileSummaryInfo.h"
92 #include "llvm/Analysis/ScalarEvolution.h"
93 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
94 #include "llvm/Analysis/TargetLibraryInfo.h"
95 #include "llvm/Analysis/TargetTransformInfo.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/LLVMContext.h"
116 #include "llvm/IR/Metadata.h"
117 #include "llvm/IR/Module.h"
118 #include "llvm/IR/Operator.h"
119 #include "llvm/IR/PatternMatch.h"
120 #include "llvm/IR/Type.h"
121 #include "llvm/IR/Use.h"
122 #include "llvm/IR/User.h"
123 #include "llvm/IR/Value.h"
124 #include "llvm/IR/ValueHandle.h"
125 #include "llvm/IR/Verifier.h"
126 #include "llvm/InitializePasses.h"
127 #include "llvm/Pass.h"
128 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/CommandLine.h"
130 #include "llvm/Support/Compiler.h"
131 #include "llvm/Support/Debug.h"
132 #include "llvm/Support/ErrorHandling.h"
133 #include "llvm/Support/InstructionCost.h"
134 #include "llvm/Support/MathExtras.h"
135 #include "llvm/Support/raw_ostream.h"
136 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
137 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
138 #include "llvm/Transforms/Utils/LoopSimplify.h"
139 #include "llvm/Transforms/Utils/LoopUtils.h"
140 #include "llvm/Transforms/Utils/LoopVersioning.h"
141 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
142 #include "llvm/Transforms/Utils/SizeOpts.h"
143 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
144 #include <algorithm>
145 #include <cassert>
146 #include <cstdint>
147 #include <cstdlib>
148 #include <functional>
149 #include <iterator>
150 #include <limits>
151 #include <memory>
152 #include <string>
153 #include <tuple>
154 #include <utility>
155 
156 using namespace llvm;
157 
158 #define LV_NAME "loop-vectorize"
159 #define DEBUG_TYPE LV_NAME
160 
161 #ifndef NDEBUG
162 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
163 #endif
164 
165 /// @{
166 /// Metadata attribute names
167 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
168 const char LLVMLoopVectorizeFollowupVectorized[] =
169     "llvm.loop.vectorize.followup_vectorized";
170 const char LLVMLoopVectorizeFollowupEpilogue[] =
171     "llvm.loop.vectorize.followup_epilogue";
172 /// @}
173 
174 STATISTIC(LoopsVectorized, "Number of loops vectorized");
175 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
176 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
177 
178 static cl::opt<bool> EnableEpilogueVectorization(
179     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180     cl::desc("Enable vectorization of epilogue loops."));
181 
182 static cl::opt<unsigned> EpilogueVectorizationForceVF(
183     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
184     cl::desc("When epilogue vectorization is enabled, and a value greater than "
185              "1 is specified, forces the given VF for all applicable epilogue "
186              "loops."));
187 
188 static cl::opt<unsigned> EpilogueVectorizationMinVF(
189     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
190     cl::desc("Only loops with vectorization factor equal to or larger than "
191              "the specified value are considered for epilogue vectorization."));
192 
193 /// Loops with a known constant trip count below this number are vectorized only
194 /// if no scalar iteration overheads are incurred.
195 static cl::opt<unsigned> TinyTripCountVectorThreshold(
196     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197     cl::desc("Loops with a constant trip count that is smaller than this "
198              "value are vectorized only if no scalar iteration overheads "
199              "are incurred."));
200 
201 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
202     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
203     cl::desc("The maximum allowed number of runtime memory checks with a "
204              "vectorize(enable) pragma."));
205 
206 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
207 // that predication is preferred, and this lists all options. I.e., the
208 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
209 // and predicate the instructions accordingly. If tail-folding fails, there are
210 // different fallback strategies depending on these values:
211 namespace PreferPredicateTy {
212   enum Option {
213     ScalarEpilogue = 0,
214     PredicateElseScalarEpilogue,
215     PredicateOrDontVectorize
216   };
217 } // namespace PreferPredicateTy
218 
219 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
220     "prefer-predicate-over-epilogue",
221     cl::init(PreferPredicateTy::ScalarEpilogue),
222     cl::Hidden,
223     cl::desc("Tail-folding and predication preferences over creating a scalar "
224              "epilogue loop."),
225     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
226                          "scalar-epilogue",
227                          "Don't tail-predicate loops, create scalar epilogue"),
228               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
229                          "predicate-else-scalar-epilogue",
230                          "prefer tail-folding, create scalar epilogue if tail "
231                          "folding fails."),
232               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
233                          "predicate-dont-vectorize",
234                          "prefers tail-folding, don't attempt vectorization if "
235                          "tail-folding fails.")));
236 
237 static cl::opt<bool> MaximizeBandwidth(
238     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
239     cl::desc("Maximize bandwidth when selecting vectorization factor which "
240              "will be determined by the smallest type in loop."));
241 
242 static cl::opt<bool> EnableInterleavedMemAccesses(
243     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
244     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
245 
246 /// An interleave-group may need masking if it resides in a block that needs
247 /// predication, or in order to mask away gaps.
248 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
249     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
250     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
251 
252 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
253     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
254     cl::desc("We don't interleave loops with a estimated constant trip count "
255              "below this number"));
256 
257 static cl::opt<unsigned> ForceTargetNumScalarRegs(
258     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
259     cl::desc("A flag that overrides the target's number of scalar registers."));
260 
261 static cl::opt<unsigned> ForceTargetNumVectorRegs(
262     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
263     cl::desc("A flag that overrides the target's number of vector registers."));
264 
265 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
266     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
267     cl::desc("A flag that overrides the target's max interleave factor for "
268              "scalar loops."));
269 
270 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
271     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
272     cl::desc("A flag that overrides the target's max interleave factor for "
273              "vectorized loops."));
274 
275 static cl::opt<unsigned> ForceTargetInstructionCost(
276     "force-target-instruction-cost", cl::init(0), cl::Hidden,
277     cl::desc("A flag that overrides the target's expected cost for "
278              "an instruction to a single constant value. Mostly "
279              "useful for getting consistent testing."));
280 
281 static cl::opt<bool> ForceTargetSupportsScalableVectors(
282     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
283     cl::desc(
284         "Pretend that scalable vectors are supported, even if the target does "
285         "not support them. This flag should only be used for testing."));
286 
287 static cl::opt<unsigned> SmallLoopCost(
288     "small-loop-cost", cl::init(20), cl::Hidden,
289     cl::desc(
290         "The cost of a loop that is considered 'small' by the interleaver."));
291 
292 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
293     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
294     cl::desc("Enable the use of the block frequency analysis to access PGO "
295              "heuristics minimizing code growth in cold regions and being more "
296              "aggressive in hot regions."));
297 
298 // Runtime interleave loops for load/store throughput.
299 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
300     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
301     cl::desc(
302         "Enable runtime interleaving until load/store ports are saturated"));
303 
304 /// Interleave small loops with scalar reductions.
305 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
306     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
307     cl::desc("Enable interleaving for loops with small iteration counts that "
308              "contain scalar reductions to expose ILP."));
309 
310 /// The number of stores in a loop that are allowed to need predication.
311 static cl::opt<unsigned> NumberOfStoresToPredicate(
312     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
313     cl::desc("Max number of stores to be predicated behind an if."));
314 
315 static cl::opt<bool> EnableIndVarRegisterHeur(
316     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
317     cl::desc("Count the induction variable only once when interleaving"));
318 
319 static cl::opt<bool> EnableCondStoresVectorization(
320     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
321     cl::desc("Enable if predication of stores during vectorization."));
322 
323 static cl::opt<unsigned> MaxNestedScalarReductionIC(
324     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
325     cl::desc("The maximum interleave count to use when interleaving a scalar "
326              "reduction in a nested loop."));
327 
328 static cl::opt<bool>
329     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
330                            cl::Hidden,
331                            cl::desc("Prefer in-loop vector reductions, "
332                                     "overriding the targets preference."));
333 
334 static cl::opt<bool> ForceOrderedReductions(
335     "force-ordered-reductions", cl::init(false), cl::Hidden,
336     cl::desc("Enable the vectorisation of loops with in-order (strict) "
337              "FP reductions"));
338 
339 static cl::opt<bool> PreferPredicatedReductionSelect(
340     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
341     cl::desc(
342         "Prefer predicating a reduction operation over an after loop select."));
343 
344 cl::opt<bool> EnableVPlanNativePath(
345     "enable-vplan-native-path", cl::init(false), cl::Hidden,
346     cl::desc("Enable VPlan-native vectorization path with "
347              "support for outer loop vectorization."));
348 
349 // FIXME: Remove this switch once we have divergence analysis. Currently we
350 // assume divergent non-backedge branches when this switch is true.
351 cl::opt<bool> EnableVPlanPredication(
352     "enable-vplan-predication", cl::init(false), cl::Hidden,
353     cl::desc("Enable VPlan-native vectorization path predicator with "
354              "support for outer loop vectorization."));
355 
356 // This flag enables the stress testing of the VPlan H-CFG construction in the
357 // VPlan-native vectorization path. It must be used in conjuction with
358 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
359 // verification of the H-CFGs built.
360 static cl::opt<bool> VPlanBuildStressTest(
361     "vplan-build-stress-test", cl::init(false), cl::Hidden,
362     cl::desc(
363         "Build VPlan for every supported loop nest in the function and bail "
364         "out right after the build (stress test the VPlan H-CFG construction "
365         "in the VPlan-native vectorization path)."));
366 
367 cl::opt<bool> llvm::EnableLoopInterleaving(
368     "interleave-loops", cl::init(true), cl::Hidden,
369     cl::desc("Enable loop interleaving in Loop vectorization passes"));
370 cl::opt<bool> llvm::EnableLoopVectorization(
371     "vectorize-loops", cl::init(true), cl::Hidden,
372     cl::desc("Run the Loop vectorization passes"));
373 
374 cl::opt<bool> PrintVPlansInDotFormat(
375     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
376     cl::desc("Use dot format instead of plain text when dumping VPlans"));
377 
378 /// A helper function that returns true if the given type is irregular. The
379 /// type is irregular if its allocated size doesn't equal the store size of an
380 /// element of the corresponding vector type.
381 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
382   // Determine if an array of N elements of type Ty is "bitcast compatible"
383   // with a <N x Ty> vector.
384   // This is only true if there is no padding between the array elements.
385   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
386 }
387 
388 /// A helper function that returns the reciprocal of the block probability of
389 /// predicated blocks. If we return X, we are assuming the predicated block
390 /// will execute once for every X iterations of the loop header.
391 ///
392 /// TODO: We should use actual block probability here, if available. Currently,
393 ///       we always assume predicated blocks have a 50% chance of executing.
394 static unsigned getReciprocalPredBlockProb() { return 2; }
395 
396 /// A helper function that returns an integer or floating-point constant with
397 /// value C.
398 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
399   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
400                            : ConstantFP::get(Ty, C);
401 }
402 
403 /// Returns "best known" trip count for the specified loop \p L as defined by
404 /// the following procedure:
405 ///   1) Returns exact trip count if it is known.
406 ///   2) Returns expected trip count according to profile data if any.
407 ///   3) Returns upper bound estimate if it is known.
408 ///   4) Returns None if all of the above failed.
409 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
410   // Check if exact trip count is known.
411   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
412     return ExpectedTC;
413 
414   // Check if there is an expected trip count available from profile data.
415   if (LoopVectorizeWithBlockFrequency)
416     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
417       return EstimatedTC;
418 
419   // Check if upper bound estimate is known.
420   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
421     return ExpectedTC;
422 
423   return None;
424 }
425 
426 // Forward declare GeneratedRTChecks.
427 class GeneratedRTChecks;
428 
429 namespace llvm {
430 
431 /// InnerLoopVectorizer vectorizes loops which contain only one basic
432 /// block to a specified vectorization factor (VF).
433 /// This class performs the widening of scalars into vectors, or multiple
434 /// scalars. This class also implements the following features:
435 /// * It inserts an epilogue loop for handling loops that don't have iteration
436 ///   counts that are known to be a multiple of the vectorization factor.
437 /// * It handles the code generation for reduction variables.
438 /// * Scalarization (implementation using scalars) of un-vectorizable
439 ///   instructions.
440 /// InnerLoopVectorizer does not perform any vectorization-legality
441 /// checks, and relies on the caller to check for the different legality
442 /// aspects. The InnerLoopVectorizer relies on the
443 /// LoopVectorizationLegality class to provide information about the induction
444 /// and reduction variables that were found to a given vectorization factor.
445 class InnerLoopVectorizer {
446 public:
447   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
448                       LoopInfo *LI, DominatorTree *DT,
449                       const TargetLibraryInfo *TLI,
450                       const TargetTransformInfo *TTI, AssumptionCache *AC,
451                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
452                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
453                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
454                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
455       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
456         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
457         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
458         PSI(PSI), RTChecks(RTChecks) {
459     // Query this against the original loop and save it here because the profile
460     // of the original loop header may change as the transformation happens.
461     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
462         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
463   }
464 
465   virtual ~InnerLoopVectorizer() = default;
466 
467   /// Create a new empty loop that will contain vectorized instructions later
468   /// on, while the old loop will be used as the scalar remainder. Control flow
469   /// is generated around the vectorized (and scalar epilogue) loops consisting
470   /// of various checks and bypasses. Return the pre-header block of the new
471   /// loop.
472   /// In the case of epilogue vectorization, this function is overriden to
473   /// handle the more complex control flow around the loops.
474   virtual BasicBlock *createVectorizedLoopSkeleton();
475 
476   /// Widen a single call instruction within the innermost loop.
477   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
478                             VPTransformState &State);
479 
480   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
481   void fixVectorizedLoop(VPTransformState &State);
482 
483   // Return true if any runtime check is added.
484   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
485 
486   /// A type for vectorized values in the new loop. Each value from the
487   /// original loop, when vectorized, is represented by UF vector values in the
488   /// new unrolled loop, where UF is the unroll factor.
489   using VectorParts = SmallVector<Value *, 2>;
490 
491   /// Vectorize a single first-order recurrence or pointer induction PHINode in
492   /// a block. This method handles the induction variable canonicalization. It
493   /// supports both VF = 1 for unrolled loops and arbitrary length vectors.
494   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
495                            VPTransformState &State);
496 
497   /// A helper function to scalarize a single Instruction in the innermost loop.
498   /// Generates a sequence of scalar instances for each lane between \p MinLane
499   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
500   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
501   /// Instr's operands.
502   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
503                             const VPIteration &Instance, bool IfPredicateInstr,
504                             VPTransformState &State);
505 
506   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
507   /// is provided, the integer induction variable will first be truncated to
508   /// the corresponding type.
509   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
510                              VPValue *Def, VPValue *CastDef,
511                              VPTransformState &State);
512 
513   /// Construct the vector value of a scalarized value \p V one lane at a time.
514   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
515                                  VPTransformState &State);
516 
517   /// Try to vectorize interleaved access group \p Group with the base address
518   /// given in \p Addr, optionally masking the vector operations if \p
519   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
520   /// values in the vectorized loop.
521   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
522                                 ArrayRef<VPValue *> VPDefs,
523                                 VPTransformState &State, VPValue *Addr,
524                                 ArrayRef<VPValue *> StoredValues,
525                                 VPValue *BlockInMask = nullptr);
526 
527   /// Set the debug location in the builder \p Ptr using the debug location in
528   /// \p V. If \p Ptr is None then it uses the class member's Builder.
529   void setDebugLocFromInst(const Value *V,
530                            Optional<IRBuilder<> *> CustomBuilder = None);
531 
532   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
533   void fixNonInductionPHIs(VPTransformState &State);
534 
535   /// Returns true if the reordering of FP operations is not allowed, but we are
536   /// able to vectorize with strict in-order reductions for the given RdxDesc.
537   bool useOrderedReductions(RecurrenceDescriptor &RdxDesc);
538 
539   /// Create a broadcast instruction. This method generates a broadcast
540   /// instruction (shuffle) for loop invariant values and for the induction
541   /// value. If this is the induction variable then we extend it to N, N+1, ...
542   /// this is needed because each iteration in the loop corresponds to a SIMD
543   /// element.
544   virtual Value *getBroadcastInstrs(Value *V);
545 
546   /// Add metadata from one instruction to another.
547   ///
548   /// This includes both the original MDs from \p From and additional ones (\see
549   /// addNewMetadata).  Use this for *newly created* instructions in the vector
550   /// loop.
551   void addMetadata(Instruction *To, Instruction *From);
552 
553   /// Similar to the previous function but it adds the metadata to a
554   /// vector of instructions.
555   void addMetadata(ArrayRef<Value *> To, Instruction *From);
556 
557 protected:
558   friend class LoopVectorizationPlanner;
559 
560   /// A small list of PHINodes.
561   using PhiVector = SmallVector<PHINode *, 4>;
562 
563   /// A type for scalarized values in the new loop. Each value from the
564   /// original loop, when scalarized, is represented by UF x VF scalar values
565   /// in the new unrolled loop, where UF is the unroll factor and VF is the
566   /// vectorization factor.
567   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
568 
569   /// Set up the values of the IVs correctly when exiting the vector loop.
570   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
571                     Value *CountRoundDown, Value *EndValue,
572                     BasicBlock *MiddleBlock);
573 
574   /// Create a new induction variable inside L.
575   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
576                                    Value *Step, Instruction *DL);
577 
578   /// Handle all cross-iteration phis in the header.
579   void fixCrossIterationPHIs(VPTransformState &State);
580 
581   /// Create the exit value of first order recurrences in the middle block and
582   /// update their users.
583   void fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR, 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   /// This function adds
608   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
609   /// to each vector element of Val. The sequence starts at StartIndex.
610   /// \p Opcode is relevant for FP induction variable.
611   virtual Value *
612   getStepVector(Value *Val, Value *StartIdx, Value *Step,
613                 Instruction::BinaryOps Opcode = Instruction::BinaryOpsEnd);
614 
615   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
616   /// variable on which to base the steps, \p Step is the size of the step, and
617   /// \p EntryVal is the value from the original loop that maps to the steps.
618   /// Note that \p EntryVal doesn't have to be an induction variable - it
619   /// can also be a truncate instruction.
620   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
621                         const InductionDescriptor &ID, VPValue *Def,
622                         VPValue *CastDef, VPTransformState &State);
623 
624   /// Create a vector induction phi node based on an existing scalar one. \p
625   /// EntryVal is the value from the original loop that maps to the vector phi
626   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
627   /// truncate instruction, instead of widening the original IV, we widen a
628   /// version of the IV truncated to \p EntryVal's type.
629   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
630                                        Value *Step, Value *Start,
631                                        Instruction *EntryVal, VPValue *Def,
632                                        VPValue *CastDef,
633                                        VPTransformState &State);
634 
635   /// Returns true if an instruction \p I should be scalarized instead of
636   /// vectorized for the chosen vectorization factor.
637   bool shouldScalarizeInstruction(Instruction *I) const;
638 
639   /// Returns true if we should generate a scalar version of \p IV.
640   bool needsScalarInduction(Instruction *IV) const;
641 
642   /// If there is a cast involved in the induction variable \p ID, which should
643   /// be ignored in the vectorized loop body, this function records the
644   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
645   /// cast. We had already proved that the casted Phi is equal to the uncasted
646   /// Phi in the vectorized loop (under a runtime guard), and therefore
647   /// there is no need to vectorize the cast - the same value can be used in the
648   /// vector loop for both the Phi and the cast.
649   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
650   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
651   ///
652   /// \p EntryVal is the value from the original loop that maps to the vector
653   /// phi node and is used to distinguish what is the IV currently being
654   /// processed - original one (if \p EntryVal is a phi corresponding to the
655   /// original IV) or the "newly-created" one based on the proof mentioned above
656   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
657   /// latter case \p EntryVal is a TruncInst and we must not record anything for
658   /// that IV, but it's error-prone to expect callers of this routine to care
659   /// about that, hence this explicit parameter.
660   void recordVectorLoopValueForInductionCast(
661       const InductionDescriptor &ID, const Instruction *EntryVal,
662       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
663       unsigned Part, unsigned Lane = UINT_MAX);
664 
665   /// Generate a shuffle sequence that will reverse the vector Vec.
666   virtual Value *reverseVector(Value *Vec);
667 
668   /// Returns (and creates if needed) the original loop trip count.
669   Value *getOrCreateTripCount(Loop *NewLoop);
670 
671   /// Returns (and creates if needed) the trip count of the widened loop.
672   Value *getOrCreateVectorTripCount(Loop *NewLoop);
673 
674   /// Returns a bitcasted value to the requested vector type.
675   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
676   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
677                                 const DataLayout &DL);
678 
679   /// Emit a bypass check to see if the vector trip count is zero, including if
680   /// it overflows.
681   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
682 
683   /// Emit a bypass check to see if all of the SCEV assumptions we've
684   /// had to make are correct. Returns the block containing the checks or
685   /// nullptr if no checks have been added.
686   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
687 
688   /// Emit bypass checks to check any memory assumptions we may have made.
689   /// Returns the block containing the checks or nullptr if no checks have been
690   /// added.
691   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
692 
693   /// Compute the transformed value of Index at offset StartValue using step
694   /// StepValue.
695   /// For integer induction, returns StartValue + Index * StepValue.
696   /// For pointer induction, returns StartValue[Index * StepValue].
697   /// FIXME: The newly created binary instructions should contain nsw/nuw
698   /// flags, which can be found from the original scalar operations.
699   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
700                               const DataLayout &DL,
701                               const InductionDescriptor &ID) const;
702 
703   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
704   /// vector loop preheader, middle block and scalar preheader. Also
705   /// allocate a loop object for the new vector loop and return it.
706   Loop *createVectorLoopSkeleton(StringRef Prefix);
707 
708   /// Create new phi nodes for the induction variables to resume iteration count
709   /// in the scalar epilogue, from where the vectorized loop left off (given by
710   /// \p VectorTripCount).
711   /// In cases where the loop skeleton is more complicated (eg. epilogue
712   /// vectorization) and the resume values can come from an additional bypass
713   /// block, the \p AdditionalBypass pair provides information about the bypass
714   /// block and the end value on the edge from bypass to this loop.
715   void createInductionResumeValues(
716       Loop *L, Value *VectorTripCount,
717       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
718 
719   /// Complete the loop skeleton by adding debug MDs, creating appropriate
720   /// conditional branches in the middle block, preparing the builder and
721   /// running the verifier. Take in the vector loop \p L as argument, and return
722   /// the preheader of the completed vector loop.
723   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
724 
725   /// Add additional metadata to \p To that was not present on \p Orig.
726   ///
727   /// Currently this is used to add the noalias annotations based on the
728   /// inserted memchecks.  Use this for instructions that are *cloned* into the
729   /// vector loop.
730   void addNewMetadata(Instruction *To, const Instruction *Orig);
731 
732   /// Collect poison-generating recipes that may generate a poison value that is
733   /// used after vectorization, even when their operands are not poison. Those
734   /// recipes meet the following conditions:
735   ///  * Contribute to the address computation of a recipe generating a widen
736   ///    memory load/store (VPWidenMemoryInstructionRecipe or
737   ///    VPInterleaveRecipe).
738   ///  * Such a widen memory load/store has at least one underlying Instruction
739   ///    that is in a basic block that needs predication and after vectorization
740   ///    the generated instruction won't be predicated.
741   void collectPoisonGeneratingRecipes(VPTransformState &State);
742 
743   /// Allow subclasses to override and print debug traces before/after vplan
744   /// execution, when trace information is requested.
745   virtual void printDebugTracesAtStart(){};
746   virtual void printDebugTracesAtEnd(){};
747 
748   /// The original loop.
749   Loop *OrigLoop;
750 
751   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
752   /// dynamic knowledge to simplify SCEV expressions and converts them to a
753   /// more usable form.
754   PredicatedScalarEvolution &PSE;
755 
756   /// Loop Info.
757   LoopInfo *LI;
758 
759   /// Dominator Tree.
760   DominatorTree *DT;
761 
762   /// Alias Analysis.
763   AAResults *AA;
764 
765   /// Target Library Info.
766   const TargetLibraryInfo *TLI;
767 
768   /// Target Transform Info.
769   const TargetTransformInfo *TTI;
770 
771   /// Assumption Cache.
772   AssumptionCache *AC;
773 
774   /// Interface to emit optimization remarks.
775   OptimizationRemarkEmitter *ORE;
776 
777   /// LoopVersioning.  It's only set up (non-null) if memchecks were
778   /// used.
779   ///
780   /// This is currently only used to add no-alias metadata based on the
781   /// memchecks.  The actually versioning is performed manually.
782   std::unique_ptr<LoopVersioning> LVer;
783 
784   /// The vectorization SIMD factor to use. Each vector will have this many
785   /// vector elements.
786   ElementCount VF;
787 
788   /// The vectorization unroll factor to use. Each scalar is vectorized to this
789   /// many different vector instructions.
790   unsigned UF;
791 
792   /// The builder that we use
793   IRBuilder<> Builder;
794 
795   // --- Vectorization state ---
796 
797   /// The vector-loop preheader.
798   BasicBlock *LoopVectorPreHeader;
799 
800   /// The scalar-loop preheader.
801   BasicBlock *LoopScalarPreHeader;
802 
803   /// Middle Block between the vector and the scalar.
804   BasicBlock *LoopMiddleBlock;
805 
806   /// The unique ExitBlock of the scalar loop if one exists.  Note that
807   /// there can be multiple exiting edges reaching this block.
808   BasicBlock *LoopExitBlock;
809 
810   /// The vector loop body.
811   BasicBlock *LoopVectorBody;
812 
813   /// The scalar loop body.
814   BasicBlock *LoopScalarBody;
815 
816   /// A list of all bypass blocks. The first block is the entry of the loop.
817   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
818 
819   /// The new Induction variable which was added to the new block.
820   PHINode *Induction = nullptr;
821 
822   /// The induction variable of the old basic block.
823   PHINode *OldInduction = nullptr;
824 
825   /// Store instructions that were predicated.
826   SmallVector<Instruction *, 4> PredicatedInstructions;
827 
828   /// Trip count of the original loop.
829   Value *TripCount = nullptr;
830 
831   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
832   Value *VectorTripCount = nullptr;
833 
834   /// The legality analysis.
835   LoopVectorizationLegality *Legal;
836 
837   /// The profitablity analysis.
838   LoopVectorizationCostModel *Cost;
839 
840   // Record whether runtime checks are added.
841   bool AddedSafetyChecks = false;
842 
843   // Holds the end values for each induction variable. We save the end values
844   // so we can later fix-up the external users of the induction variables.
845   DenseMap<PHINode *, Value *> IVEndValues;
846 
847   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
848   // fixed up at the end of vector code generation.
849   SmallVector<PHINode *, 8> OrigPHIsToFix;
850 
851   /// BFI and PSI are used to check for profile guided size optimizations.
852   BlockFrequencyInfo *BFI;
853   ProfileSummaryInfo *PSI;
854 
855   // Whether this loop should be optimized for size based on profile guided size
856   // optimizatios.
857   bool OptForSizeBasedOnProfile;
858 
859   /// Structure to hold information about generated runtime checks, responsible
860   /// for cleaning the checks, if vectorization turns out unprofitable.
861   GeneratedRTChecks &RTChecks;
862 };
863 
864 class InnerLoopUnroller : public InnerLoopVectorizer {
865 public:
866   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
867                     LoopInfo *LI, DominatorTree *DT,
868                     const TargetLibraryInfo *TLI,
869                     const TargetTransformInfo *TTI, AssumptionCache *AC,
870                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
871                     LoopVectorizationLegality *LVL,
872                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
873                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
874       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
875                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
876                             BFI, PSI, Check) {}
877 
878 private:
879   Value *getBroadcastInstrs(Value *V) override;
880   Value *getStepVector(
881       Value *Val, Value *StartIdx, Value *Step,
882       Instruction::BinaryOps Opcode = Instruction::BinaryOpsEnd) override;
883   Value *reverseVector(Value *Vec) override;
884 };
885 
886 /// Encapsulate information regarding vectorization of a loop and its epilogue.
887 /// This information is meant to be updated and used across two stages of
888 /// epilogue vectorization.
889 struct EpilogueLoopVectorizationInfo {
890   ElementCount MainLoopVF = ElementCount::getFixed(0);
891   unsigned MainLoopUF = 0;
892   ElementCount EpilogueVF = ElementCount::getFixed(0);
893   unsigned EpilogueUF = 0;
894   BasicBlock *MainLoopIterationCountCheck = nullptr;
895   BasicBlock *EpilogueIterationCountCheck = nullptr;
896   BasicBlock *SCEVSafetyCheck = nullptr;
897   BasicBlock *MemSafetyCheck = nullptr;
898   Value *TripCount = nullptr;
899   Value *VectorTripCount = nullptr;
900 
901   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
902                                 ElementCount EVF, unsigned EUF)
903       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
904     assert(EUF == 1 &&
905            "A high UF for the epilogue loop is likely not beneficial.");
906   }
907 };
908 
909 /// An extension of the inner loop vectorizer that creates a skeleton for a
910 /// vectorized loop that has its epilogue (residual) also vectorized.
911 /// The idea is to run the vplan on a given loop twice, firstly to setup the
912 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
913 /// from the first step and vectorize the epilogue.  This is achieved by
914 /// deriving two concrete strategy classes from this base class and invoking
915 /// them in succession from the loop vectorizer planner.
916 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
917 public:
918   InnerLoopAndEpilogueVectorizer(
919       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
920       DominatorTree *DT, const TargetLibraryInfo *TLI,
921       const TargetTransformInfo *TTI, AssumptionCache *AC,
922       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
923       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
924       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
925       GeneratedRTChecks &Checks)
926       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
927                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
928                             Checks),
929         EPI(EPI) {}
930 
931   // Override this function to handle the more complex control flow around the
932   // three loops.
933   BasicBlock *createVectorizedLoopSkeleton() final override {
934     return createEpilogueVectorizedLoopSkeleton();
935   }
936 
937   /// The interface for creating a vectorized skeleton using one of two
938   /// different strategies, each corresponding to one execution of the vplan
939   /// as described above.
940   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
941 
942   /// Holds and updates state information required to vectorize the main loop
943   /// and its epilogue in two separate passes. This setup helps us avoid
944   /// regenerating and recomputing runtime safety checks. It also helps us to
945   /// shorten the iteration-count-check path length for the cases where the
946   /// iteration count of the loop is so small that the main vector loop is
947   /// completely skipped.
948   EpilogueLoopVectorizationInfo &EPI;
949 };
950 
951 /// A specialized derived class of inner loop vectorizer that performs
952 /// vectorization of *main* loops in the process of vectorizing loops and their
953 /// epilogues.
954 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
955 public:
956   EpilogueVectorizerMainLoop(
957       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
958       DominatorTree *DT, const TargetLibraryInfo *TLI,
959       const TargetTransformInfo *TTI, AssumptionCache *AC,
960       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
961       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
962       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
963       GeneratedRTChecks &Check)
964       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
965                                        EPI, LVL, CM, BFI, PSI, Check) {}
966   /// Implements the interface for creating a vectorized skeleton using the
967   /// *main loop* strategy (ie the first pass of vplan execution).
968   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
969 
970 protected:
971   /// Emits an iteration count bypass check once for the main loop (when \p
972   /// ForEpilogue is false) and once for the epilogue loop (when \p
973   /// ForEpilogue is true).
974   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
975                                              bool ForEpilogue);
976   void printDebugTracesAtStart() override;
977   void printDebugTracesAtEnd() override;
978 };
979 
980 // A specialized derived class of inner loop vectorizer that performs
981 // vectorization of *epilogue* loops in the process of vectorizing loops and
982 // their epilogues.
983 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
984 public:
985   EpilogueVectorizerEpilogueLoop(
986       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
987       DominatorTree *DT, const TargetLibraryInfo *TLI,
988       const TargetTransformInfo *TTI, AssumptionCache *AC,
989       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
990       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
991       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
992       GeneratedRTChecks &Checks)
993       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
994                                        EPI, LVL, CM, BFI, PSI, Checks) {}
995   /// Implements the interface for creating a vectorized skeleton using the
996   /// *epilogue loop* strategy (ie the second pass of vplan execution).
997   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
998 
999 protected:
1000   /// Emits an iteration count bypass check after the main vector loop has
1001   /// finished to see if there are any iterations left to execute by either
1002   /// the vector epilogue or the scalar epilogue.
1003   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1004                                                       BasicBlock *Bypass,
1005                                                       BasicBlock *Insert);
1006   void printDebugTracesAtStart() override;
1007   void printDebugTracesAtEnd() override;
1008 };
1009 } // end namespace llvm
1010 
1011 /// Look for a meaningful debug location on the instruction or it's
1012 /// operands.
1013 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1014   if (!I)
1015     return I;
1016 
1017   DebugLoc Empty;
1018   if (I->getDebugLoc() != Empty)
1019     return I;
1020 
1021   for (Use &Op : I->operands()) {
1022     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1023       if (OpInst->getDebugLoc() != Empty)
1024         return OpInst;
1025   }
1026 
1027   return I;
1028 }
1029 
1030 void InnerLoopVectorizer::setDebugLocFromInst(
1031     const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
1032   IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
1033   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
1034     const DILocation *DIL = Inst->getDebugLoc();
1035 
1036     // When a FSDiscriminator is enabled, we don't need to add the multiply
1037     // factors to the discriminators.
1038     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1039         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1040       // FIXME: For scalable vectors, assume vscale=1.
1041       auto NewDIL =
1042           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1043       if (NewDIL)
1044         B->SetCurrentDebugLocation(NewDIL.getValue());
1045       else
1046         LLVM_DEBUG(dbgs()
1047                    << "Failed to create new discriminator: "
1048                    << DIL->getFilename() << " Line: " << DIL->getLine());
1049     } else
1050       B->SetCurrentDebugLocation(DIL);
1051   } else
1052     B->SetCurrentDebugLocation(DebugLoc());
1053 }
1054 
1055 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1056 /// is passed, the message relates to that particular instruction.
1057 #ifndef NDEBUG
1058 static void debugVectorizationMessage(const StringRef Prefix,
1059                                       const StringRef DebugMsg,
1060                                       Instruction *I) {
1061   dbgs() << "LV: " << Prefix << DebugMsg;
1062   if (I != nullptr)
1063     dbgs() << " " << *I;
1064   else
1065     dbgs() << '.';
1066   dbgs() << '\n';
1067 }
1068 #endif
1069 
1070 /// Create an analysis remark that explains why vectorization failed
1071 ///
1072 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1073 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1074 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1075 /// the location of the remark.  \return the remark object that can be
1076 /// streamed to.
1077 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1078     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1079   Value *CodeRegion = TheLoop->getHeader();
1080   DebugLoc DL = TheLoop->getStartLoc();
1081 
1082   if (I) {
1083     CodeRegion = I->getParent();
1084     // If there is no debug location attached to the instruction, revert back to
1085     // using the loop's.
1086     if (I->getDebugLoc())
1087       DL = I->getDebugLoc();
1088   }
1089 
1090   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1091 }
1092 
1093 /// Return a value for Step multiplied by VF.
1094 static Value *createStepForVF(IRBuilder<> &B, Type *Ty, ElementCount VF,
1095                               int64_t Step) {
1096   assert(Ty->isIntegerTy() && "Expected an integer step");
1097   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
1098   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1099 }
1100 
1101 namespace llvm {
1102 
1103 /// Return the runtime value for VF.
1104 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1105   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1106   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1107 }
1108 
1109 static Value *getRuntimeVFAsFloat(IRBuilder<> &B, Type *FTy, ElementCount VF) {
1110   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1111   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1112   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1113   return B.CreateUIToFP(RuntimeVF, FTy);
1114 }
1115 
1116 void reportVectorizationFailure(const StringRef DebugMsg,
1117                                 const StringRef OREMsg, const StringRef ORETag,
1118                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1119                                 Instruction *I) {
1120   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1121   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1122   ORE->emit(
1123       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1124       << "loop not vectorized: " << OREMsg);
1125 }
1126 
1127 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1128                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1129                              Instruction *I) {
1130   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1131   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1132   ORE->emit(
1133       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1134       << Msg);
1135 }
1136 
1137 } // end namespace llvm
1138 
1139 #ifndef NDEBUG
1140 /// \return string containing a file name and a line # for the given loop.
1141 static std::string getDebugLocString(const Loop *L) {
1142   std::string Result;
1143   if (L) {
1144     raw_string_ostream OS(Result);
1145     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1146       LoopDbgLoc.print(OS);
1147     else
1148       // Just print the module name.
1149       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1150     OS.flush();
1151   }
1152   return Result;
1153 }
1154 #endif
1155 
1156 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1157                                          const Instruction *Orig) {
1158   // If the loop was versioned with memchecks, add the corresponding no-alias
1159   // metadata.
1160   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1161     LVer->annotateInstWithNoAlias(To, Orig);
1162 }
1163 
1164 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1165     VPTransformState &State) {
1166 
1167   // Collect recipes in the backward slice of `Root` that may generate a poison
1168   // value that is used after vectorization.
1169   SmallPtrSet<VPRecipeBase *, 16> Visited;
1170   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1171     SmallVector<VPRecipeBase *, 16> Worklist;
1172     Worklist.push_back(Root);
1173 
1174     // Traverse the backward slice of Root through its use-def chain.
1175     while (!Worklist.empty()) {
1176       VPRecipeBase *CurRec = Worklist.back();
1177       Worklist.pop_back();
1178 
1179       if (!Visited.insert(CurRec).second)
1180         continue;
1181 
1182       // Prune search if we find another recipe generating a widen memory
1183       // instruction. Widen memory instructions involved in address computation
1184       // will lead to gather/scatter instructions, which don't need to be
1185       // handled.
1186       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1187           isa<VPInterleaveRecipe>(CurRec))
1188         continue;
1189 
1190       // This recipe contributes to the address computation of a widen
1191       // load/store. Collect recipe if its underlying instruction has
1192       // poison-generating flags.
1193       Instruction *Instr = CurRec->getUnderlyingInstr();
1194       if (Instr && Instr->hasPoisonGeneratingFlags())
1195         State.MayGeneratePoisonRecipes.insert(CurRec);
1196 
1197       // Add new definitions to the worklist.
1198       for (VPValue *operand : CurRec->operands())
1199         if (VPDef *OpDef = operand->getDef())
1200           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1201     }
1202   });
1203 
1204   // Traverse all the recipes in the VPlan and collect the poison-generating
1205   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1206   // VPInterleaveRecipe.
1207   auto Iter = depth_first(
1208       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1209   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1210     for (VPRecipeBase &Recipe : *VPBB) {
1211       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1212         Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
1213         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1214         if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
1215             Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
1216           collectPoisonGeneratingInstrsInBackwardSlice(
1217               cast<VPRecipeBase>(AddrDef));
1218       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1219         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1220         if (AddrDef) {
1221           // Check if any member of the interleave group needs predication.
1222           const InterleaveGroup<Instruction> *InterGroup =
1223               InterleaveRec->getInterleaveGroup();
1224           bool NeedPredication = false;
1225           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1226                I < NumMembers; ++I) {
1227             Instruction *Member = InterGroup->getMember(I);
1228             if (Member)
1229               NeedPredication |=
1230                   Legal->blockNeedsPredication(Member->getParent());
1231           }
1232 
1233           if (NeedPredication)
1234             collectPoisonGeneratingInstrsInBackwardSlice(
1235                 cast<VPRecipeBase>(AddrDef));
1236         }
1237       }
1238     }
1239   }
1240 }
1241 
1242 void InnerLoopVectorizer::addMetadata(Instruction *To,
1243                                       Instruction *From) {
1244   propagateMetadata(To, From);
1245   addNewMetadata(To, From);
1246 }
1247 
1248 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1249                                       Instruction *From) {
1250   for (Value *V : To) {
1251     if (Instruction *I = dyn_cast<Instruction>(V))
1252       addMetadata(I, From);
1253   }
1254 }
1255 
1256 namespace llvm {
1257 
1258 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1259 // lowered.
1260 enum ScalarEpilogueLowering {
1261 
1262   // The default: allowing scalar epilogues.
1263   CM_ScalarEpilogueAllowed,
1264 
1265   // Vectorization with OptForSize: don't allow epilogues.
1266   CM_ScalarEpilogueNotAllowedOptSize,
1267 
1268   // A special case of vectorisation with OptForSize: loops with a very small
1269   // trip count are considered for vectorization under OptForSize, thereby
1270   // making sure the cost of their loop body is dominant, free of runtime
1271   // guards and scalar iteration overheads.
1272   CM_ScalarEpilogueNotAllowedLowTripLoop,
1273 
1274   // Loop hint predicate indicating an epilogue is undesired.
1275   CM_ScalarEpilogueNotNeededUsePredicate,
1276 
1277   // Directive indicating we must either tail fold or not vectorize
1278   CM_ScalarEpilogueNotAllowedUsePredicate
1279 };
1280 
1281 /// ElementCountComparator creates a total ordering for ElementCount
1282 /// for the purposes of using it in a set structure.
1283 struct ElementCountComparator {
1284   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1285     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1286            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1287   }
1288 };
1289 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1290 
1291 /// LoopVectorizationCostModel - estimates the expected speedups due to
1292 /// vectorization.
1293 /// In many cases vectorization is not profitable. This can happen because of
1294 /// a number of reasons. In this class we mainly attempt to predict the
1295 /// expected speedup/slowdowns due to the supported instruction set. We use the
1296 /// TargetTransformInfo to query the different backends for the cost of
1297 /// different operations.
1298 class LoopVectorizationCostModel {
1299 public:
1300   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1301                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1302                              LoopVectorizationLegality *Legal,
1303                              const TargetTransformInfo &TTI,
1304                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1305                              AssumptionCache *AC,
1306                              OptimizationRemarkEmitter *ORE, const Function *F,
1307                              const LoopVectorizeHints *Hints,
1308                              InterleavedAccessInfo &IAI)
1309       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1310         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1311         Hints(Hints), InterleaveInfo(IAI) {}
1312 
1313   /// \return An upper bound for the vectorization factors (both fixed and
1314   /// scalable). If the factors are 0, vectorization and interleaving should be
1315   /// avoided up front.
1316   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1317 
1318   /// \return True if runtime checks are required for vectorization, and false
1319   /// otherwise.
1320   bool runtimeChecksRequired();
1321 
1322   /// \return The most profitable vectorization factor and the cost of that VF.
1323   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1324   /// then this vectorization factor will be selected if vectorization is
1325   /// possible.
1326   VectorizationFactor
1327   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1328 
1329   VectorizationFactor
1330   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1331                                     const LoopVectorizationPlanner &LVP);
1332 
1333   /// Setup cost-based decisions for user vectorization factor.
1334   /// \return true if the UserVF is a feasible VF to be chosen.
1335   bool selectUserVectorizationFactor(ElementCount UserVF) {
1336     collectUniformsAndScalars(UserVF);
1337     collectInstsToScalarize(UserVF);
1338     return expectedCost(UserVF).first.isValid();
1339   }
1340 
1341   /// \return The size (in bits) of the smallest and widest types in the code
1342   /// that needs to be vectorized. We ignore values that remain scalar such as
1343   /// 64 bit loop indices.
1344   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1345 
1346   /// \return The desired interleave count.
1347   /// If interleave count has been specified by metadata it will be returned.
1348   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1349   /// are the selected vectorization factor and the cost of the selected VF.
1350   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1351 
1352   /// Memory access instruction may be vectorized in more than one way.
1353   /// Form of instruction after vectorization depends on cost.
1354   /// This function takes cost-based decisions for Load/Store instructions
1355   /// and collects them in a map. This decisions map is used for building
1356   /// the lists of loop-uniform and loop-scalar instructions.
1357   /// The calculated cost is saved with widening decision in order to
1358   /// avoid redundant calculations.
1359   void setCostBasedWideningDecision(ElementCount VF);
1360 
1361   /// A struct that represents some properties of the register usage
1362   /// of a loop.
1363   struct RegisterUsage {
1364     /// Holds the number of loop invariant values that are used in the loop.
1365     /// The key is ClassID of target-provided register class.
1366     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1367     /// Holds the maximum number of concurrent live intervals in the loop.
1368     /// The key is ClassID of target-provided register class.
1369     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1370   };
1371 
1372   /// \return Returns information about the register usages of the loop for the
1373   /// given vectorization factors.
1374   SmallVector<RegisterUsage, 8>
1375   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1376 
1377   /// Collect values we want to ignore in the cost model.
1378   void collectValuesToIgnore();
1379 
1380   /// Collect all element types in the loop for which widening is needed.
1381   void collectElementTypesForWidening();
1382 
1383   /// Split reductions into those that happen in the loop, and those that happen
1384   /// outside. In loop reductions are collected into InLoopReductionChains.
1385   void collectInLoopReductions();
1386 
1387   /// Returns true if we should use strict in-order reductions for the given
1388   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1389   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1390   /// of FP operations.
1391   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1392     return !Hints->allowReordering() && RdxDesc.isOrdered();
1393   }
1394 
1395   /// \returns The smallest bitwidth each instruction can be represented with.
1396   /// The vector equivalents of these instructions should be truncated to this
1397   /// type.
1398   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1399     return MinBWs;
1400   }
1401 
1402   /// \returns True if it is more profitable to scalarize instruction \p I for
1403   /// vectorization factor \p VF.
1404   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1405     assert(VF.isVector() &&
1406            "Profitable to scalarize relevant only for VF > 1.");
1407 
1408     // Cost model is not run in the VPlan-native path - return conservative
1409     // result until this changes.
1410     if (EnableVPlanNativePath)
1411       return false;
1412 
1413     auto Scalars = InstsToScalarize.find(VF);
1414     assert(Scalars != InstsToScalarize.end() &&
1415            "VF not yet analyzed for scalarization profitability");
1416     return Scalars->second.find(I) != Scalars->second.end();
1417   }
1418 
1419   /// Returns true if \p I is known to be uniform after vectorization.
1420   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1421     if (VF.isScalar())
1422       return true;
1423 
1424     // Cost model is not run in the VPlan-native path - return conservative
1425     // result until this changes.
1426     if (EnableVPlanNativePath)
1427       return false;
1428 
1429     auto UniformsPerVF = Uniforms.find(VF);
1430     assert(UniformsPerVF != Uniforms.end() &&
1431            "VF not yet analyzed for uniformity");
1432     return UniformsPerVF->second.count(I);
1433   }
1434 
1435   /// Returns true if \p I is known to be scalar after vectorization.
1436   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1437     if (VF.isScalar())
1438       return true;
1439 
1440     // Cost model is not run in the VPlan-native path - return conservative
1441     // result until this changes.
1442     if (EnableVPlanNativePath)
1443       return false;
1444 
1445     auto ScalarsPerVF = Scalars.find(VF);
1446     assert(ScalarsPerVF != Scalars.end() &&
1447            "Scalar values are not calculated for VF");
1448     return ScalarsPerVF->second.count(I);
1449   }
1450 
1451   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1452   /// for vectorization factor \p VF.
1453   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1454     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1455            !isProfitableToScalarize(I, VF) &&
1456            !isScalarAfterVectorization(I, VF);
1457   }
1458 
1459   /// Decision that was taken during cost calculation for memory instruction.
1460   enum InstWidening {
1461     CM_Unknown,
1462     CM_Widen,         // For consecutive accesses with stride +1.
1463     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1464     CM_Interleave,
1465     CM_GatherScatter,
1466     CM_Scalarize
1467   };
1468 
1469   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1470   /// instruction \p I and vector width \p VF.
1471   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1472                            InstructionCost Cost) {
1473     assert(VF.isVector() && "Expected VF >=2");
1474     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1475   }
1476 
1477   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1478   /// interleaving group \p Grp and vector width \p VF.
1479   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1480                            ElementCount VF, InstWidening W,
1481                            InstructionCost Cost) {
1482     assert(VF.isVector() && "Expected VF >=2");
1483     /// Broadcast this decicion to all instructions inside the group.
1484     /// But the cost will be assigned to one instruction only.
1485     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1486       if (auto *I = Grp->getMember(i)) {
1487         if (Grp->getInsertPos() == I)
1488           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1489         else
1490           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1491       }
1492     }
1493   }
1494 
1495   /// Return the cost model decision for the given instruction \p I and vector
1496   /// width \p VF. Return CM_Unknown if this instruction did not pass
1497   /// through the cost modeling.
1498   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1499     assert(VF.isVector() && "Expected VF to be a vector VF");
1500     // Cost model is not run in the VPlan-native path - return conservative
1501     // result until this changes.
1502     if (EnableVPlanNativePath)
1503       return CM_GatherScatter;
1504 
1505     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1506     auto Itr = WideningDecisions.find(InstOnVF);
1507     if (Itr == WideningDecisions.end())
1508       return CM_Unknown;
1509     return Itr->second.first;
1510   }
1511 
1512   /// Return the vectorization cost for the given instruction \p I and vector
1513   /// width \p VF.
1514   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1515     assert(VF.isVector() && "Expected VF >=2");
1516     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1517     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1518            "The cost is not calculated");
1519     return WideningDecisions[InstOnVF].second;
1520   }
1521 
1522   /// Return True if instruction \p I is an optimizable truncate whose operand
1523   /// is an induction variable. Such a truncate will be removed by adding a new
1524   /// induction variable with the destination type.
1525   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1526     // If the instruction is not a truncate, return false.
1527     auto *Trunc = dyn_cast<TruncInst>(I);
1528     if (!Trunc)
1529       return false;
1530 
1531     // Get the source and destination types of the truncate.
1532     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1533     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1534 
1535     // If the truncate is free for the given types, return false. Replacing a
1536     // free truncate with an induction variable would add an induction variable
1537     // update instruction to each iteration of the loop. We exclude from this
1538     // check the primary induction variable since it will need an update
1539     // instruction regardless.
1540     Value *Op = Trunc->getOperand(0);
1541     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1542       return false;
1543 
1544     // If the truncated value is not an induction variable, return false.
1545     return Legal->isInductionPhi(Op);
1546   }
1547 
1548   /// Collects the instructions to scalarize for each predicated instruction in
1549   /// the loop.
1550   void collectInstsToScalarize(ElementCount VF);
1551 
1552   /// Collect Uniform and Scalar values for the given \p VF.
1553   /// The sets depend on CM decision for Load/Store instructions
1554   /// that may be vectorized as interleave, gather-scatter or scalarized.
1555   void collectUniformsAndScalars(ElementCount VF) {
1556     // Do the analysis once.
1557     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1558       return;
1559     setCostBasedWideningDecision(VF);
1560     collectLoopUniforms(VF);
1561     collectLoopScalars(VF);
1562   }
1563 
1564   /// Returns true if the target machine supports masked store operation
1565   /// for the given \p DataType and kind of access to \p Ptr.
1566   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1567     return Legal->isConsecutivePtr(DataType, Ptr) &&
1568            TTI.isLegalMaskedStore(DataType, Alignment);
1569   }
1570 
1571   /// Returns true if the target machine supports masked load operation
1572   /// for the given \p DataType and kind of access to \p Ptr.
1573   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1574     return Legal->isConsecutivePtr(DataType, Ptr) &&
1575            TTI.isLegalMaskedLoad(DataType, Alignment);
1576   }
1577 
1578   /// Returns true if the target machine can represent \p V as a masked gather
1579   /// or scatter operation.
1580   bool isLegalGatherOrScatter(Value *V) {
1581     bool LI = isa<LoadInst>(V);
1582     bool SI = isa<StoreInst>(V);
1583     if (!LI && !SI)
1584       return false;
1585     auto *Ty = getLoadStoreType(V);
1586     Align Align = getLoadStoreAlignment(V);
1587     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1588            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1589   }
1590 
1591   /// Returns true if the target machine supports all of the reduction
1592   /// variables found for the given VF.
1593   bool canVectorizeReductions(ElementCount VF) const {
1594     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1595       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1596       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1597     }));
1598   }
1599 
1600   /// Returns true if \p I is an instruction that will be scalarized with
1601   /// predication. Such instructions include conditional stores and
1602   /// instructions that may divide by zero.
1603   /// If a non-zero VF has been calculated, we check if I will be scalarized
1604   /// predication for that VF.
1605   bool isScalarWithPredication(Instruction *I) const;
1606 
1607   // Returns true if \p I is an instruction that will be predicated either
1608   // through scalar predication or masked load/store or masked gather/scatter.
1609   // Superset of instructions that return true for isScalarWithPredication.
1610   bool isPredicatedInst(Instruction *I, bool IsKnownUniform = false) {
1611     // When we know the load is uniform and the original scalar loop was not
1612     // predicated we don't need to mark it as a predicated instruction. Any
1613     // vectorised blocks created when tail-folding are something artificial we
1614     // have introduced and we know there is always at least one active lane.
1615     // That's why we call Legal->blockNeedsPredication here because it doesn't
1616     // query tail-folding.
1617     if (IsKnownUniform && isa<LoadInst>(I) &&
1618         !Legal->blockNeedsPredication(I->getParent()))
1619       return false;
1620     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1621       return false;
1622     // Loads and stores that need some form of masked operation are predicated
1623     // instructions.
1624     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1625       return Legal->isMaskRequired(I);
1626     return isScalarWithPredication(I);
1627   }
1628 
1629   /// Returns true if \p I is a memory instruction with consecutive memory
1630   /// access that can be widened.
1631   bool
1632   memoryInstructionCanBeWidened(Instruction *I,
1633                                 ElementCount VF = ElementCount::getFixed(1));
1634 
1635   /// Returns true if \p I is a memory instruction in an interleaved-group
1636   /// of memory accesses that can be vectorized with wide vector loads/stores
1637   /// and shuffles.
1638   bool
1639   interleavedAccessCanBeWidened(Instruction *I,
1640                                 ElementCount VF = ElementCount::getFixed(1));
1641 
1642   /// Check if \p Instr belongs to any interleaved access group.
1643   bool isAccessInterleaved(Instruction *Instr) {
1644     return InterleaveInfo.isInterleaved(Instr);
1645   }
1646 
1647   /// Get the interleaved access group that \p Instr belongs to.
1648   const InterleaveGroup<Instruction> *
1649   getInterleavedAccessGroup(Instruction *Instr) {
1650     return InterleaveInfo.getInterleaveGroup(Instr);
1651   }
1652 
1653   /// Returns true if we're required to use a scalar epilogue for at least
1654   /// the final iteration of the original loop.
1655   bool requiresScalarEpilogue(ElementCount VF) const {
1656     if (!isScalarEpilogueAllowed())
1657       return false;
1658     // If we might exit from anywhere but the latch, must run the exiting
1659     // iteration in scalar form.
1660     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1661       return true;
1662     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1663   }
1664 
1665   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1666   /// loop hint annotation.
1667   bool isScalarEpilogueAllowed() const {
1668     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1669   }
1670 
1671   /// Returns true if all loop blocks should be masked to fold tail loop.
1672   bool foldTailByMasking() const { return FoldTailByMasking; }
1673 
1674   /// Returns true if the instructions in this block requires predication
1675   /// for any reason, e.g. because tail folding now requires a predicate
1676   /// or because the block in the original loop was predicated.
1677   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1678     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1679   }
1680 
1681   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1682   /// nodes to the chain of instructions representing the reductions. Uses a
1683   /// MapVector to ensure deterministic iteration order.
1684   using ReductionChainMap =
1685       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1686 
1687   /// Return the chain of instructions representing an inloop reduction.
1688   const ReductionChainMap &getInLoopReductionChains() const {
1689     return InLoopReductionChains;
1690   }
1691 
1692   /// Returns true if the Phi is part of an inloop reduction.
1693   bool isInLoopReduction(PHINode *Phi) const {
1694     return InLoopReductionChains.count(Phi);
1695   }
1696 
1697   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1698   /// with factor VF.  Return the cost of the instruction, including
1699   /// scalarization overhead if it's needed.
1700   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1701 
1702   /// Estimate cost of a call instruction CI if it were vectorized with factor
1703   /// VF. Return the cost of the instruction, including scalarization overhead
1704   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1705   /// scalarized -
1706   /// i.e. either vector version isn't available, or is too expensive.
1707   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1708                                     bool &NeedToScalarize) const;
1709 
1710   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1711   /// that of B.
1712   bool isMoreProfitable(const VectorizationFactor &A,
1713                         const VectorizationFactor &B) const;
1714 
1715   /// Invalidates decisions already taken by the cost model.
1716   void invalidateCostModelingDecisions() {
1717     WideningDecisions.clear();
1718     Uniforms.clear();
1719     Scalars.clear();
1720   }
1721 
1722 private:
1723   unsigned NumPredStores = 0;
1724 
1725   /// \return An upper bound for the vectorization factors for both
1726   /// fixed and scalable vectorization, where the minimum-known number of
1727   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1728   /// disabled or unsupported, then the scalable part will be equal to
1729   /// ElementCount::getScalable(0).
1730   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1731                                            ElementCount UserVF);
1732 
1733   /// \return the maximized element count based on the targets vector
1734   /// registers and the loop trip-count, but limited to a maximum safe VF.
1735   /// This is a helper function of computeFeasibleMaxVF.
1736   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1737   /// issue that occurred on one of the buildbots which cannot be reproduced
1738   /// without having access to the properietary compiler (see comments on
1739   /// D98509). The issue is currently under investigation and this workaround
1740   /// will be removed as soon as possible.
1741   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1742                                        unsigned SmallestType,
1743                                        unsigned WidestType,
1744                                        const ElementCount &MaxSafeVF);
1745 
1746   /// \return the maximum legal scalable VF, based on the safe max number
1747   /// of elements.
1748   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1749 
1750   /// The vectorization cost is a combination of the cost itself and a boolean
1751   /// indicating whether any of the contributing operations will actually
1752   /// operate on vector values after type legalization in the backend. If this
1753   /// latter value is false, then all operations will be scalarized (i.e. no
1754   /// vectorization has actually taken place).
1755   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1756 
1757   /// Returns the expected execution cost. The unit of the cost does
1758   /// not matter because we use the 'cost' units to compare different
1759   /// vector widths. The cost that is returned is *not* normalized by
1760   /// the factor width. If \p Invalid is not nullptr, this function
1761   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1762   /// each instruction that has an Invalid cost for the given VF.
1763   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1764   VectorizationCostTy
1765   expectedCost(ElementCount VF,
1766                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1767 
1768   /// Returns the execution time cost of an instruction for a given vector
1769   /// width. Vector width of one means scalar.
1770   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1771 
1772   /// The cost-computation logic from getInstructionCost which provides
1773   /// the vector type as an output parameter.
1774   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1775                                      Type *&VectorTy);
1776 
1777   /// Return the cost of instructions in an inloop reduction pattern, if I is
1778   /// part of that pattern.
1779   Optional<InstructionCost>
1780   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1781                           TTI::TargetCostKind CostKind);
1782 
1783   /// Calculate vectorization cost of memory instruction \p I.
1784   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1785 
1786   /// The cost computation for scalarized memory instruction.
1787   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1788 
1789   /// The cost computation for interleaving group of memory instructions.
1790   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1791 
1792   /// The cost computation for Gather/Scatter instruction.
1793   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1794 
1795   /// The cost computation for widening instruction \p I with consecutive
1796   /// memory access.
1797   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1798 
1799   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1800   /// Load: scalar load + broadcast.
1801   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1802   /// element)
1803   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1804 
1805   /// Estimate the overhead of scalarizing an instruction. This is a
1806   /// convenience wrapper for the type-based getScalarizationOverhead API.
1807   InstructionCost getScalarizationOverhead(Instruction *I,
1808                                            ElementCount VF) const;
1809 
1810   /// Returns whether the instruction is a load or store and will be a emitted
1811   /// as a vector operation.
1812   bool isConsecutiveLoadOrStore(Instruction *I);
1813 
1814   /// Returns true if an artificially high cost for emulated masked memrefs
1815   /// should be used.
1816   bool useEmulatedMaskMemRefHack(Instruction *I);
1817 
1818   /// Map of scalar integer values to the smallest bitwidth they can be legally
1819   /// represented as. The vector equivalents of these values should be truncated
1820   /// to this type.
1821   MapVector<Instruction *, uint64_t> MinBWs;
1822 
1823   /// A type representing the costs for instructions if they were to be
1824   /// scalarized rather than vectorized. The entries are Instruction-Cost
1825   /// pairs.
1826   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1827 
1828   /// A set containing all BasicBlocks that are known to present after
1829   /// vectorization as a predicated block.
1830   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1831 
1832   /// Records whether it is allowed to have the original scalar loop execute at
1833   /// least once. This may be needed as a fallback loop in case runtime
1834   /// aliasing/dependence checks fail, or to handle the tail/remainder
1835   /// iterations when the trip count is unknown or doesn't divide by the VF,
1836   /// or as a peel-loop to handle gaps in interleave-groups.
1837   /// Under optsize and when the trip count is very small we don't allow any
1838   /// iterations to execute in the scalar loop.
1839   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1840 
1841   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1842   bool FoldTailByMasking = false;
1843 
1844   /// A map holding scalar costs for different vectorization factors. The
1845   /// presence of a cost for an instruction in the mapping indicates that the
1846   /// instruction will be scalarized when vectorizing with the associated
1847   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1848   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1849 
1850   /// Holds the instructions known to be uniform after vectorization.
1851   /// The data is collected per VF.
1852   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1853 
1854   /// Holds the instructions known to be scalar after vectorization.
1855   /// The data is collected per VF.
1856   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1857 
1858   /// Holds the instructions (address computations) that are forced to be
1859   /// scalarized.
1860   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1861 
1862   /// PHINodes of the reductions that should be expanded in-loop along with
1863   /// their associated chains of reduction operations, in program order from top
1864   /// (PHI) to bottom
1865   ReductionChainMap InLoopReductionChains;
1866 
1867   /// A Map of inloop reduction operations and their immediate chain operand.
1868   /// FIXME: This can be removed once reductions can be costed correctly in
1869   /// vplan. This was added to allow quick lookup to the inloop operations,
1870   /// without having to loop through InLoopReductionChains.
1871   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1872 
1873   /// Returns the expected difference in cost from scalarizing the expression
1874   /// feeding a predicated instruction \p PredInst. The instructions to
1875   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1876   /// non-negative return value implies the expression will be scalarized.
1877   /// Currently, only single-use chains are considered for scalarization.
1878   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1879                               ElementCount VF);
1880 
1881   /// Collect the instructions that are uniform after vectorization. An
1882   /// instruction is uniform if we represent it with a single scalar value in
1883   /// the vectorized loop corresponding to each vector iteration. Examples of
1884   /// uniform instructions include pointer operands of consecutive or
1885   /// interleaved memory accesses. Note that although uniformity implies an
1886   /// instruction will be scalar, the reverse is not true. In general, a
1887   /// scalarized instruction will be represented by VF scalar values in the
1888   /// vectorized loop, each corresponding to an iteration of the original
1889   /// scalar loop.
1890   void collectLoopUniforms(ElementCount VF);
1891 
1892   /// Collect the instructions that are scalar after vectorization. An
1893   /// instruction is scalar if it is known to be uniform or will be scalarized
1894   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1895   /// to the list if they are used by a load/store instruction that is marked as
1896   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1897   /// VF values in the vectorized loop, each corresponding to an iteration of
1898   /// the original scalar loop.
1899   void collectLoopScalars(ElementCount VF);
1900 
1901   /// Keeps cost model vectorization decision and cost for instructions.
1902   /// Right now it is used for memory instructions only.
1903   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1904                                 std::pair<InstWidening, InstructionCost>>;
1905 
1906   DecisionList WideningDecisions;
1907 
1908   /// Returns true if \p V is expected to be vectorized and it needs to be
1909   /// extracted.
1910   bool needsExtract(Value *V, ElementCount VF) const {
1911     Instruction *I = dyn_cast<Instruction>(V);
1912     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1913         TheLoop->isLoopInvariant(I))
1914       return false;
1915 
1916     // Assume we can vectorize V (and hence we need extraction) if the
1917     // scalars are not computed yet. This can happen, because it is called
1918     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1919     // the scalars are collected. That should be a safe assumption in most
1920     // cases, because we check if the operands have vectorizable types
1921     // beforehand in LoopVectorizationLegality.
1922     return Scalars.find(VF) == Scalars.end() ||
1923            !isScalarAfterVectorization(I, VF);
1924   };
1925 
1926   /// Returns a range containing only operands needing to be extracted.
1927   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1928                                                    ElementCount VF) const {
1929     return SmallVector<Value *, 4>(make_filter_range(
1930         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1931   }
1932 
1933   /// Determines if we have the infrastructure to vectorize loop \p L and its
1934   /// epilogue, assuming the main loop is vectorized by \p VF.
1935   bool isCandidateForEpilogueVectorization(const Loop &L,
1936                                            const ElementCount VF) const;
1937 
1938   /// Returns true if epilogue vectorization is considered profitable, and
1939   /// false otherwise.
1940   /// \p VF is the vectorization factor chosen for the original loop.
1941   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1942 
1943 public:
1944   /// The loop that we evaluate.
1945   Loop *TheLoop;
1946 
1947   /// Predicated scalar evolution analysis.
1948   PredicatedScalarEvolution &PSE;
1949 
1950   /// Loop Info analysis.
1951   LoopInfo *LI;
1952 
1953   /// Vectorization legality.
1954   LoopVectorizationLegality *Legal;
1955 
1956   /// Vector target information.
1957   const TargetTransformInfo &TTI;
1958 
1959   /// Target Library Info.
1960   const TargetLibraryInfo *TLI;
1961 
1962   /// Demanded bits analysis.
1963   DemandedBits *DB;
1964 
1965   /// Assumption cache.
1966   AssumptionCache *AC;
1967 
1968   /// Interface to emit optimization remarks.
1969   OptimizationRemarkEmitter *ORE;
1970 
1971   const Function *TheFunction;
1972 
1973   /// Loop Vectorize Hint.
1974   const LoopVectorizeHints *Hints;
1975 
1976   /// The interleave access information contains groups of interleaved accesses
1977   /// with the same stride and close to each other.
1978   InterleavedAccessInfo &InterleaveInfo;
1979 
1980   /// Values to ignore in the cost model.
1981   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1982 
1983   /// Values to ignore in the cost model when VF > 1.
1984   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1985 
1986   /// All element types found in the loop.
1987   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1988 
1989   /// Profitable vector factors.
1990   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1991 };
1992 } // end namespace llvm
1993 
1994 /// Helper struct to manage generating runtime checks for vectorization.
1995 ///
1996 /// The runtime checks are created up-front in temporary blocks to allow better
1997 /// estimating the cost and un-linked from the existing IR. After deciding to
1998 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1999 /// temporary blocks are completely removed.
2000 class GeneratedRTChecks {
2001   /// Basic block which contains the generated SCEV checks, if any.
2002   BasicBlock *SCEVCheckBlock = nullptr;
2003 
2004   /// The value representing the result of the generated SCEV checks. If it is
2005   /// nullptr, either no SCEV checks have been generated or they have been used.
2006   Value *SCEVCheckCond = nullptr;
2007 
2008   /// Basic block which contains the generated memory runtime checks, if any.
2009   BasicBlock *MemCheckBlock = nullptr;
2010 
2011   /// The value representing the result of the generated memory runtime checks.
2012   /// If it is nullptr, either no memory runtime checks have been generated or
2013   /// they have been used.
2014   Value *MemRuntimeCheckCond = nullptr;
2015 
2016   DominatorTree *DT;
2017   LoopInfo *LI;
2018 
2019   SCEVExpander SCEVExp;
2020   SCEVExpander MemCheckExp;
2021 
2022 public:
2023   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
2024                     const DataLayout &DL)
2025       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
2026         MemCheckExp(SE, DL, "scev.check") {}
2027 
2028   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
2029   /// accurately estimate the cost of the runtime checks. The blocks are
2030   /// un-linked from the IR and is added back during vector code generation. If
2031   /// there is no vector code generation, the check blocks are removed
2032   /// completely.
2033   void Create(Loop *L, const LoopAccessInfo &LAI,
2034               const SCEVUnionPredicate &UnionPred) {
2035 
2036     BasicBlock *LoopHeader = L->getHeader();
2037     BasicBlock *Preheader = L->getLoopPreheader();
2038 
2039     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
2040     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
2041     // may be used by SCEVExpander. The blocks will be un-linked from their
2042     // predecessors and removed from LI & DT at the end of the function.
2043     if (!UnionPred.isAlwaysTrue()) {
2044       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
2045                                   nullptr, "vector.scevcheck");
2046 
2047       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
2048           &UnionPred, SCEVCheckBlock->getTerminator());
2049     }
2050 
2051     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
2052     if (RtPtrChecking.Need) {
2053       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
2054       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
2055                                  "vector.memcheck");
2056 
2057       MemRuntimeCheckCond =
2058           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
2059                            RtPtrChecking.getChecks(), MemCheckExp);
2060       assert(MemRuntimeCheckCond &&
2061              "no RT checks generated although RtPtrChecking "
2062              "claimed checks are required");
2063     }
2064 
2065     if (!MemCheckBlock && !SCEVCheckBlock)
2066       return;
2067 
2068     // Unhook the temporary block with the checks, update various places
2069     // accordingly.
2070     if (SCEVCheckBlock)
2071       SCEVCheckBlock->replaceAllUsesWith(Preheader);
2072     if (MemCheckBlock)
2073       MemCheckBlock->replaceAllUsesWith(Preheader);
2074 
2075     if (SCEVCheckBlock) {
2076       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2077       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
2078       Preheader->getTerminator()->eraseFromParent();
2079     }
2080     if (MemCheckBlock) {
2081       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2082       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2083       Preheader->getTerminator()->eraseFromParent();
2084     }
2085 
2086     DT->changeImmediateDominator(LoopHeader, Preheader);
2087     if (MemCheckBlock) {
2088       DT->eraseNode(MemCheckBlock);
2089       LI->removeBlock(MemCheckBlock);
2090     }
2091     if (SCEVCheckBlock) {
2092       DT->eraseNode(SCEVCheckBlock);
2093       LI->removeBlock(SCEVCheckBlock);
2094     }
2095   }
2096 
2097   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2098   /// unused.
2099   ~GeneratedRTChecks() {
2100     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2101     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2102     if (!SCEVCheckCond)
2103       SCEVCleaner.markResultUsed();
2104 
2105     if (!MemRuntimeCheckCond)
2106       MemCheckCleaner.markResultUsed();
2107 
2108     if (MemRuntimeCheckCond) {
2109       auto &SE = *MemCheckExp.getSE();
2110       // Memory runtime check generation creates compares that use expanded
2111       // values. Remove them before running the SCEVExpanderCleaners.
2112       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2113         if (MemCheckExp.isInsertedInstruction(&I))
2114           continue;
2115         SE.forgetValue(&I);
2116         I.eraseFromParent();
2117       }
2118     }
2119     MemCheckCleaner.cleanup();
2120     SCEVCleaner.cleanup();
2121 
2122     if (SCEVCheckCond)
2123       SCEVCheckBlock->eraseFromParent();
2124     if (MemRuntimeCheckCond)
2125       MemCheckBlock->eraseFromParent();
2126   }
2127 
2128   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2129   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2130   /// depending on the generated condition.
2131   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2132                              BasicBlock *LoopVectorPreHeader,
2133                              BasicBlock *LoopExitBlock) {
2134     if (!SCEVCheckCond)
2135       return nullptr;
2136     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2137       if (C->isZero())
2138         return nullptr;
2139 
2140     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2141 
2142     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2143     // Create new preheader for vector loop.
2144     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2145       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2146 
2147     SCEVCheckBlock->getTerminator()->eraseFromParent();
2148     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2149     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2150                                                 SCEVCheckBlock);
2151 
2152     DT->addNewBlock(SCEVCheckBlock, Pred);
2153     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2154 
2155     ReplaceInstWithInst(
2156         SCEVCheckBlock->getTerminator(),
2157         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2158     // Mark the check as used, to prevent it from being removed during cleanup.
2159     SCEVCheckCond = nullptr;
2160     return SCEVCheckBlock;
2161   }
2162 
2163   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2164   /// the branches to branch to the vector preheader or \p Bypass, depending on
2165   /// the generated condition.
2166   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2167                                    BasicBlock *LoopVectorPreHeader) {
2168     // Check if we generated code that checks in runtime if arrays overlap.
2169     if (!MemRuntimeCheckCond)
2170       return nullptr;
2171 
2172     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2173     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2174                                                 MemCheckBlock);
2175 
2176     DT->addNewBlock(MemCheckBlock, Pred);
2177     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2178     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2179 
2180     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2181       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2182 
2183     ReplaceInstWithInst(
2184         MemCheckBlock->getTerminator(),
2185         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2186     MemCheckBlock->getTerminator()->setDebugLoc(
2187         Pred->getTerminator()->getDebugLoc());
2188 
2189     // Mark the check as used, to prevent it from being removed during cleanup.
2190     MemRuntimeCheckCond = nullptr;
2191     return MemCheckBlock;
2192   }
2193 };
2194 
2195 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2196 // vectorization. The loop needs to be annotated with #pragma omp simd
2197 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2198 // vector length information is not provided, vectorization is not considered
2199 // explicit. Interleave hints are not allowed either. These limitations will be
2200 // relaxed in the future.
2201 // Please, note that we are currently forced to abuse the pragma 'clang
2202 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2203 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2204 // provides *explicit vectorization hints* (LV can bypass legal checks and
2205 // assume that vectorization is legal). However, both hints are implemented
2206 // using the same metadata (llvm.loop.vectorize, processed by
2207 // LoopVectorizeHints). This will be fixed in the future when the native IR
2208 // representation for pragma 'omp simd' is introduced.
2209 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2210                                    OptimizationRemarkEmitter *ORE) {
2211   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2212   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2213 
2214   // Only outer loops with an explicit vectorization hint are supported.
2215   // Unannotated outer loops are ignored.
2216   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2217     return false;
2218 
2219   Function *Fn = OuterLp->getHeader()->getParent();
2220   if (!Hints.allowVectorization(Fn, OuterLp,
2221                                 true /*VectorizeOnlyWhenForced*/)) {
2222     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2223     return false;
2224   }
2225 
2226   if (Hints.getInterleave() > 1) {
2227     // TODO: Interleave support is future work.
2228     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2229                          "outer loops.\n");
2230     Hints.emitRemarkWithHints();
2231     return false;
2232   }
2233 
2234   return true;
2235 }
2236 
2237 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2238                                   OptimizationRemarkEmitter *ORE,
2239                                   SmallVectorImpl<Loop *> &V) {
2240   // Collect inner loops and outer loops without irreducible control flow. For
2241   // now, only collect outer loops that have explicit vectorization hints. If we
2242   // are stress testing the VPlan H-CFG construction, we collect the outermost
2243   // loop of every loop nest.
2244   if (L.isInnermost() || VPlanBuildStressTest ||
2245       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2246     LoopBlocksRPO RPOT(&L);
2247     RPOT.perform(LI);
2248     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2249       V.push_back(&L);
2250       // TODO: Collect inner loops inside marked outer loops in case
2251       // vectorization fails for the outer loop. Do not invoke
2252       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2253       // already known to be reducible. We can use an inherited attribute for
2254       // that.
2255       return;
2256     }
2257   }
2258   for (Loop *InnerL : L)
2259     collectSupportedLoops(*InnerL, LI, ORE, V);
2260 }
2261 
2262 namespace {
2263 
2264 /// The LoopVectorize Pass.
2265 struct LoopVectorize : public FunctionPass {
2266   /// Pass identification, replacement for typeid
2267   static char ID;
2268 
2269   LoopVectorizePass Impl;
2270 
2271   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2272                          bool VectorizeOnlyWhenForced = false)
2273       : FunctionPass(ID),
2274         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2275     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2276   }
2277 
2278   bool runOnFunction(Function &F) override {
2279     if (skipFunction(F))
2280       return false;
2281 
2282     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2283     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2284     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2285     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2286     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2287     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2288     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2289     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2290     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2291     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2292     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2293     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2294     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2295 
2296     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2297         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2298 
2299     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2300                         GetLAA, *ORE, PSI).MadeAnyChange;
2301   }
2302 
2303   void getAnalysisUsage(AnalysisUsage &AU) const override {
2304     AU.addRequired<AssumptionCacheTracker>();
2305     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2306     AU.addRequired<DominatorTreeWrapperPass>();
2307     AU.addRequired<LoopInfoWrapperPass>();
2308     AU.addRequired<ScalarEvolutionWrapperPass>();
2309     AU.addRequired<TargetTransformInfoWrapperPass>();
2310     AU.addRequired<AAResultsWrapperPass>();
2311     AU.addRequired<LoopAccessLegacyAnalysis>();
2312     AU.addRequired<DemandedBitsWrapperPass>();
2313     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2314     AU.addRequired<InjectTLIMappingsLegacy>();
2315 
2316     // We currently do not preserve loopinfo/dominator analyses with outer loop
2317     // vectorization. Until this is addressed, mark these analyses as preserved
2318     // only for non-VPlan-native path.
2319     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2320     if (!EnableVPlanNativePath) {
2321       AU.addPreserved<LoopInfoWrapperPass>();
2322       AU.addPreserved<DominatorTreeWrapperPass>();
2323     }
2324 
2325     AU.addPreserved<BasicAAWrapperPass>();
2326     AU.addPreserved<GlobalsAAWrapperPass>();
2327     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2328   }
2329 };
2330 
2331 } // end anonymous namespace
2332 
2333 //===----------------------------------------------------------------------===//
2334 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2335 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2336 //===----------------------------------------------------------------------===//
2337 
2338 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2339   // We need to place the broadcast of invariant variables outside the loop,
2340   // but only if it's proven safe to do so. Else, broadcast will be inside
2341   // vector loop body.
2342   Instruction *Instr = dyn_cast<Instruction>(V);
2343   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2344                      (!Instr ||
2345                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2346   // Place the code for broadcasting invariant variables in the new preheader.
2347   IRBuilder<>::InsertPointGuard Guard(Builder);
2348   if (SafeToHoist)
2349     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2350 
2351   // Broadcast the scalar into all locations in the vector.
2352   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2353 
2354   return Shuf;
2355 }
2356 
2357 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2358     const InductionDescriptor &II, Value *Step, Value *Start,
2359     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2360     VPTransformState &State) {
2361   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2362          "Expected either an induction phi-node or a truncate of it!");
2363 
2364   // Construct the initial value of the vector IV in the vector loop preheader
2365   auto CurrIP = Builder.saveIP();
2366   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2367   if (isa<TruncInst>(EntryVal)) {
2368     assert(Start->getType()->isIntegerTy() &&
2369            "Truncation requires an integer type");
2370     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2371     Step = Builder.CreateTrunc(Step, TruncType);
2372     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2373   }
2374 
2375   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
2376   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2377   Value *SteppedStart =
2378       getStepVector(SplatStart, Zero, Step, II.getInductionOpcode());
2379 
2380   // We create vector phi nodes for both integer and floating-point induction
2381   // variables. Here, we determine the kind of arithmetic we will perform.
2382   Instruction::BinaryOps AddOp;
2383   Instruction::BinaryOps MulOp;
2384   if (Step->getType()->isIntegerTy()) {
2385     AddOp = Instruction::Add;
2386     MulOp = Instruction::Mul;
2387   } else {
2388     AddOp = II.getInductionOpcode();
2389     MulOp = Instruction::FMul;
2390   }
2391 
2392   // Multiply the vectorization factor by the step using integer or
2393   // floating-point arithmetic as appropriate.
2394   Type *StepType = Step->getType();
2395   Value *RuntimeVF;
2396   if (Step->getType()->isFloatingPointTy())
2397     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, VF);
2398   else
2399     RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2400   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2401 
2402   // Create a vector splat to use in the induction update.
2403   //
2404   // FIXME: If the step is non-constant, we create the vector splat with
2405   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2406   //        handle a constant vector splat.
2407   Value *SplatVF = isa<Constant>(Mul)
2408                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2409                        : Builder.CreateVectorSplat(VF, Mul);
2410   Builder.restoreIP(CurrIP);
2411 
2412   // We may need to add the step a number of times, depending on the unroll
2413   // factor. The last of those goes into the PHI.
2414   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2415                                     &*LoopVectorBody->getFirstInsertionPt());
2416   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2417   Instruction *LastInduction = VecInd;
2418   for (unsigned Part = 0; Part < UF; ++Part) {
2419     State.set(Def, LastInduction, Part);
2420 
2421     if (isa<TruncInst>(EntryVal))
2422       addMetadata(LastInduction, EntryVal);
2423     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2424                                           State, Part);
2425 
2426     LastInduction = cast<Instruction>(
2427         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2428     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2429   }
2430 
2431   // Move the last step to the end of the latch block. This ensures consistent
2432   // placement of all induction updates.
2433   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2434   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2435   auto *ICmp = cast<Instruction>(Br->getCondition());
2436   LastInduction->moveBefore(ICmp);
2437   LastInduction->setName("vec.ind.next");
2438 
2439   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2440   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2441 }
2442 
2443 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2444   return Cost->isScalarAfterVectorization(I, VF) ||
2445          Cost->isProfitableToScalarize(I, VF);
2446 }
2447 
2448 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2449   if (shouldScalarizeInstruction(IV))
2450     return true;
2451   auto isScalarInst = [&](User *U) -> bool {
2452     auto *I = cast<Instruction>(U);
2453     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2454   };
2455   return llvm::any_of(IV->users(), isScalarInst);
2456 }
2457 
2458 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2459     const InductionDescriptor &ID, const Instruction *EntryVal,
2460     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2461     unsigned Part, unsigned Lane) {
2462   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2463          "Expected either an induction phi-node or a truncate of it!");
2464 
2465   // This induction variable is not the phi from the original loop but the
2466   // newly-created IV based on the proof that casted Phi is equal to the
2467   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2468   // re-uses the same InductionDescriptor that original IV uses but we don't
2469   // have to do any recording in this case - that is done when original IV is
2470   // processed.
2471   if (isa<TruncInst>(EntryVal))
2472     return;
2473 
2474   if (!CastDef) {
2475     assert(ID.getCastInsts().empty() &&
2476            "there are casts for ID, but no CastDef");
2477     return;
2478   }
2479   assert(!ID.getCastInsts().empty() &&
2480          "there is a CastDef, but no casts for ID");
2481   // Only the first Cast instruction in the Casts vector is of interest.
2482   // The rest of the Casts (if exist) have no uses outside the
2483   // induction update chain itself.
2484   if (Lane < UINT_MAX)
2485     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2486   else
2487     State.set(CastDef, VectorLoopVal, Part);
2488 }
2489 
2490 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2491                                                 TruncInst *Trunc, VPValue *Def,
2492                                                 VPValue *CastDef,
2493                                                 VPTransformState &State) {
2494   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2495          "Primary induction variable must have an integer type");
2496 
2497   auto II = Legal->getInductionVars().find(IV);
2498   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2499 
2500   auto ID = II->second;
2501   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2502 
2503   // The value from the original loop to which we are mapping the new induction
2504   // variable.
2505   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2506 
2507   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2508 
2509   // Generate code for the induction step. Note that induction steps are
2510   // required to be loop-invariant
2511   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2512     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2513            "Induction step should be loop invariant");
2514     if (PSE.getSE()->isSCEVable(IV->getType())) {
2515       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2516       return Exp.expandCodeFor(Step, Step->getType(),
2517                                LoopVectorPreHeader->getTerminator());
2518     }
2519     return cast<SCEVUnknown>(Step)->getValue();
2520   };
2521 
2522   // The scalar value to broadcast. This is derived from the canonical
2523   // induction variable. If a truncation type is given, truncate the canonical
2524   // induction variable and step. Otherwise, derive these values from the
2525   // induction descriptor.
2526   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2527     Value *ScalarIV = Induction;
2528     if (IV != OldInduction) {
2529       ScalarIV = IV->getType()->isIntegerTy()
2530                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2531                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2532                                           IV->getType());
2533       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2534       ScalarIV->setName("offset.idx");
2535     }
2536     if (Trunc) {
2537       auto *TruncType = cast<IntegerType>(Trunc->getType());
2538       assert(Step->getType()->isIntegerTy() &&
2539              "Truncation requires an integer step");
2540       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2541       Step = Builder.CreateTrunc(Step, TruncType);
2542     }
2543     return ScalarIV;
2544   };
2545 
2546   // Create the vector values from the scalar IV, in the absence of creating a
2547   // vector IV.
2548   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2549     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2550     for (unsigned Part = 0; Part < UF; ++Part) {
2551       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2552       Value *StartIdx;
2553       if (Step->getType()->isFloatingPointTy())
2554         StartIdx = getRuntimeVFAsFloat(Builder, Step->getType(), VF * Part);
2555       else
2556         StartIdx = getRuntimeVF(Builder, Step->getType(), VF * Part);
2557 
2558       Value *EntryPart =
2559           getStepVector(Broadcasted, StartIdx, Step, ID.getInductionOpcode());
2560       State.set(Def, EntryPart, Part);
2561       if (Trunc)
2562         addMetadata(EntryPart, Trunc);
2563       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2564                                             State, Part);
2565     }
2566   };
2567 
2568   // Fast-math-flags propagate from the original induction instruction.
2569   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2570   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2571     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2572 
2573   // Now do the actual transformations, and start with creating the step value.
2574   Value *Step = CreateStepValue(ID.getStep());
2575   if (VF.isZero() || VF.isScalar()) {
2576     Value *ScalarIV = CreateScalarIV(Step);
2577     CreateSplatIV(ScalarIV, Step);
2578     return;
2579   }
2580 
2581   // Determine if we want a scalar version of the induction variable. This is
2582   // true if the induction variable itself is not widened, or if it has at
2583   // least one user in the loop that is not widened.
2584   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2585   if (!NeedsScalarIV) {
2586     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2587                                     State);
2588     return;
2589   }
2590 
2591   // Try to create a new independent vector induction variable. If we can't
2592   // create the phi node, we will splat the scalar induction variable in each
2593   // loop iteration.
2594   if (!shouldScalarizeInstruction(EntryVal)) {
2595     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2596                                     State);
2597     Value *ScalarIV = CreateScalarIV(Step);
2598     // Create scalar steps that can be used by instructions we will later
2599     // scalarize. Note that the addition of the scalar steps will not increase
2600     // the number of instructions in the loop in the common case prior to
2601     // InstCombine. We will be trading one vector extract for each scalar step.
2602     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2603     return;
2604   }
2605 
2606   // All IV users are scalar instructions, so only emit a scalar IV, not a
2607   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2608   // predicate used by the masked loads/stores.
2609   Value *ScalarIV = CreateScalarIV(Step);
2610   if (!Cost->isScalarEpilogueAllowed())
2611     CreateSplatIV(ScalarIV, Step);
2612   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2613 }
2614 
2615 Value *InnerLoopVectorizer::getStepVector(Value *Val, Value *StartIdx,
2616                                           Value *Step,
2617                                           Instruction::BinaryOps BinOp) {
2618   // Create and check the types.
2619   auto *ValVTy = cast<VectorType>(Val->getType());
2620   ElementCount VLen = ValVTy->getElementCount();
2621 
2622   Type *STy = Val->getType()->getScalarType();
2623   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2624          "Induction Step must be an integer or FP");
2625   assert(Step->getType() == STy && "Step has wrong type");
2626 
2627   SmallVector<Constant *, 8> Indices;
2628 
2629   // Create a vector of consecutive numbers from zero to VF.
2630   VectorType *InitVecValVTy = ValVTy;
2631   Type *InitVecValSTy = STy;
2632   if (STy->isFloatingPointTy()) {
2633     InitVecValSTy =
2634         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2635     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2636   }
2637   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2638 
2639   // Splat the StartIdx
2640   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2641 
2642   if (STy->isIntegerTy()) {
2643     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2644     Step = Builder.CreateVectorSplat(VLen, Step);
2645     assert(Step->getType() == Val->getType() && "Invalid step vec");
2646     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2647     // which can be found from the original scalar operations.
2648     Step = Builder.CreateMul(InitVec, Step);
2649     return Builder.CreateAdd(Val, Step, "induction");
2650   }
2651 
2652   // Floating point induction.
2653   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2654          "Binary Opcode should be specified for FP induction");
2655   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2656   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2657 
2658   Step = Builder.CreateVectorSplat(VLen, Step);
2659   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2660   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2661 }
2662 
2663 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2664                                            Instruction *EntryVal,
2665                                            const InductionDescriptor &ID,
2666                                            VPValue *Def, VPValue *CastDef,
2667                                            VPTransformState &State) {
2668   // We shouldn't have to build scalar steps if we aren't vectorizing.
2669   assert(VF.isVector() && "VF should be greater than one");
2670   // Get the value type and ensure it and the step have the same integer type.
2671   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2672   assert(ScalarIVTy == Step->getType() &&
2673          "Val and Step should have the same type");
2674 
2675   // We build scalar steps for both integer and floating-point induction
2676   // variables. Here, we determine the kind of arithmetic we will perform.
2677   Instruction::BinaryOps AddOp;
2678   Instruction::BinaryOps MulOp;
2679   if (ScalarIVTy->isIntegerTy()) {
2680     AddOp = Instruction::Add;
2681     MulOp = Instruction::Mul;
2682   } else {
2683     AddOp = ID.getInductionOpcode();
2684     MulOp = Instruction::FMul;
2685   }
2686 
2687   // Determine the number of scalars we need to generate for each unroll
2688   // iteration. If EntryVal is uniform, we only need to generate the first
2689   // lane. Otherwise, we generate all VF values.
2690   bool IsUniform =
2691       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2692   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2693   // Compute the scalar steps and save the results in State.
2694   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2695                                      ScalarIVTy->getScalarSizeInBits());
2696   Type *VecIVTy = nullptr;
2697   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2698   if (!IsUniform && VF.isScalable()) {
2699     VecIVTy = VectorType::get(ScalarIVTy, VF);
2700     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2701     SplatStep = Builder.CreateVectorSplat(VF, Step);
2702     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2703   }
2704 
2705   for (unsigned Part = 0; Part < UF; ++Part) {
2706     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, VF, Part);
2707 
2708     if (!IsUniform && VF.isScalable()) {
2709       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2710       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2711       if (ScalarIVTy->isFloatingPointTy())
2712         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2713       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2714       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2715       State.set(Def, Add, Part);
2716       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2717                                             Part);
2718       // It's useful to record the lane values too for the known minimum number
2719       // of elements so we do those below. This improves the code quality when
2720       // trying to extract the first element, for example.
2721     }
2722 
2723     if (ScalarIVTy->isFloatingPointTy())
2724       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2725 
2726     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2727       Value *StartIdx = Builder.CreateBinOp(
2728           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2729       // The step returned by `createStepForVF` is a runtime-evaluated value
2730       // when VF is scalable. Otherwise, it should be folded into a Constant.
2731       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2732              "Expected StartIdx to be folded to a constant when VF is not "
2733              "scalable");
2734       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2735       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2736       State.set(Def, Add, VPIteration(Part, Lane));
2737       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2738                                             Part, Lane);
2739     }
2740   }
2741 }
2742 
2743 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2744                                                     const VPIteration &Instance,
2745                                                     VPTransformState &State) {
2746   Value *ScalarInst = State.get(Def, Instance);
2747   Value *VectorValue = State.get(Def, Instance.Part);
2748   VectorValue = Builder.CreateInsertElement(
2749       VectorValue, ScalarInst,
2750       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2751   State.set(Def, VectorValue, Instance.Part);
2752 }
2753 
2754 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2755   assert(Vec->getType()->isVectorTy() && "Invalid type");
2756   return Builder.CreateVectorReverse(Vec, "reverse");
2757 }
2758 
2759 // Return whether we allow using masked interleave-groups (for dealing with
2760 // strided loads/stores that reside in predicated blocks, or for dealing
2761 // with gaps).
2762 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2763   // If an override option has been passed in for interleaved accesses, use it.
2764   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2765     return EnableMaskedInterleavedMemAccesses;
2766 
2767   return TTI.enableMaskedInterleavedAccessVectorization();
2768 }
2769 
2770 // Try to vectorize the interleave group that \p Instr belongs to.
2771 //
2772 // E.g. Translate following interleaved load group (factor = 3):
2773 //   for (i = 0; i < N; i+=3) {
2774 //     R = Pic[i];             // Member of index 0
2775 //     G = Pic[i+1];           // Member of index 1
2776 //     B = Pic[i+2];           // Member of index 2
2777 //     ... // do something to R, G, B
2778 //   }
2779 // To:
2780 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2781 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2782 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2783 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2784 //
2785 // Or translate following interleaved store group (factor = 3):
2786 //   for (i = 0; i < N; i+=3) {
2787 //     ... do something to R, G, B
2788 //     Pic[i]   = R;           // Member of index 0
2789 //     Pic[i+1] = G;           // Member of index 1
2790 //     Pic[i+2] = B;           // Member of index 2
2791 //   }
2792 // To:
2793 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2794 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2795 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2796 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2797 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2798 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2799     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2800     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2801     VPValue *BlockInMask) {
2802   Instruction *Instr = Group->getInsertPos();
2803   const DataLayout &DL = Instr->getModule()->getDataLayout();
2804 
2805   // Prepare for the vector type of the interleaved load/store.
2806   Type *ScalarTy = getLoadStoreType(Instr);
2807   unsigned InterleaveFactor = Group->getFactor();
2808   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2809   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2810 
2811   // Prepare for the new pointers.
2812   SmallVector<Value *, 2> AddrParts;
2813   unsigned Index = Group->getIndex(Instr);
2814 
2815   // TODO: extend the masked interleaved-group support to reversed access.
2816   assert((!BlockInMask || !Group->isReverse()) &&
2817          "Reversed masked interleave-group not supported.");
2818 
2819   // If the group is reverse, adjust the index to refer to the last vector lane
2820   // instead of the first. We adjust the index from the first vector lane,
2821   // rather than directly getting the pointer for lane VF - 1, because the
2822   // pointer operand of the interleaved access is supposed to be uniform. For
2823   // uniform instructions, we're only required to generate a value for the
2824   // first vector lane in each unroll iteration.
2825   if (Group->isReverse())
2826     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2827 
2828   for (unsigned Part = 0; Part < UF; Part++) {
2829     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2830     setDebugLocFromInst(AddrPart);
2831 
2832     // Notice current instruction could be any index. Need to adjust the address
2833     // to the member of index 0.
2834     //
2835     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2836     //       b = A[i];       // Member of index 0
2837     // Current pointer is pointed to A[i+1], adjust it to A[i].
2838     //
2839     // E.g.  A[i+1] = a;     // Member of index 1
2840     //       A[i]   = b;     // Member of index 0
2841     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2842     // Current pointer is pointed to A[i+2], adjust it to A[i].
2843 
2844     bool InBounds = false;
2845     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2846       InBounds = gep->isInBounds();
2847     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2848     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2849 
2850     // Cast to the vector pointer type.
2851     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2852     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2853     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2854   }
2855 
2856   setDebugLocFromInst(Instr);
2857   Value *PoisonVec = PoisonValue::get(VecTy);
2858 
2859   Value *MaskForGaps = nullptr;
2860   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2861     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2862     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2863   }
2864 
2865   // Vectorize the interleaved load group.
2866   if (isa<LoadInst>(Instr)) {
2867     // For each unroll part, create a wide load for the group.
2868     SmallVector<Value *, 2> NewLoads;
2869     for (unsigned Part = 0; Part < UF; Part++) {
2870       Instruction *NewLoad;
2871       if (BlockInMask || MaskForGaps) {
2872         assert(useMaskedInterleavedAccesses(*TTI) &&
2873                "masked interleaved groups are not allowed.");
2874         Value *GroupMask = MaskForGaps;
2875         if (BlockInMask) {
2876           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2877           Value *ShuffledMask = Builder.CreateShuffleVector(
2878               BlockInMaskPart,
2879               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2880               "interleaved.mask");
2881           GroupMask = MaskForGaps
2882                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2883                                                 MaskForGaps)
2884                           : ShuffledMask;
2885         }
2886         NewLoad =
2887             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2888                                      GroupMask, PoisonVec, "wide.masked.vec");
2889       }
2890       else
2891         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2892                                             Group->getAlign(), "wide.vec");
2893       Group->addMetadata(NewLoad);
2894       NewLoads.push_back(NewLoad);
2895     }
2896 
2897     // For each member in the group, shuffle out the appropriate data from the
2898     // wide loads.
2899     unsigned J = 0;
2900     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2901       Instruction *Member = Group->getMember(I);
2902 
2903       // Skip the gaps in the group.
2904       if (!Member)
2905         continue;
2906 
2907       auto StrideMask =
2908           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2909       for (unsigned Part = 0; Part < UF; Part++) {
2910         Value *StridedVec = Builder.CreateShuffleVector(
2911             NewLoads[Part], StrideMask, "strided.vec");
2912 
2913         // If this member has different type, cast the result type.
2914         if (Member->getType() != ScalarTy) {
2915           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2916           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2917           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2918         }
2919 
2920         if (Group->isReverse())
2921           StridedVec = reverseVector(StridedVec);
2922 
2923         State.set(VPDefs[J], StridedVec, Part);
2924       }
2925       ++J;
2926     }
2927     return;
2928   }
2929 
2930   // The sub vector type for current instruction.
2931   auto *SubVT = VectorType::get(ScalarTy, VF);
2932 
2933   // Vectorize the interleaved store group.
2934   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2935   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2936          "masked interleaved groups are not allowed.");
2937   assert((!MaskForGaps || !VF.isScalable()) &&
2938          "masking gaps for scalable vectors is not yet supported.");
2939   for (unsigned Part = 0; Part < UF; Part++) {
2940     // Collect the stored vector from each member.
2941     SmallVector<Value *, 4> StoredVecs;
2942     for (unsigned i = 0; i < InterleaveFactor; i++) {
2943       assert((Group->getMember(i) || MaskForGaps) &&
2944              "Fail to get a member from an interleaved store group");
2945       Instruction *Member = Group->getMember(i);
2946 
2947       // Skip the gaps in the group.
2948       if (!Member) {
2949         Value *Undef = PoisonValue::get(SubVT);
2950         StoredVecs.push_back(Undef);
2951         continue;
2952       }
2953 
2954       Value *StoredVec = State.get(StoredValues[i], Part);
2955 
2956       if (Group->isReverse())
2957         StoredVec = reverseVector(StoredVec);
2958 
2959       // If this member has different type, cast it to a unified type.
2960 
2961       if (StoredVec->getType() != SubVT)
2962         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2963 
2964       StoredVecs.push_back(StoredVec);
2965     }
2966 
2967     // Concatenate all vectors into a wide vector.
2968     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2969 
2970     // Interleave the elements in the wide vector.
2971     Value *IVec = Builder.CreateShuffleVector(
2972         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2973         "interleaved.vec");
2974 
2975     Instruction *NewStoreInstr;
2976     if (BlockInMask || MaskForGaps) {
2977       Value *GroupMask = MaskForGaps;
2978       if (BlockInMask) {
2979         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2980         Value *ShuffledMask = Builder.CreateShuffleVector(
2981             BlockInMaskPart,
2982             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2983             "interleaved.mask");
2984         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2985                                                       ShuffledMask, MaskForGaps)
2986                                 : ShuffledMask;
2987       }
2988       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2989                                                 Group->getAlign(), GroupMask);
2990     } else
2991       NewStoreInstr =
2992           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2993 
2994     Group->addMetadata(NewStoreInstr);
2995   }
2996 }
2997 
2998 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2999                                                VPReplicateRecipe *RepRecipe,
3000                                                const VPIteration &Instance,
3001                                                bool IfPredicateInstr,
3002                                                VPTransformState &State) {
3003   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3004 
3005   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3006   // the first lane and part.
3007   if (isa<NoAliasScopeDeclInst>(Instr))
3008     if (!Instance.isFirstIteration())
3009       return;
3010 
3011   setDebugLocFromInst(Instr);
3012 
3013   // Does this instruction return a value ?
3014   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3015 
3016   Instruction *Cloned = Instr->clone();
3017   if (!IsVoidRetTy)
3018     Cloned->setName(Instr->getName() + ".cloned");
3019 
3020   // If the scalarized instruction contributes to the address computation of a
3021   // widen masked load/store which was in a basic block that needed predication
3022   // and is not predicated after vectorization, we can't propagate
3023   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
3024   // instruction could feed a poison value to the base address of the widen
3025   // load/store.
3026   if (State.MayGeneratePoisonRecipes.count(RepRecipe) > 0)
3027     Cloned->dropPoisonGeneratingFlags();
3028 
3029   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3030                                Builder.GetInsertPoint());
3031   // Replace the operands of the cloned instructions with their scalar
3032   // equivalents in the new loop.
3033   for (auto &I : enumerate(RepRecipe->operands())) {
3034     auto InputInstance = Instance;
3035     VPValue *Operand = I.value();
3036     if (State.Plan->isUniformAfterVectorization(Operand))
3037       InputInstance.Lane = VPLane::getFirstLane();
3038     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
3039   }
3040   addNewMetadata(Cloned, Instr);
3041 
3042   // Place the cloned scalar in the new loop.
3043   Builder.Insert(Cloned);
3044 
3045   State.set(RepRecipe, Cloned, Instance);
3046 
3047   // If we just cloned a new assumption, add it the assumption cache.
3048   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3049     AC->registerAssumption(II);
3050 
3051   // End if-block.
3052   if (IfPredicateInstr)
3053     PredicatedInstructions.push_back(Cloned);
3054 }
3055 
3056 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3057                                                       Value *End, Value *Step,
3058                                                       Instruction *DL) {
3059   BasicBlock *Header = L->getHeader();
3060   BasicBlock *Latch = L->getLoopLatch();
3061   // As we're just creating this loop, it's possible no latch exists
3062   // yet. If so, use the header as this will be a single block loop.
3063   if (!Latch)
3064     Latch = Header;
3065 
3066   IRBuilder<> B(&*Header->getFirstInsertionPt());
3067   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3068   setDebugLocFromInst(OldInst, &B);
3069   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3070 
3071   B.SetInsertPoint(Latch->getTerminator());
3072   setDebugLocFromInst(OldInst, &B);
3073 
3074   // Create i+1 and fill the PHINode.
3075   //
3076   // If the tail is not folded, we know that End - Start >= Step (either
3077   // statically or through the minimum iteration checks). We also know that both
3078   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3079   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3080   // overflows and we can mark the induction increment as NUW.
3081   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3082                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3083   Induction->addIncoming(Start, L->getLoopPreheader());
3084   Induction->addIncoming(Next, Latch);
3085   // Create the compare.
3086   Value *ICmp = B.CreateICmpEQ(Next, End);
3087   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3088 
3089   // Now we have two terminators. Remove the old one from the block.
3090   Latch->getTerminator()->eraseFromParent();
3091 
3092   return Induction;
3093 }
3094 
3095 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3096   if (TripCount)
3097     return TripCount;
3098 
3099   assert(L && "Create Trip Count for null loop.");
3100   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3101   // Find the loop boundaries.
3102   ScalarEvolution *SE = PSE.getSE();
3103   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3104   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3105          "Invalid loop count");
3106 
3107   Type *IdxTy = Legal->getWidestInductionType();
3108   assert(IdxTy && "No type for induction");
3109 
3110   // The exit count might have the type of i64 while the phi is i32. This can
3111   // happen if we have an induction variable that is sign extended before the
3112   // compare. The only way that we get a backedge taken count is that the
3113   // induction variable was signed and as such will not overflow. In such a case
3114   // truncation is legal.
3115   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3116       IdxTy->getPrimitiveSizeInBits())
3117     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3118   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3119 
3120   // Get the total trip count from the count by adding 1.
3121   const SCEV *ExitCount = SE->getAddExpr(
3122       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3123 
3124   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3125 
3126   // Expand the trip count and place the new instructions in the preheader.
3127   // Notice that the pre-header does not change, only the loop body.
3128   SCEVExpander Exp(*SE, DL, "induction");
3129 
3130   // Count holds the overall loop count (N).
3131   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3132                                 L->getLoopPreheader()->getTerminator());
3133 
3134   if (TripCount->getType()->isPointerTy())
3135     TripCount =
3136         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3137                                     L->getLoopPreheader()->getTerminator());
3138 
3139   return TripCount;
3140 }
3141 
3142 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3143   if (VectorTripCount)
3144     return VectorTripCount;
3145 
3146   Value *TC = getOrCreateTripCount(L);
3147   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3148 
3149   Type *Ty = TC->getType();
3150   // This is where we can make the step a runtime constant.
3151   Value *Step = createStepForVF(Builder, Ty, VF, UF);
3152 
3153   // If the tail is to be folded by masking, round the number of iterations N
3154   // up to a multiple of Step instead of rounding down. This is done by first
3155   // adding Step-1 and then rounding down. Note that it's ok if this addition
3156   // overflows: the vector induction variable will eventually wrap to zero given
3157   // that it starts at zero and its Step is a power of two; the loop will then
3158   // exit, with the last early-exit vector comparison also producing all-true.
3159   if (Cost->foldTailByMasking()) {
3160     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3161            "VF*UF must be a power of 2 when folding tail by masking");
3162     assert(!VF.isScalable() &&
3163            "Tail folding not yet supported for scalable vectors");
3164     TC = Builder.CreateAdd(
3165         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3166   }
3167 
3168   // Now we need to generate the expression for the part of the loop that the
3169   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3170   // iterations are not required for correctness, or N - Step, otherwise. Step
3171   // is equal to the vectorization factor (number of SIMD elements) times the
3172   // unroll factor (number of SIMD instructions).
3173   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3174 
3175   // There are cases where we *must* run at least one iteration in the remainder
3176   // loop.  See the cost model for when this can happen.  If the step evenly
3177   // divides the trip count, we set the remainder to be equal to the step. If
3178   // the step does not evenly divide the trip count, no adjustment is necessary
3179   // since there will already be scalar iterations. Note that the minimum
3180   // iterations check ensures that N >= Step.
3181   if (Cost->requiresScalarEpilogue(VF)) {
3182     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3183     R = Builder.CreateSelect(IsZero, Step, R);
3184   }
3185 
3186   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3187 
3188   return VectorTripCount;
3189 }
3190 
3191 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3192                                                    const DataLayout &DL) {
3193   // Verify that V is a vector type with same number of elements as DstVTy.
3194   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3195   unsigned VF = DstFVTy->getNumElements();
3196   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3197   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3198   Type *SrcElemTy = SrcVecTy->getElementType();
3199   Type *DstElemTy = DstFVTy->getElementType();
3200   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3201          "Vector elements must have same size");
3202 
3203   // Do a direct cast if element types are castable.
3204   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3205     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3206   }
3207   // V cannot be directly casted to desired vector type.
3208   // May happen when V is a floating point vector but DstVTy is a vector of
3209   // pointers or vice-versa. Handle this using a two-step bitcast using an
3210   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3211   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3212          "Only one type should be a pointer type");
3213   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3214          "Only one type should be a floating point type");
3215   Type *IntTy =
3216       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3217   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3218   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3219   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3220 }
3221 
3222 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3223                                                          BasicBlock *Bypass) {
3224   Value *Count = getOrCreateTripCount(L);
3225   // Reuse existing vector loop preheader for TC checks.
3226   // Note that new preheader block is generated for vector loop.
3227   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3228   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3229 
3230   // Generate code to check if the loop's trip count is less than VF * UF, or
3231   // equal to it in case a scalar epilogue is required; this implies that the
3232   // vector trip count is zero. This check also covers the case where adding one
3233   // to the backedge-taken count overflowed leading to an incorrect trip count
3234   // of zero. In this case we will also jump to the scalar loop.
3235   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3236                                             : ICmpInst::ICMP_ULT;
3237 
3238   // If tail is to be folded, vector loop takes care of all iterations.
3239   Value *CheckMinIters = Builder.getFalse();
3240   if (!Cost->foldTailByMasking()) {
3241     Value *Step = createStepForVF(Builder, Count->getType(), VF, UF);
3242     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3243   }
3244   // Create new preheader for vector loop.
3245   LoopVectorPreHeader =
3246       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3247                  "vector.ph");
3248 
3249   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3250                                DT->getNode(Bypass)->getIDom()) &&
3251          "TC check is expected to dominate Bypass");
3252 
3253   // Update dominator for Bypass & LoopExit (if needed).
3254   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3255   if (!Cost->requiresScalarEpilogue(VF))
3256     // If there is an epilogue which must run, there's no edge from the
3257     // middle block to exit blocks  and thus no need to update the immediate
3258     // dominator of the exit blocks.
3259     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3260 
3261   ReplaceInstWithInst(
3262       TCCheckBlock->getTerminator(),
3263       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3264   LoopBypassBlocks.push_back(TCCheckBlock);
3265 }
3266 
3267 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3268 
3269   BasicBlock *const SCEVCheckBlock =
3270       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3271   if (!SCEVCheckBlock)
3272     return nullptr;
3273 
3274   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3275            (OptForSizeBasedOnProfile &&
3276             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3277          "Cannot SCEV check stride or overflow when optimizing for size");
3278 
3279 
3280   // Update dominator only if this is first RT check.
3281   if (LoopBypassBlocks.empty()) {
3282     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3283     if (!Cost->requiresScalarEpilogue(VF))
3284       // If there is an epilogue which must run, there's no edge from the
3285       // middle block to exit blocks  and thus no need to update the immediate
3286       // dominator of the exit blocks.
3287       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3288   }
3289 
3290   LoopBypassBlocks.push_back(SCEVCheckBlock);
3291   AddedSafetyChecks = true;
3292   return SCEVCheckBlock;
3293 }
3294 
3295 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3296                                                       BasicBlock *Bypass) {
3297   // VPlan-native path does not do any analysis for runtime checks currently.
3298   if (EnableVPlanNativePath)
3299     return nullptr;
3300 
3301   BasicBlock *const MemCheckBlock =
3302       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3303 
3304   // Check if we generated code that checks in runtime if arrays overlap. We put
3305   // the checks into a separate block to make the more common case of few
3306   // elements faster.
3307   if (!MemCheckBlock)
3308     return nullptr;
3309 
3310   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3311     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3312            "Cannot emit memory checks when optimizing for size, unless forced "
3313            "to vectorize.");
3314     ORE->emit([&]() {
3315       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3316                                         L->getStartLoc(), L->getHeader())
3317              << "Code-size may be reduced by not forcing "
3318                 "vectorization, or by source-code modifications "
3319                 "eliminating the need for runtime checks "
3320                 "(e.g., adding 'restrict').";
3321     });
3322   }
3323 
3324   LoopBypassBlocks.push_back(MemCheckBlock);
3325 
3326   AddedSafetyChecks = true;
3327 
3328   // We currently don't use LoopVersioning for the actual loop cloning but we
3329   // still use it to add the noalias metadata.
3330   LVer = std::make_unique<LoopVersioning>(
3331       *Legal->getLAI(),
3332       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3333       DT, PSE.getSE());
3334   LVer->prepareNoAliasMetadata();
3335   return MemCheckBlock;
3336 }
3337 
3338 Value *InnerLoopVectorizer::emitTransformedIndex(
3339     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3340     const InductionDescriptor &ID) const {
3341 
3342   SCEVExpander Exp(*SE, DL, "induction");
3343   auto Step = ID.getStep();
3344   auto StartValue = ID.getStartValue();
3345   assert(Index->getType()->getScalarType() == Step->getType() &&
3346          "Index scalar type does not match StepValue type");
3347 
3348   // Note: the IR at this point is broken. We cannot use SE to create any new
3349   // SCEV and then expand it, hoping that SCEV's simplification will give us
3350   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3351   // lead to various SCEV crashes. So all we can do is to use builder and rely
3352   // on InstCombine for future simplifications. Here we handle some trivial
3353   // cases only.
3354   auto CreateAdd = [&B](Value *X, Value *Y) {
3355     assert(X->getType() == Y->getType() && "Types don't match!");
3356     if (auto *CX = dyn_cast<ConstantInt>(X))
3357       if (CX->isZero())
3358         return Y;
3359     if (auto *CY = dyn_cast<ConstantInt>(Y))
3360       if (CY->isZero())
3361         return X;
3362     return B.CreateAdd(X, Y);
3363   };
3364 
3365   // We allow X to be a vector type, in which case Y will potentially be
3366   // splatted into a vector with the same element count.
3367   auto CreateMul = [&B](Value *X, Value *Y) {
3368     assert(X->getType()->getScalarType() == Y->getType() &&
3369            "Types don't match!");
3370     if (auto *CX = dyn_cast<ConstantInt>(X))
3371       if (CX->isOne())
3372         return Y;
3373     if (auto *CY = dyn_cast<ConstantInt>(Y))
3374       if (CY->isOne())
3375         return X;
3376     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3377     if (XVTy && !isa<VectorType>(Y->getType()))
3378       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3379     return B.CreateMul(X, Y);
3380   };
3381 
3382   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3383   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3384   // the DomTree is not kept up-to-date for additional blocks generated in the
3385   // vector loop. By using the header as insertion point, we guarantee that the
3386   // expanded instructions dominate all their uses.
3387   auto GetInsertPoint = [this, &B]() {
3388     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3389     if (InsertBB != LoopVectorBody &&
3390         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3391       return LoopVectorBody->getTerminator();
3392     return &*B.GetInsertPoint();
3393   };
3394 
3395   switch (ID.getKind()) {
3396   case InductionDescriptor::IK_IntInduction: {
3397     assert(!isa<VectorType>(Index->getType()) &&
3398            "Vector indices not supported for integer inductions yet");
3399     assert(Index->getType() == StartValue->getType() &&
3400            "Index type does not match StartValue type");
3401     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3402       return B.CreateSub(StartValue, Index);
3403     auto *Offset = CreateMul(
3404         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3405     return CreateAdd(StartValue, Offset);
3406   }
3407   case InductionDescriptor::IK_PtrInduction: {
3408     assert(isa<SCEVConstant>(Step) &&
3409            "Expected constant step for pointer induction");
3410     return B.CreateGEP(
3411         ID.getElementType(), StartValue,
3412         CreateMul(Index,
3413                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3414                                     GetInsertPoint())));
3415   }
3416   case InductionDescriptor::IK_FpInduction: {
3417     assert(!isa<VectorType>(Index->getType()) &&
3418            "Vector indices not supported for FP inductions yet");
3419     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3420     auto InductionBinOp = ID.getInductionBinOp();
3421     assert(InductionBinOp &&
3422            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3423             InductionBinOp->getOpcode() == Instruction::FSub) &&
3424            "Original bin op should be defined for FP induction");
3425 
3426     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3427     Value *MulExp = B.CreateFMul(StepValue, Index);
3428     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3429                          "induction");
3430   }
3431   case InductionDescriptor::IK_NoInduction:
3432     return nullptr;
3433   }
3434   llvm_unreachable("invalid enum");
3435 }
3436 
3437 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3438   LoopScalarBody = OrigLoop->getHeader();
3439   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3440   assert(LoopVectorPreHeader && "Invalid loop structure");
3441   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3442   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3443          "multiple exit loop without required epilogue?");
3444 
3445   LoopMiddleBlock =
3446       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3447                  LI, nullptr, Twine(Prefix) + "middle.block");
3448   LoopScalarPreHeader =
3449       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3450                  nullptr, Twine(Prefix) + "scalar.ph");
3451 
3452   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3453 
3454   // Set up the middle block terminator.  Two cases:
3455   // 1) If we know that we must execute the scalar epilogue, emit an
3456   //    unconditional branch.
3457   // 2) Otherwise, we must have a single unique exit block (due to how we
3458   //    implement the multiple exit case).  In this case, set up a conditonal
3459   //    branch from the middle block to the loop scalar preheader, and the
3460   //    exit block.  completeLoopSkeleton will update the condition to use an
3461   //    iteration check, if required to decide whether to execute the remainder.
3462   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3463     BranchInst::Create(LoopScalarPreHeader) :
3464     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3465                        Builder.getTrue());
3466   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3467   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3468 
3469   // We intentionally don't let SplitBlock to update LoopInfo since
3470   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3471   // LoopVectorBody is explicitly added to the correct place few lines later.
3472   LoopVectorBody =
3473       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3474                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3475 
3476   // Update dominator for loop exit.
3477   if (!Cost->requiresScalarEpilogue(VF))
3478     // If there is an epilogue which must run, there's no edge from the
3479     // middle block to exit blocks  and thus no need to update the immediate
3480     // dominator of the exit blocks.
3481     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3482 
3483   // Create and register the new vector loop.
3484   Loop *Lp = LI->AllocateLoop();
3485   Loop *ParentLoop = OrigLoop->getParentLoop();
3486 
3487   // Insert the new loop into the loop nest and register the new basic blocks
3488   // before calling any utilities such as SCEV that require valid LoopInfo.
3489   if (ParentLoop) {
3490     ParentLoop->addChildLoop(Lp);
3491   } else {
3492     LI->addTopLevelLoop(Lp);
3493   }
3494   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3495   return Lp;
3496 }
3497 
3498 void InnerLoopVectorizer::createInductionResumeValues(
3499     Loop *L, Value *VectorTripCount,
3500     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3501   assert(VectorTripCount && L && "Expected valid arguments");
3502   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3503           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3504          "Inconsistent information about additional bypass.");
3505   // We are going to resume the execution of the scalar loop.
3506   // Go over all of the induction variables that we found and fix the
3507   // PHIs that are left in the scalar version of the loop.
3508   // The starting values of PHI nodes depend on the counter of the last
3509   // iteration in the vectorized loop.
3510   // If we come from a bypass edge then we need to start from the original
3511   // start value.
3512   for (auto &InductionEntry : Legal->getInductionVars()) {
3513     PHINode *OrigPhi = InductionEntry.first;
3514     InductionDescriptor II = InductionEntry.second;
3515 
3516     // Create phi nodes to merge from the  backedge-taken check block.
3517     PHINode *BCResumeVal =
3518         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3519                         LoopScalarPreHeader->getTerminator());
3520     // Copy original phi DL over to the new one.
3521     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3522     Value *&EndValue = IVEndValues[OrigPhi];
3523     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3524     if (OrigPhi == OldInduction) {
3525       // We know what the end value is.
3526       EndValue = VectorTripCount;
3527     } else {
3528       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3529 
3530       // Fast-math-flags propagate from the original induction instruction.
3531       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3532         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3533 
3534       Type *StepType = II.getStep()->getType();
3535       Instruction::CastOps CastOp =
3536           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3537       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3538       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3539       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3540       EndValue->setName("ind.end");
3541 
3542       // Compute the end value for the additional bypass (if applicable).
3543       if (AdditionalBypass.first) {
3544         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3545         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3546                                          StepType, true);
3547         CRD =
3548             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3549         EndValueFromAdditionalBypass =
3550             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3551         EndValueFromAdditionalBypass->setName("ind.end");
3552       }
3553     }
3554     // The new PHI merges the original incoming value, in case of a bypass,
3555     // or the value at the end of the vectorized loop.
3556     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3557 
3558     // Fix the scalar body counter (PHI node).
3559     // The old induction's phi node in the scalar body needs the truncated
3560     // value.
3561     for (BasicBlock *BB : LoopBypassBlocks)
3562       BCResumeVal->addIncoming(II.getStartValue(), BB);
3563 
3564     if (AdditionalBypass.first)
3565       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3566                                             EndValueFromAdditionalBypass);
3567 
3568     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3569   }
3570 }
3571 
3572 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3573                                                       MDNode *OrigLoopID) {
3574   assert(L && "Expected valid loop.");
3575 
3576   // The trip counts should be cached by now.
3577   Value *Count = getOrCreateTripCount(L);
3578   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3579 
3580   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3581 
3582   // Add a check in the middle block to see if we have completed
3583   // all of the iterations in the first vector loop.  Three cases:
3584   // 1) If we require a scalar epilogue, there is no conditional branch as
3585   //    we unconditionally branch to the scalar preheader.  Do nothing.
3586   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3587   //    Thus if tail is to be folded, we know we don't need to run the
3588   //    remainder and we can use the previous value for the condition (true).
3589   // 3) Otherwise, construct a runtime check.
3590   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3591     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3592                                         Count, VectorTripCount, "cmp.n",
3593                                         LoopMiddleBlock->getTerminator());
3594 
3595     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3596     // of the corresponding compare because they may have ended up with
3597     // different line numbers and we want to avoid awkward line stepping while
3598     // debugging. Eg. if the compare has got a line number inside the loop.
3599     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3600     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3601   }
3602 
3603   // Get ready to start creating new instructions into the vectorized body.
3604   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3605          "Inconsistent vector loop preheader");
3606   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3607 
3608   Optional<MDNode *> VectorizedLoopID =
3609       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3610                                       LLVMLoopVectorizeFollowupVectorized});
3611   if (VectorizedLoopID.hasValue()) {
3612     L->setLoopID(VectorizedLoopID.getValue());
3613 
3614     // Do not setAlreadyVectorized if loop attributes have been defined
3615     // explicitly.
3616     return LoopVectorPreHeader;
3617   }
3618 
3619   // Keep all loop hints from the original loop on the vector loop (we'll
3620   // replace the vectorizer-specific hints below).
3621   if (MDNode *LID = OrigLoop->getLoopID())
3622     L->setLoopID(LID);
3623 
3624   LoopVectorizeHints Hints(L, true, *ORE);
3625   Hints.setAlreadyVectorized();
3626 
3627 #ifdef EXPENSIVE_CHECKS
3628   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3629   LI->verify(*DT);
3630 #endif
3631 
3632   return LoopVectorPreHeader;
3633 }
3634 
3635 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3636   /*
3637    In this function we generate a new loop. The new loop will contain
3638    the vectorized instructions while the old loop will continue to run the
3639    scalar remainder.
3640 
3641        [ ] <-- loop iteration number check.
3642     /   |
3643    /    v
3644   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3645   |  /  |
3646   | /   v
3647   ||   [ ]     <-- vector pre header.
3648   |/    |
3649   |     v
3650   |    [  ] \
3651   |    [  ]_|   <-- vector loop.
3652   |     |
3653   |     v
3654   \   -[ ]   <--- middle-block.
3655    \/   |
3656    /\   v
3657    | ->[ ]     <--- new preheader.
3658    |    |
3659  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3660    |   [ ] \
3661    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3662     \   |
3663      \  v
3664       >[ ]     <-- exit block(s).
3665    ...
3666    */
3667 
3668   // Get the metadata of the original loop before it gets modified.
3669   MDNode *OrigLoopID = OrigLoop->getLoopID();
3670 
3671   // Workaround!  Compute the trip count of the original loop and cache it
3672   // before we start modifying the CFG.  This code has a systemic problem
3673   // wherein it tries to run analysis over partially constructed IR; this is
3674   // wrong, and not simply for SCEV.  The trip count of the original loop
3675   // simply happens to be prone to hitting this in practice.  In theory, we
3676   // can hit the same issue for any SCEV, or ValueTracking query done during
3677   // mutation.  See PR49900.
3678   getOrCreateTripCount(OrigLoop);
3679 
3680   // Create an empty vector loop, and prepare basic blocks for the runtime
3681   // checks.
3682   Loop *Lp = createVectorLoopSkeleton("");
3683 
3684   // Now, compare the new count to zero. If it is zero skip the vector loop and
3685   // jump to the scalar loop. This check also covers the case where the
3686   // backedge-taken count is uint##_max: adding one to it will overflow leading
3687   // to an incorrect trip count of zero. In this (rare) case we will also jump
3688   // to the scalar loop.
3689   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3690 
3691   // Generate the code to check any assumptions that we've made for SCEV
3692   // expressions.
3693   emitSCEVChecks(Lp, LoopScalarPreHeader);
3694 
3695   // Generate the code that checks in runtime if arrays overlap. We put the
3696   // checks into a separate block to make the more common case of few elements
3697   // faster.
3698   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3699 
3700   // Some loops have a single integer induction variable, while other loops
3701   // don't. One example is c++ iterators that often have multiple pointer
3702   // induction variables. In the code below we also support a case where we
3703   // don't have a single induction variable.
3704   //
3705   // We try to obtain an induction variable from the original loop as hard
3706   // as possible. However if we don't find one that:
3707   //   - is an integer
3708   //   - counts from zero, stepping by one
3709   //   - is the size of the widest induction variable type
3710   // then we create a new one.
3711   OldInduction = Legal->getPrimaryInduction();
3712   Type *IdxTy = Legal->getWidestInductionType();
3713   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3714   // The loop step is equal to the vectorization factor (num of SIMD elements)
3715   // times the unroll factor (num of SIMD instructions).
3716   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3717   Value *Step = createStepForVF(Builder, IdxTy, VF, UF);
3718   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3719   Induction =
3720       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3721                               getDebugLocFromInstOrOperands(OldInduction));
3722 
3723   // Emit phis for the new starting index of the scalar loop.
3724   createInductionResumeValues(Lp, CountRoundDown);
3725 
3726   return completeLoopSkeleton(Lp, OrigLoopID);
3727 }
3728 
3729 // Fix up external users of the induction variable. At this point, we are
3730 // in LCSSA form, with all external PHIs that use the IV having one input value,
3731 // coming from the remainder loop. We need those PHIs to also have a correct
3732 // value for the IV when arriving directly from the middle block.
3733 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3734                                        const InductionDescriptor &II,
3735                                        Value *CountRoundDown, Value *EndValue,
3736                                        BasicBlock *MiddleBlock) {
3737   // There are two kinds of external IV usages - those that use the value
3738   // computed in the last iteration (the PHI) and those that use the penultimate
3739   // value (the value that feeds into the phi from the loop latch).
3740   // We allow both, but they, obviously, have different values.
3741 
3742   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3743 
3744   DenseMap<Value *, Value *> MissingVals;
3745 
3746   // An external user of the last iteration's value should see the value that
3747   // the remainder loop uses to initialize its own IV.
3748   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3749   for (User *U : PostInc->users()) {
3750     Instruction *UI = cast<Instruction>(U);
3751     if (!OrigLoop->contains(UI)) {
3752       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3753       MissingVals[UI] = EndValue;
3754     }
3755   }
3756 
3757   // An external user of the penultimate value need to see EndValue - Step.
3758   // The simplest way to get this is to recompute it from the constituent SCEVs,
3759   // that is Start + (Step * (CRD - 1)).
3760   for (User *U : OrigPhi->users()) {
3761     auto *UI = cast<Instruction>(U);
3762     if (!OrigLoop->contains(UI)) {
3763       const DataLayout &DL =
3764           OrigLoop->getHeader()->getModule()->getDataLayout();
3765       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3766 
3767       IRBuilder<> B(MiddleBlock->getTerminator());
3768 
3769       // Fast-math-flags propagate from the original induction instruction.
3770       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3771         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3772 
3773       Value *CountMinusOne = B.CreateSub(
3774           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3775       Value *CMO =
3776           !II.getStep()->getType()->isIntegerTy()
3777               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3778                              II.getStep()->getType())
3779               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3780       CMO->setName("cast.cmo");
3781       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3782       Escape->setName("ind.escape");
3783       MissingVals[UI] = Escape;
3784     }
3785   }
3786 
3787   for (auto &I : MissingVals) {
3788     PHINode *PHI = cast<PHINode>(I.first);
3789     // One corner case we have to handle is two IVs "chasing" each-other,
3790     // that is %IV2 = phi [...], [ %IV1, %latch ]
3791     // In this case, if IV1 has an external use, we need to avoid adding both
3792     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3793     // don't already have an incoming value for the middle block.
3794     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3795       PHI->addIncoming(I.second, MiddleBlock);
3796   }
3797 }
3798 
3799 namespace {
3800 
3801 struct CSEDenseMapInfo {
3802   static bool canHandle(const Instruction *I) {
3803     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3804            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3805   }
3806 
3807   static inline Instruction *getEmptyKey() {
3808     return DenseMapInfo<Instruction *>::getEmptyKey();
3809   }
3810 
3811   static inline Instruction *getTombstoneKey() {
3812     return DenseMapInfo<Instruction *>::getTombstoneKey();
3813   }
3814 
3815   static unsigned getHashValue(const Instruction *I) {
3816     assert(canHandle(I) && "Unknown instruction!");
3817     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3818                                                            I->value_op_end()));
3819   }
3820 
3821   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3822     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3823         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3824       return LHS == RHS;
3825     return LHS->isIdenticalTo(RHS);
3826   }
3827 };
3828 
3829 } // end anonymous namespace
3830 
3831 ///Perform cse of induction variable instructions.
3832 static void cse(BasicBlock *BB) {
3833   // Perform simple cse.
3834   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3835   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3836     if (!CSEDenseMapInfo::canHandle(&In))
3837       continue;
3838 
3839     // Check if we can replace this instruction with any of the
3840     // visited instructions.
3841     if (Instruction *V = CSEMap.lookup(&In)) {
3842       In.replaceAllUsesWith(V);
3843       In.eraseFromParent();
3844       continue;
3845     }
3846 
3847     CSEMap[&In] = &In;
3848   }
3849 }
3850 
3851 InstructionCost
3852 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3853                                               bool &NeedToScalarize) const {
3854   Function *F = CI->getCalledFunction();
3855   Type *ScalarRetTy = CI->getType();
3856   SmallVector<Type *, 4> Tys, ScalarTys;
3857   for (auto &ArgOp : CI->args())
3858     ScalarTys.push_back(ArgOp->getType());
3859 
3860   // Estimate cost of scalarized vector call. The source operands are assumed
3861   // to be vectors, so we need to extract individual elements from there,
3862   // execute VF scalar calls, and then gather the result into the vector return
3863   // value.
3864   InstructionCost ScalarCallCost =
3865       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3866   if (VF.isScalar())
3867     return ScalarCallCost;
3868 
3869   // Compute corresponding vector type for return value and arguments.
3870   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3871   for (Type *ScalarTy : ScalarTys)
3872     Tys.push_back(ToVectorTy(ScalarTy, VF));
3873 
3874   // Compute costs of unpacking argument values for the scalar calls and
3875   // packing the return values to a vector.
3876   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3877 
3878   InstructionCost Cost =
3879       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3880 
3881   // If we can't emit a vector call for this function, then the currently found
3882   // cost is the cost we need to return.
3883   NeedToScalarize = true;
3884   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3885   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3886 
3887   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3888     return Cost;
3889 
3890   // If the corresponding vector cost is cheaper, return its cost.
3891   InstructionCost VectorCallCost =
3892       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3893   if (VectorCallCost < Cost) {
3894     NeedToScalarize = false;
3895     Cost = VectorCallCost;
3896   }
3897   return Cost;
3898 }
3899 
3900 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3901   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3902     return Elt;
3903   return VectorType::get(Elt, VF);
3904 }
3905 
3906 InstructionCost
3907 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3908                                                    ElementCount VF) const {
3909   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3910   assert(ID && "Expected intrinsic call!");
3911   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3912   FastMathFlags FMF;
3913   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3914     FMF = FPMO->getFastMathFlags();
3915 
3916   SmallVector<const Value *> Arguments(CI->args());
3917   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3918   SmallVector<Type *> ParamTys;
3919   std::transform(FTy->param_begin(), FTy->param_end(),
3920                  std::back_inserter(ParamTys),
3921                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3922 
3923   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3924                                     dyn_cast<IntrinsicInst>(CI));
3925   return TTI.getIntrinsicInstrCost(CostAttrs,
3926                                    TargetTransformInfo::TCK_RecipThroughput);
3927 }
3928 
3929 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3930   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3931   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3932   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3933 }
3934 
3935 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3936   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3937   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3938   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3939 }
3940 
3941 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3942   // For every instruction `I` in MinBWs, truncate the operands, create a
3943   // truncated version of `I` and reextend its result. InstCombine runs
3944   // later and will remove any ext/trunc pairs.
3945   SmallPtrSet<Value *, 4> Erased;
3946   for (const auto &KV : Cost->getMinimalBitwidths()) {
3947     // If the value wasn't vectorized, we must maintain the original scalar
3948     // type. The absence of the value from State indicates that it
3949     // wasn't vectorized.
3950     // FIXME: Should not rely on getVPValue at this point.
3951     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3952     if (!State.hasAnyVectorValue(Def))
3953       continue;
3954     for (unsigned Part = 0; Part < UF; ++Part) {
3955       Value *I = State.get(Def, Part);
3956       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3957         continue;
3958       Type *OriginalTy = I->getType();
3959       Type *ScalarTruncatedTy =
3960           IntegerType::get(OriginalTy->getContext(), KV.second);
3961       auto *TruncatedTy = VectorType::get(
3962           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3963       if (TruncatedTy == OriginalTy)
3964         continue;
3965 
3966       IRBuilder<> B(cast<Instruction>(I));
3967       auto ShrinkOperand = [&](Value *V) -> Value * {
3968         if (auto *ZI = dyn_cast<ZExtInst>(V))
3969           if (ZI->getSrcTy() == TruncatedTy)
3970             return ZI->getOperand(0);
3971         return B.CreateZExtOrTrunc(V, TruncatedTy);
3972       };
3973 
3974       // The actual instruction modification depends on the instruction type,
3975       // unfortunately.
3976       Value *NewI = nullptr;
3977       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3978         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3979                              ShrinkOperand(BO->getOperand(1)));
3980 
3981         // Any wrapping introduced by shrinking this operation shouldn't be
3982         // considered undefined behavior. So, we can't unconditionally copy
3983         // arithmetic wrapping flags to NewI.
3984         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3985       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3986         NewI =
3987             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3988                          ShrinkOperand(CI->getOperand(1)));
3989       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3990         NewI = B.CreateSelect(SI->getCondition(),
3991                               ShrinkOperand(SI->getTrueValue()),
3992                               ShrinkOperand(SI->getFalseValue()));
3993       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3994         switch (CI->getOpcode()) {
3995         default:
3996           llvm_unreachable("Unhandled cast!");
3997         case Instruction::Trunc:
3998           NewI = ShrinkOperand(CI->getOperand(0));
3999           break;
4000         case Instruction::SExt:
4001           NewI = B.CreateSExtOrTrunc(
4002               CI->getOperand(0),
4003               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4004           break;
4005         case Instruction::ZExt:
4006           NewI = B.CreateZExtOrTrunc(
4007               CI->getOperand(0),
4008               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4009           break;
4010         }
4011       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
4012         auto Elements0 =
4013             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
4014         auto *O0 = B.CreateZExtOrTrunc(
4015             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
4016         auto Elements1 =
4017             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
4018         auto *O1 = B.CreateZExtOrTrunc(
4019             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
4020 
4021         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4022       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4023         // Don't do anything with the operands, just extend the result.
4024         continue;
4025       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4026         auto Elements =
4027             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
4028         auto *O0 = B.CreateZExtOrTrunc(
4029             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
4030         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4031         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4032       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4033         auto Elements =
4034             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
4035         auto *O0 = B.CreateZExtOrTrunc(
4036             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
4037         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4038       } else {
4039         // If we don't know what to do, be conservative and don't do anything.
4040         continue;
4041       }
4042 
4043       // Lastly, extend the result.
4044       NewI->takeName(cast<Instruction>(I));
4045       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4046       I->replaceAllUsesWith(Res);
4047       cast<Instruction>(I)->eraseFromParent();
4048       Erased.insert(I);
4049       State.reset(Def, Res, Part);
4050     }
4051   }
4052 
4053   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4054   for (const auto &KV : Cost->getMinimalBitwidths()) {
4055     // If the value wasn't vectorized, we must maintain the original scalar
4056     // type. The absence of the value from State indicates that it
4057     // wasn't vectorized.
4058     // FIXME: Should not rely on getVPValue at this point.
4059     VPValue *Def = State.Plan->getVPValue(KV.first, true);
4060     if (!State.hasAnyVectorValue(Def))
4061       continue;
4062     for (unsigned Part = 0; Part < UF; ++Part) {
4063       Value *I = State.get(Def, Part);
4064       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4065       if (Inst && Inst->use_empty()) {
4066         Value *NewI = Inst->getOperand(0);
4067         Inst->eraseFromParent();
4068         State.reset(Def, NewI, Part);
4069       }
4070     }
4071   }
4072 }
4073 
4074 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4075   // Insert truncates and extends for any truncated instructions as hints to
4076   // InstCombine.
4077   if (VF.isVector())
4078     truncateToMinimalBitwidths(State);
4079 
4080   // Fix widened non-induction PHIs by setting up the PHI operands.
4081   if (OrigPHIsToFix.size()) {
4082     assert(EnableVPlanNativePath &&
4083            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4084     fixNonInductionPHIs(State);
4085   }
4086 
4087   // At this point every instruction in the original loop is widened to a
4088   // vector form. Now we need to fix the recurrences in the loop. These PHI
4089   // nodes are currently empty because we did not want to introduce cycles.
4090   // This is the second stage of vectorizing recurrences.
4091   fixCrossIterationPHIs(State);
4092 
4093   // Forget the original basic block.
4094   PSE.getSE()->forgetLoop(OrigLoop);
4095 
4096   // If we inserted an edge from the middle block to the unique exit block,
4097   // update uses outside the loop (phis) to account for the newly inserted
4098   // edge.
4099   if (!Cost->requiresScalarEpilogue(VF)) {
4100     // Fix-up external users of the induction variables.
4101     for (auto &Entry : Legal->getInductionVars())
4102       fixupIVUsers(Entry.first, Entry.second,
4103                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4104                    IVEndValues[Entry.first], LoopMiddleBlock);
4105 
4106     fixLCSSAPHIs(State);
4107   }
4108 
4109   for (Instruction *PI : PredicatedInstructions)
4110     sinkScalarOperands(&*PI);
4111 
4112   // Remove redundant induction instructions.
4113   cse(LoopVectorBody);
4114 
4115   // Set/update profile weights for the vector and remainder loops as original
4116   // loop iterations are now distributed among them. Note that original loop
4117   // represented by LoopScalarBody becomes remainder loop after vectorization.
4118   //
4119   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4120   // end up getting slightly roughened result but that should be OK since
4121   // profile is not inherently precise anyway. Note also possible bypass of
4122   // vector code caused by legality checks is ignored, assigning all the weight
4123   // to the vector loop, optimistically.
4124   //
4125   // For scalable vectorization we can't know at compile time how many iterations
4126   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4127   // vscale of '1'.
4128   setProfileInfoAfterUnrolling(
4129       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4130       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4131 }
4132 
4133 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4134   // In order to support recurrences we need to be able to vectorize Phi nodes.
4135   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4136   // stage #2: We now need to fix the recurrences by adding incoming edges to
4137   // the currently empty PHI nodes. At this point every instruction in the
4138   // original loop is widened to a vector form so we can use them to construct
4139   // the incoming edges.
4140   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4141   for (VPRecipeBase &R : Header->phis()) {
4142     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
4143       fixReduction(ReductionPhi, State);
4144     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
4145       fixFirstOrderRecurrence(FOR, State);
4146   }
4147 }
4148 
4149 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4150                                                   VPTransformState &State) {
4151   // This is the second phase of vectorizing first-order recurrences. An
4152   // overview of the transformation is described below. Suppose we have the
4153   // following loop.
4154   //
4155   //   for (int i = 0; i < n; ++i)
4156   //     b[i] = a[i] - a[i - 1];
4157   //
4158   // There is a first-order recurrence on "a". For this loop, the shorthand
4159   // scalar IR looks like:
4160   //
4161   //   scalar.ph:
4162   //     s_init = a[-1]
4163   //     br scalar.body
4164   //
4165   //   scalar.body:
4166   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4167   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4168   //     s2 = a[i]
4169   //     b[i] = s2 - s1
4170   //     br cond, scalar.body, ...
4171   //
4172   // In this example, s1 is a recurrence because it's value depends on the
4173   // previous iteration. In the first phase of vectorization, we created a
4174   // vector phi v1 for s1. We now complete the vectorization and produce the
4175   // shorthand vector IR shown below (for VF = 4, UF = 1).
4176   //
4177   //   vector.ph:
4178   //     v_init = vector(..., ..., ..., a[-1])
4179   //     br vector.body
4180   //
4181   //   vector.body
4182   //     i = phi [0, vector.ph], [i+4, vector.body]
4183   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4184   //     v2 = a[i, i+1, i+2, i+3];
4185   //     v3 = vector(v1(3), v2(0, 1, 2))
4186   //     b[i, i+1, i+2, i+3] = v2 - v3
4187   //     br cond, vector.body, middle.block
4188   //
4189   //   middle.block:
4190   //     x = v2(3)
4191   //     br scalar.ph
4192   //
4193   //   scalar.ph:
4194   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4195   //     br scalar.body
4196   //
4197   // After execution completes the vector loop, we extract the next value of
4198   // the recurrence (x) to use as the initial value in the scalar loop.
4199 
4200   // Extract the last vector element in the middle block. This will be the
4201   // initial value for the recurrence when jumping to the scalar loop.
4202   VPValue *PreviousDef = PhiR->getBackedgeValue();
4203   Value *Incoming = State.get(PreviousDef, UF - 1);
4204   auto *ExtractForScalar = Incoming;
4205   auto *IdxTy = Builder.getInt32Ty();
4206   if (VF.isVector()) {
4207     auto *One = ConstantInt::get(IdxTy, 1);
4208     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4209     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4210     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4211     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4212                                                     "vector.recur.extract");
4213   }
4214   // Extract the second last element in the middle block if the
4215   // Phi is used outside the loop. We need to extract the phi itself
4216   // and not the last element (the phi update in the current iteration). This
4217   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4218   // when the scalar loop is not run at all.
4219   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4220   if (VF.isVector()) {
4221     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4222     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4223     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4224         Incoming, Idx, "vector.recur.extract.for.phi");
4225   } else if (UF > 1)
4226     // When loop is unrolled without vectorizing, initialize
4227     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4228     // of `Incoming`. This is analogous to the vectorized case above: extracting
4229     // the second last element when VF > 1.
4230     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4231 
4232   // Fix the initial value of the original recurrence in the scalar loop.
4233   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4234   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4235   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4236   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4237   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4238     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4239     Start->addIncoming(Incoming, BB);
4240   }
4241 
4242   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4243   Phi->setName("scalar.recur");
4244 
4245   // Finally, fix users of the recurrence outside the loop. The users will need
4246   // either the last value of the scalar recurrence or the last value of the
4247   // vector recurrence we extracted in the middle block. Since the loop is in
4248   // LCSSA form, we just need to find all the phi nodes for the original scalar
4249   // recurrence in the exit block, and then add an edge for the middle block.
4250   // Note that LCSSA does not imply single entry when the original scalar loop
4251   // had multiple exiting edges (as we always run the last iteration in the
4252   // scalar epilogue); in that case, there is no edge from middle to exit and
4253   // and thus no phis which needed updated.
4254   if (!Cost->requiresScalarEpilogue(VF))
4255     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4256       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
4257         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4258 }
4259 
4260 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4261                                        VPTransformState &State) {
4262   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4263   // Get it's reduction variable descriptor.
4264   assert(Legal->isReductionVariable(OrigPhi) &&
4265          "Unable to find the reduction variable");
4266   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4267 
4268   RecurKind RK = RdxDesc.getRecurrenceKind();
4269   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4270   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4271   setDebugLocFromInst(ReductionStartValue);
4272 
4273   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
4274   // This is the vector-clone of the value that leaves the loop.
4275   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4276 
4277   // Wrap flags are in general invalid after vectorization, clear them.
4278   clearReductionWrapFlags(RdxDesc, State);
4279 
4280   // Before each round, move the insertion point right between
4281   // the PHIs and the values we are going to write.
4282   // This allows us to write both PHINodes and the extractelement
4283   // instructions.
4284   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4285 
4286   setDebugLocFromInst(LoopExitInst);
4287 
4288   Type *PhiTy = OrigPhi->getType();
4289   // If tail is folded by masking, the vector value to leave the loop should be
4290   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4291   // instead of the former. For an inloop reduction the reduction will already
4292   // be predicated, and does not need to be handled here.
4293   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4294     for (unsigned Part = 0; Part < UF; ++Part) {
4295       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4296       Value *Sel = nullptr;
4297       for (User *U : VecLoopExitInst->users()) {
4298         if (isa<SelectInst>(U)) {
4299           assert(!Sel && "Reduction exit feeding two selects");
4300           Sel = U;
4301         } else
4302           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4303       }
4304       assert(Sel && "Reduction exit feeds no select");
4305       State.reset(LoopExitInstDef, Sel, Part);
4306 
4307       // If the target can create a predicated operator for the reduction at no
4308       // extra cost in the loop (for example a predicated vadd), it can be
4309       // cheaper for the select to remain in the loop than be sunk out of it,
4310       // and so use the select value for the phi instead of the old
4311       // LoopExitValue.
4312       if (PreferPredicatedReductionSelect ||
4313           TTI->preferPredicatedReductionSelect(
4314               RdxDesc.getOpcode(), PhiTy,
4315               TargetTransformInfo::ReductionFlags())) {
4316         auto *VecRdxPhi =
4317             cast<PHINode>(State.get(PhiR, Part));
4318         VecRdxPhi->setIncomingValueForBlock(
4319             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4320       }
4321     }
4322   }
4323 
4324   // If the vector reduction can be performed in a smaller type, we truncate
4325   // then extend the loop exit value to enable InstCombine to evaluate the
4326   // entire expression in the smaller type.
4327   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4328     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4329     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4330     Builder.SetInsertPoint(
4331         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4332     VectorParts RdxParts(UF);
4333     for (unsigned Part = 0; Part < UF; ++Part) {
4334       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4335       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4336       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4337                                         : Builder.CreateZExt(Trunc, VecTy);
4338       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
4339         if (U != Trunc) {
4340           U->replaceUsesOfWith(RdxParts[Part], Extnd);
4341           RdxParts[Part] = Extnd;
4342         }
4343     }
4344     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4345     for (unsigned Part = 0; Part < UF; ++Part) {
4346       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4347       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4348     }
4349   }
4350 
4351   // Reduce all of the unrolled parts into a single vector.
4352   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4353   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4354 
4355   // The middle block terminator has already been assigned a DebugLoc here (the
4356   // OrigLoop's single latch terminator). We want the whole middle block to
4357   // appear to execute on this line because: (a) it is all compiler generated,
4358   // (b) these instructions are always executed after evaluating the latch
4359   // conditional branch, and (c) other passes may add new predecessors which
4360   // terminate on this line. This is the easiest way to ensure we don't
4361   // accidentally cause an extra step back into the loop while debugging.
4362   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4363   if (PhiR->isOrdered())
4364     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4365   else {
4366     // Floating-point operations should have some FMF to enable the reduction.
4367     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4368     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4369     for (unsigned Part = 1; Part < UF; ++Part) {
4370       Value *RdxPart = State.get(LoopExitInstDef, Part);
4371       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4372         ReducedPartRdx = Builder.CreateBinOp(
4373             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4374       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
4375         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
4376                                            ReducedPartRdx, RdxPart);
4377       else
4378         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4379     }
4380   }
4381 
4382   // Create the reduction after the loop. Note that inloop reductions create the
4383   // target reduction in the loop using a Reduction recipe.
4384   if (VF.isVector() && !PhiR->isInLoop()) {
4385     ReducedPartRdx =
4386         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
4387     // If the reduction can be performed in a smaller type, we need to extend
4388     // the reduction to the wider type before we branch to the original loop.
4389     if (PhiTy != RdxDesc.getRecurrenceType())
4390       ReducedPartRdx = RdxDesc.isSigned()
4391                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4392                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4393   }
4394 
4395   // Create a phi node that merges control-flow from the backedge-taken check
4396   // block and the middle block.
4397   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4398                                         LoopScalarPreHeader->getTerminator());
4399   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4400     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4401   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4402 
4403   // Now, we need to fix the users of the reduction variable
4404   // inside and outside of the scalar remainder loop.
4405 
4406   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4407   // in the exit blocks.  See comment on analogous loop in
4408   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4409   if (!Cost->requiresScalarEpilogue(VF))
4410     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4411       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4412         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4413 
4414   // Fix the scalar loop reduction variable with the incoming reduction sum
4415   // from the vector body and from the backedge value.
4416   int IncomingEdgeBlockIdx =
4417       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4418   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4419   // Pick the other block.
4420   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4421   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4422   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4423 }
4424 
4425 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4426                                                   VPTransformState &State) {
4427   RecurKind RK = RdxDesc.getRecurrenceKind();
4428   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4429     return;
4430 
4431   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4432   assert(LoopExitInstr && "null loop exit instruction");
4433   SmallVector<Instruction *, 8> Worklist;
4434   SmallPtrSet<Instruction *, 8> Visited;
4435   Worklist.push_back(LoopExitInstr);
4436   Visited.insert(LoopExitInstr);
4437 
4438   while (!Worklist.empty()) {
4439     Instruction *Cur = Worklist.pop_back_val();
4440     if (isa<OverflowingBinaryOperator>(Cur))
4441       for (unsigned Part = 0; Part < UF; ++Part) {
4442         // FIXME: Should not rely on getVPValue at this point.
4443         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4444         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4445       }
4446 
4447     for (User *U : Cur->users()) {
4448       Instruction *UI = cast<Instruction>(U);
4449       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4450           Visited.insert(UI).second)
4451         Worklist.push_back(UI);
4452     }
4453   }
4454 }
4455 
4456 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4457   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4458     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4459       // Some phis were already hand updated by the reduction and recurrence
4460       // code above, leave them alone.
4461       continue;
4462 
4463     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4464     // Non-instruction incoming values will have only one value.
4465 
4466     VPLane Lane = VPLane::getFirstLane();
4467     if (isa<Instruction>(IncomingValue) &&
4468         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4469                                            VF))
4470       Lane = VPLane::getLastLaneForVF(VF);
4471 
4472     // Can be a loop invariant incoming value or the last scalar value to be
4473     // extracted from the vectorized loop.
4474     // FIXME: Should not rely on getVPValue at this point.
4475     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4476     Value *lastIncomingValue =
4477         OrigLoop->isLoopInvariant(IncomingValue)
4478             ? IncomingValue
4479             : State.get(State.Plan->getVPValue(IncomingValue, true),
4480                         VPIteration(UF - 1, Lane));
4481     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4482   }
4483 }
4484 
4485 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4486   // The basic block and loop containing the predicated instruction.
4487   auto *PredBB = PredInst->getParent();
4488   auto *VectorLoop = LI->getLoopFor(PredBB);
4489 
4490   // Initialize a worklist with the operands of the predicated instruction.
4491   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4492 
4493   // Holds instructions that we need to analyze again. An instruction may be
4494   // reanalyzed if we don't yet know if we can sink it or not.
4495   SmallVector<Instruction *, 8> InstsToReanalyze;
4496 
4497   // Returns true if a given use occurs in the predicated block. Phi nodes use
4498   // their operands in their corresponding predecessor blocks.
4499   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4500     auto *I = cast<Instruction>(U.getUser());
4501     BasicBlock *BB = I->getParent();
4502     if (auto *Phi = dyn_cast<PHINode>(I))
4503       BB = Phi->getIncomingBlock(
4504           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4505     return BB == PredBB;
4506   };
4507 
4508   // Iteratively sink the scalarized operands of the predicated instruction
4509   // into the block we created for it. When an instruction is sunk, it's
4510   // operands are then added to the worklist. The algorithm ends after one pass
4511   // through the worklist doesn't sink a single instruction.
4512   bool Changed;
4513   do {
4514     // Add the instructions that need to be reanalyzed to the worklist, and
4515     // reset the changed indicator.
4516     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4517     InstsToReanalyze.clear();
4518     Changed = false;
4519 
4520     while (!Worklist.empty()) {
4521       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4522 
4523       // We can't sink an instruction if it is a phi node, is not in the loop,
4524       // or may have side effects.
4525       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4526           I->mayHaveSideEffects())
4527         continue;
4528 
4529       // If the instruction is already in PredBB, check if we can sink its
4530       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4531       // sinking the scalar instruction I, hence it appears in PredBB; but it
4532       // may have failed to sink I's operands (recursively), which we try
4533       // (again) here.
4534       if (I->getParent() == PredBB) {
4535         Worklist.insert(I->op_begin(), I->op_end());
4536         continue;
4537       }
4538 
4539       // It's legal to sink the instruction if all its uses occur in the
4540       // predicated block. Otherwise, there's nothing to do yet, and we may
4541       // need to reanalyze the instruction.
4542       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4543         InstsToReanalyze.push_back(I);
4544         continue;
4545       }
4546 
4547       // Move the instruction to the beginning of the predicated block, and add
4548       // it's operands to the worklist.
4549       I->moveBefore(&*PredBB->getFirstInsertionPt());
4550       Worklist.insert(I->op_begin(), I->op_end());
4551 
4552       // The sinking may have enabled other instructions to be sunk, so we will
4553       // need to iterate.
4554       Changed = true;
4555     }
4556   } while (Changed);
4557 }
4558 
4559 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4560   for (PHINode *OrigPhi : OrigPHIsToFix) {
4561     VPWidenPHIRecipe *VPPhi =
4562         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4563     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4564     // Make sure the builder has a valid insert point.
4565     Builder.SetInsertPoint(NewPhi);
4566     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4567       VPValue *Inc = VPPhi->getIncomingValue(i);
4568       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4569       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4570     }
4571   }
4572 }
4573 
4574 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4575   return Cost->useOrderedReductions(RdxDesc);
4576 }
4577 
4578 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4579                                               VPWidenPHIRecipe *PhiR,
4580                                               VPTransformState &State) {
4581   PHINode *P = cast<PHINode>(PN);
4582   if (EnableVPlanNativePath) {
4583     // Currently we enter here in the VPlan-native path for non-induction
4584     // PHIs where all control flow is uniform. We simply widen these PHIs.
4585     // Create a vector phi with no operands - the vector phi operands will be
4586     // set at the end of vector code generation.
4587     Type *VecTy = (State.VF.isScalar())
4588                       ? PN->getType()
4589                       : VectorType::get(PN->getType(), State.VF);
4590     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4591     State.set(PhiR, VecPhi, 0);
4592     OrigPHIsToFix.push_back(P);
4593 
4594     return;
4595   }
4596 
4597   assert(PN->getParent() == OrigLoop->getHeader() &&
4598          "Non-header phis should have been handled elsewhere");
4599 
4600   // In order to support recurrences we need to be able to vectorize Phi nodes.
4601   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4602   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4603   // this value when we vectorize all of the instructions that use the PHI.
4604 
4605   assert(!Legal->isReductionVariable(P) &&
4606          "reductions should be handled elsewhere");
4607 
4608   setDebugLocFromInst(P);
4609 
4610   // This PHINode must be an induction variable.
4611   // Make sure that we know about it.
4612   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4613 
4614   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4615   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4616 
4617   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4618   // which can be found from the original scalar operations.
4619   switch (II.getKind()) {
4620   case InductionDescriptor::IK_NoInduction:
4621     llvm_unreachable("Unknown induction");
4622   case InductionDescriptor::IK_IntInduction:
4623   case InductionDescriptor::IK_FpInduction:
4624     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4625   case InductionDescriptor::IK_PtrInduction: {
4626     // Handle the pointer induction variable case.
4627     assert(P->getType()->isPointerTy() && "Unexpected type.");
4628 
4629     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4630       // This is the normalized GEP that starts counting at zero.
4631       Value *PtrInd =
4632           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4633       // Determine the number of scalars we need to generate for each unroll
4634       // iteration. If the instruction is uniform, we only need to generate the
4635       // first lane. Otherwise, we generate all VF values.
4636       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4637       assert((IsUniform || !State.VF.isScalable()) &&
4638              "Cannot scalarize a scalable VF");
4639       unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
4640 
4641       for (unsigned Part = 0; Part < UF; ++Part) {
4642         Value *PartStart =
4643             createStepForVF(Builder, PtrInd->getType(), VF, Part);
4644 
4645         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4646           Value *Idx = Builder.CreateAdd(
4647               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4648           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4649           Value *SclrGep =
4650               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4651           SclrGep->setName("next.gep");
4652           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4653         }
4654       }
4655       return;
4656     }
4657     assert(isa<SCEVConstant>(II.getStep()) &&
4658            "Induction step not a SCEV constant!");
4659     Type *PhiType = II.getStep()->getType();
4660 
4661     // Build a pointer phi
4662     Value *ScalarStartValue = II.getStartValue();
4663     Type *ScStValueType = ScalarStartValue->getType();
4664     PHINode *NewPointerPhi =
4665         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4666     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4667 
4668     // A pointer induction, performed by using a gep
4669     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4670     Instruction *InductionLoc = LoopLatch->getTerminator();
4671     const SCEV *ScalarStep = II.getStep();
4672     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4673     Value *ScalarStepValue =
4674         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4675     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4676     Value *NumUnrolledElems =
4677         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4678     Value *InductionGEP = GetElementPtrInst::Create(
4679         II.getElementType(), NewPointerPhi,
4680         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4681         InductionLoc);
4682     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4683 
4684     // Create UF many actual address geps that use the pointer
4685     // phi as base and a vectorized version of the step value
4686     // (<step*0, ..., step*N>) as offset.
4687     for (unsigned Part = 0; Part < State.UF; ++Part) {
4688       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4689       Value *StartOffsetScalar =
4690           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4691       Value *StartOffset =
4692           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4693       // Create a vector of consecutive numbers from zero to VF.
4694       StartOffset =
4695           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4696 
4697       Value *GEP = Builder.CreateGEP(
4698           II.getElementType(), NewPointerPhi,
4699           Builder.CreateMul(
4700               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4701               "vector.gep"));
4702       State.set(PhiR, GEP, Part);
4703     }
4704   }
4705   }
4706 }
4707 
4708 /// A helper function for checking whether an integer division-related
4709 /// instruction may divide by zero (in which case it must be predicated if
4710 /// executed conditionally in the scalar code).
4711 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4712 /// Non-zero divisors that are non compile-time constants will not be
4713 /// converted into multiplication, so we will still end up scalarizing
4714 /// the division, but can do so w/o predication.
4715 static bool mayDivideByZero(Instruction &I) {
4716   assert((I.getOpcode() == Instruction::UDiv ||
4717           I.getOpcode() == Instruction::SDiv ||
4718           I.getOpcode() == Instruction::URem ||
4719           I.getOpcode() == Instruction::SRem) &&
4720          "Unexpected instruction");
4721   Value *Divisor = I.getOperand(1);
4722   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4723   return !CInt || CInt->isZero();
4724 }
4725 
4726 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4727                                                VPUser &ArgOperands,
4728                                                VPTransformState &State) {
4729   assert(!isa<DbgInfoIntrinsic>(I) &&
4730          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4731   setDebugLocFromInst(&I);
4732 
4733   Module *M = I.getParent()->getParent()->getParent();
4734   auto *CI = cast<CallInst>(&I);
4735 
4736   SmallVector<Type *, 4> Tys;
4737   for (Value *ArgOperand : CI->args())
4738     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4739 
4740   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4741 
4742   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4743   // version of the instruction.
4744   // Is it beneficial to perform intrinsic call compared to lib call?
4745   bool NeedToScalarize = false;
4746   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4747   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4748   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4749   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4750          "Instruction should be scalarized elsewhere.");
4751   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4752          "Either the intrinsic cost or vector call cost must be valid");
4753 
4754   for (unsigned Part = 0; Part < UF; ++Part) {
4755     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4756     SmallVector<Value *, 4> Args;
4757     for (auto &I : enumerate(ArgOperands.operands())) {
4758       // Some intrinsics have a scalar argument - don't replace it with a
4759       // vector.
4760       Value *Arg;
4761       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
4762         Arg = State.get(I.value(), Part);
4763       else {
4764         Arg = State.get(I.value(), VPIteration(0, 0));
4765         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
4766           TysForDecl.push_back(Arg->getType());
4767       }
4768       Args.push_back(Arg);
4769     }
4770 
4771     Function *VectorF;
4772     if (UseVectorIntrinsic) {
4773       // Use vector version of the intrinsic.
4774       if (VF.isVector())
4775         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4776       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4777       assert(VectorF && "Can't retrieve vector intrinsic.");
4778     } else {
4779       // Use vector version of the function call.
4780       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4781 #ifndef NDEBUG
4782       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4783              "Can't create vector function.");
4784 #endif
4785         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4786     }
4787       SmallVector<OperandBundleDef, 1> OpBundles;
4788       CI->getOperandBundlesAsDefs(OpBundles);
4789       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4790 
4791       if (isa<FPMathOperator>(V))
4792         V->copyFastMathFlags(CI);
4793 
4794       State.set(Def, V, Part);
4795       addMetadata(V, &I);
4796   }
4797 }
4798 
4799 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4800   // We should not collect Scalars more than once per VF. Right now, this
4801   // function is called from collectUniformsAndScalars(), which already does
4802   // this check. Collecting Scalars for VF=1 does not make any sense.
4803   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4804          "This function should not be visited twice for the same VF");
4805 
4806   SmallSetVector<Instruction *, 8> Worklist;
4807 
4808   // These sets are used to seed the analysis with pointers used by memory
4809   // accesses that will remain scalar.
4810   SmallSetVector<Instruction *, 8> ScalarPtrs;
4811   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4812   auto *Latch = TheLoop->getLoopLatch();
4813 
4814   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4815   // The pointer operands of loads and stores will be scalar as long as the
4816   // memory access is not a gather or scatter operation. The value operand of a
4817   // store will remain scalar if the store is scalarized.
4818   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4819     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4820     assert(WideningDecision != CM_Unknown &&
4821            "Widening decision should be ready at this moment");
4822     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4823       if (Ptr == Store->getValueOperand())
4824         return WideningDecision == CM_Scalarize;
4825     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4826            "Ptr is neither a value or pointer operand");
4827     return WideningDecision != CM_GatherScatter;
4828   };
4829 
4830   // A helper that returns true if the given value is a bitcast or
4831   // getelementptr instruction contained in the loop.
4832   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4833     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4834             isa<GetElementPtrInst>(V)) &&
4835            !TheLoop->isLoopInvariant(V);
4836   };
4837 
4838   // A helper that evaluates a memory access's use of a pointer. If the use will
4839   // be a scalar use and the pointer is only used by memory accesses, we place
4840   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4841   // PossibleNonScalarPtrs.
4842   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4843     // We only care about bitcast and getelementptr instructions contained in
4844     // the loop.
4845     if (!isLoopVaryingBitCastOrGEP(Ptr))
4846       return;
4847 
4848     // If the pointer has already been identified as scalar (e.g., if it was
4849     // also identified as uniform), there's nothing to do.
4850     auto *I = cast<Instruction>(Ptr);
4851     if (Worklist.count(I))
4852       return;
4853 
4854     // If the use of the pointer will be a scalar use, and all users of the
4855     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4856     // place the pointer in PossibleNonScalarPtrs.
4857     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4858           return isa<LoadInst>(U) || isa<StoreInst>(U);
4859         }))
4860       ScalarPtrs.insert(I);
4861     else
4862       PossibleNonScalarPtrs.insert(I);
4863   };
4864 
4865   // We seed the scalars analysis with three classes of instructions: (1)
4866   // instructions marked uniform-after-vectorization and (2) bitcast,
4867   // getelementptr and (pointer) phi instructions used by memory accesses
4868   // requiring a scalar use.
4869   //
4870   // (1) Add to the worklist all instructions that have been identified as
4871   // uniform-after-vectorization.
4872   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4873 
4874   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4875   // memory accesses requiring a scalar use. The pointer operands of loads and
4876   // stores will be scalar as long as the memory accesses is not a gather or
4877   // scatter operation. The value operand of a store will remain scalar if the
4878   // store is scalarized.
4879   for (auto *BB : TheLoop->blocks())
4880     for (auto &I : *BB) {
4881       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4882         evaluatePtrUse(Load, Load->getPointerOperand());
4883       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4884         evaluatePtrUse(Store, Store->getPointerOperand());
4885         evaluatePtrUse(Store, Store->getValueOperand());
4886       }
4887     }
4888   for (auto *I : ScalarPtrs)
4889     if (!PossibleNonScalarPtrs.count(I)) {
4890       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4891       Worklist.insert(I);
4892     }
4893 
4894   // Insert the forced scalars.
4895   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4896   // induction variable when the PHI user is scalarized.
4897   auto ForcedScalar = ForcedScalars.find(VF);
4898   if (ForcedScalar != ForcedScalars.end())
4899     for (auto *I : ForcedScalar->second)
4900       Worklist.insert(I);
4901 
4902   // Expand the worklist by looking through any bitcasts and getelementptr
4903   // instructions we've already identified as scalar. This is similar to the
4904   // expansion step in collectLoopUniforms(); however, here we're only
4905   // expanding to include additional bitcasts and getelementptr instructions.
4906   unsigned Idx = 0;
4907   while (Idx != Worklist.size()) {
4908     Instruction *Dst = Worklist[Idx++];
4909     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4910       continue;
4911     auto *Src = cast<Instruction>(Dst->getOperand(0));
4912     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4913           auto *J = cast<Instruction>(U);
4914           return !TheLoop->contains(J) || Worklist.count(J) ||
4915                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4916                   isScalarUse(J, Src));
4917         })) {
4918       Worklist.insert(Src);
4919       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4920     }
4921   }
4922 
4923   // An induction variable will remain scalar if all users of the induction
4924   // variable and induction variable update remain scalar.
4925   for (auto &Induction : Legal->getInductionVars()) {
4926     auto *Ind = Induction.first;
4927     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4928 
4929     // If tail-folding is applied, the primary induction variable will be used
4930     // to feed a vector compare.
4931     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4932       continue;
4933 
4934     // Returns true if \p Indvar is a pointer induction that is used directly by
4935     // load/store instruction \p I.
4936     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4937                                               Instruction *I) {
4938       return Induction.second.getKind() ==
4939                  InductionDescriptor::IK_PtrInduction &&
4940              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4941              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4942     };
4943 
4944     // Determine if all users of the induction variable are scalar after
4945     // vectorization.
4946     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4947       auto *I = cast<Instruction>(U);
4948       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4949              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4950     });
4951     if (!ScalarInd)
4952       continue;
4953 
4954     // Determine if all users of the induction variable update instruction are
4955     // scalar after vectorization.
4956     auto ScalarIndUpdate =
4957         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4958           auto *I = cast<Instruction>(U);
4959           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4960                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4961         });
4962     if (!ScalarIndUpdate)
4963       continue;
4964 
4965     // The induction variable and its update instruction will remain scalar.
4966     Worklist.insert(Ind);
4967     Worklist.insert(IndUpdate);
4968     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4969     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4970                       << "\n");
4971   }
4972 
4973   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4974 }
4975 
4976 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
4977   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4978     return false;
4979   switch(I->getOpcode()) {
4980   default:
4981     break;
4982   case Instruction::Load:
4983   case Instruction::Store: {
4984     if (!Legal->isMaskRequired(I))
4985       return false;
4986     auto *Ptr = getLoadStorePointerOperand(I);
4987     auto *Ty = getLoadStoreType(I);
4988     const Align Alignment = getLoadStoreAlignment(I);
4989     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4990                                 TTI.isLegalMaskedGather(Ty, Alignment))
4991                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4992                                 TTI.isLegalMaskedScatter(Ty, Alignment));
4993   }
4994   case Instruction::UDiv:
4995   case Instruction::SDiv:
4996   case Instruction::SRem:
4997   case Instruction::URem:
4998     return mayDivideByZero(*I);
4999   }
5000   return false;
5001 }
5002 
5003 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5004     Instruction *I, ElementCount VF) {
5005   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5006   assert(getWideningDecision(I, VF) == CM_Unknown &&
5007          "Decision should not be set yet.");
5008   auto *Group = getInterleavedAccessGroup(I);
5009   assert(Group && "Must have a group.");
5010 
5011   // If the instruction's allocated size doesn't equal it's type size, it
5012   // requires padding and will be scalarized.
5013   auto &DL = I->getModule()->getDataLayout();
5014   auto *ScalarTy = getLoadStoreType(I);
5015   if (hasIrregularType(ScalarTy, DL))
5016     return false;
5017 
5018   // Check if masking is required.
5019   // A Group may need masking for one of two reasons: it resides in a block that
5020   // needs predication, or it was decided to use masking to deal with gaps
5021   // (either a gap at the end of a load-access that may result in a speculative
5022   // load, or any gaps in a store-access).
5023   bool PredicatedAccessRequiresMasking =
5024       blockNeedsPredicationForAnyReason(I->getParent()) &&
5025       Legal->isMaskRequired(I);
5026   bool LoadAccessWithGapsRequiresEpilogMasking =
5027       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
5028       !isScalarEpilogueAllowed();
5029   bool StoreAccessWithGapsRequiresMasking =
5030       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
5031   if (!PredicatedAccessRequiresMasking &&
5032       !LoadAccessWithGapsRequiresEpilogMasking &&
5033       !StoreAccessWithGapsRequiresMasking)
5034     return true;
5035 
5036   // If masked interleaving is required, we expect that the user/target had
5037   // enabled it, because otherwise it either wouldn't have been created or
5038   // it should have been invalidated by the CostModel.
5039   assert(useMaskedInterleavedAccesses(TTI) &&
5040          "Masked interleave-groups for predicated accesses are not enabled.");
5041 
5042   if (Group->isReverse())
5043     return false;
5044 
5045   auto *Ty = getLoadStoreType(I);
5046   const Align Alignment = getLoadStoreAlignment(I);
5047   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5048                           : TTI.isLegalMaskedStore(Ty, Alignment);
5049 }
5050 
5051 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5052     Instruction *I, ElementCount VF) {
5053   // Get and ensure we have a valid memory instruction.
5054   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
5055 
5056   auto *Ptr = getLoadStorePointerOperand(I);
5057   auto *ScalarTy = getLoadStoreType(I);
5058 
5059   // In order to be widened, the pointer should be consecutive, first of all.
5060   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
5061     return false;
5062 
5063   // If the instruction is a store located in a predicated block, it will be
5064   // scalarized.
5065   if (isScalarWithPredication(I))
5066     return false;
5067 
5068   // If the instruction's allocated size doesn't equal it's type size, it
5069   // requires padding and will be scalarized.
5070   auto &DL = I->getModule()->getDataLayout();
5071   if (hasIrregularType(ScalarTy, DL))
5072     return false;
5073 
5074   return true;
5075 }
5076 
5077 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5078   // We should not collect Uniforms more than once per VF. Right now,
5079   // this function is called from collectUniformsAndScalars(), which
5080   // already does this check. Collecting Uniforms for VF=1 does not make any
5081   // sense.
5082 
5083   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5084          "This function should not be visited twice for the same VF");
5085 
5086   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5087   // not analyze again.  Uniforms.count(VF) will return 1.
5088   Uniforms[VF].clear();
5089 
5090   // We now know that the loop is vectorizable!
5091   // Collect instructions inside the loop that will remain uniform after
5092   // vectorization.
5093 
5094   // Global values, params and instructions outside of current loop are out of
5095   // scope.
5096   auto isOutOfScope = [&](Value *V) -> bool {
5097     Instruction *I = dyn_cast<Instruction>(V);
5098     return (!I || !TheLoop->contains(I));
5099   };
5100 
5101   // Worklist containing uniform instructions demanding lane 0.
5102   SetVector<Instruction *> Worklist;
5103   BasicBlock *Latch = TheLoop->getLoopLatch();
5104 
5105   // Add uniform instructions demanding lane 0 to the worklist. Instructions
5106   // that are scalar with predication must not be considered uniform after
5107   // vectorization, because that would create an erroneous replicating region
5108   // where only a single instance out of VF should be formed.
5109   // TODO: optimize such seldom cases if found important, see PR40816.
5110   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5111     if (isOutOfScope(I)) {
5112       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5113                         << *I << "\n");
5114       return;
5115     }
5116     if (isScalarWithPredication(I)) {
5117       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5118                         << *I << "\n");
5119       return;
5120     }
5121     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5122     Worklist.insert(I);
5123   };
5124 
5125   // Start with the conditional branch. If the branch condition is an
5126   // instruction contained in the loop that is only used by the branch, it is
5127   // uniform.
5128   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5129   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5130     addToWorklistIfAllowed(Cmp);
5131 
5132   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5133     InstWidening WideningDecision = getWideningDecision(I, VF);
5134     assert(WideningDecision != CM_Unknown &&
5135            "Widening decision should be ready at this moment");
5136 
5137     // A uniform memory op is itself uniform.  We exclude uniform stores
5138     // here as they demand the last lane, not the first one.
5139     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5140       assert(WideningDecision == CM_Scalarize);
5141       return true;
5142     }
5143 
5144     return (WideningDecision == CM_Widen ||
5145             WideningDecision == CM_Widen_Reverse ||
5146             WideningDecision == CM_Interleave);
5147   };
5148 
5149 
5150   // Returns true if Ptr is the pointer operand of a memory access instruction
5151   // I, and I is known to not require scalarization.
5152   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5153     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5154   };
5155 
5156   // Holds a list of values which are known to have at least one uniform use.
5157   // Note that there may be other uses which aren't uniform.  A "uniform use"
5158   // here is something which only demands lane 0 of the unrolled iterations;
5159   // it does not imply that all lanes produce the same value (e.g. this is not
5160   // the usual meaning of uniform)
5161   SetVector<Value *> HasUniformUse;
5162 
5163   // Scan the loop for instructions which are either a) known to have only
5164   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5165   for (auto *BB : TheLoop->blocks())
5166     for (auto &I : *BB) {
5167       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
5168         switch (II->getIntrinsicID()) {
5169         case Intrinsic::sideeffect:
5170         case Intrinsic::experimental_noalias_scope_decl:
5171         case Intrinsic::assume:
5172         case Intrinsic::lifetime_start:
5173         case Intrinsic::lifetime_end:
5174           if (TheLoop->hasLoopInvariantOperands(&I))
5175             addToWorklistIfAllowed(&I);
5176           break;
5177         default:
5178           break;
5179         }
5180       }
5181 
5182       // ExtractValue instructions must be uniform, because the operands are
5183       // known to be loop-invariant.
5184       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
5185         assert(isOutOfScope(EVI->getAggregateOperand()) &&
5186                "Expected aggregate value to be loop invariant");
5187         addToWorklistIfAllowed(EVI);
5188         continue;
5189       }
5190 
5191       // If there's no pointer operand, there's nothing to do.
5192       auto *Ptr = getLoadStorePointerOperand(&I);
5193       if (!Ptr)
5194         continue;
5195 
5196       // A uniform memory op is itself uniform.  We exclude uniform stores
5197       // here as they demand the last lane, not the first one.
5198       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5199         addToWorklistIfAllowed(&I);
5200 
5201       if (isUniformDecision(&I, VF)) {
5202         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5203         HasUniformUse.insert(Ptr);
5204       }
5205     }
5206 
5207   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5208   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5209   // disallows uses outside the loop as well.
5210   for (auto *V : HasUniformUse) {
5211     if (isOutOfScope(V))
5212       continue;
5213     auto *I = cast<Instruction>(V);
5214     auto UsersAreMemAccesses =
5215       llvm::all_of(I->users(), [&](User *U) -> bool {
5216         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5217       });
5218     if (UsersAreMemAccesses)
5219       addToWorklistIfAllowed(I);
5220   }
5221 
5222   // Expand Worklist in topological order: whenever a new instruction
5223   // is added , its users should be already inside Worklist.  It ensures
5224   // a uniform instruction will only be used by uniform instructions.
5225   unsigned idx = 0;
5226   while (idx != Worklist.size()) {
5227     Instruction *I = Worklist[idx++];
5228 
5229     for (auto OV : I->operand_values()) {
5230       // isOutOfScope operands cannot be uniform instructions.
5231       if (isOutOfScope(OV))
5232         continue;
5233       // First order recurrence Phi's should typically be considered
5234       // non-uniform.
5235       auto *OP = dyn_cast<PHINode>(OV);
5236       if (OP && Legal->isFirstOrderRecurrence(OP))
5237         continue;
5238       // If all the users of the operand are uniform, then add the
5239       // operand into the uniform worklist.
5240       auto *OI = cast<Instruction>(OV);
5241       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5242             auto *J = cast<Instruction>(U);
5243             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5244           }))
5245         addToWorklistIfAllowed(OI);
5246     }
5247   }
5248 
5249   // For an instruction to be added into Worklist above, all its users inside
5250   // the loop should also be in Worklist. However, this condition cannot be
5251   // true for phi nodes that form a cyclic dependence. We must process phi
5252   // nodes separately. An induction variable will remain uniform if all users
5253   // of the induction variable and induction variable update remain uniform.
5254   // The code below handles both pointer and non-pointer induction variables.
5255   for (auto &Induction : Legal->getInductionVars()) {
5256     auto *Ind = Induction.first;
5257     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5258 
5259     // Determine if all users of the induction variable are uniform after
5260     // vectorization.
5261     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5262       auto *I = cast<Instruction>(U);
5263       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5264              isVectorizedMemAccessUse(I, Ind);
5265     });
5266     if (!UniformInd)
5267       continue;
5268 
5269     // Determine if all users of the induction variable update instruction are
5270     // uniform after vectorization.
5271     auto UniformIndUpdate =
5272         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5273           auto *I = cast<Instruction>(U);
5274           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5275                  isVectorizedMemAccessUse(I, IndUpdate);
5276         });
5277     if (!UniformIndUpdate)
5278       continue;
5279 
5280     // The induction variable and its update instruction will remain uniform.
5281     addToWorklistIfAllowed(Ind);
5282     addToWorklistIfAllowed(IndUpdate);
5283   }
5284 
5285   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5286 }
5287 
5288 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5289   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5290 
5291   if (Legal->getRuntimePointerChecking()->Need) {
5292     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5293         "runtime pointer checks needed. Enable vectorization of this "
5294         "loop with '#pragma clang loop vectorize(enable)' when "
5295         "compiling with -Os/-Oz",
5296         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5297     return true;
5298   }
5299 
5300   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5301     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5302         "runtime SCEV checks needed. Enable vectorization of this "
5303         "loop with '#pragma clang loop vectorize(enable)' when "
5304         "compiling with -Os/-Oz",
5305         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5306     return true;
5307   }
5308 
5309   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5310   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5311     reportVectorizationFailure("Runtime stride check for small trip count",
5312         "runtime stride == 1 checks needed. Enable vectorization of "
5313         "this loop without such check by compiling with -Os/-Oz",
5314         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5315     return true;
5316   }
5317 
5318   return false;
5319 }
5320 
5321 ElementCount
5322 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5323   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
5324     return ElementCount::getScalable(0);
5325 
5326   if (Hints->isScalableVectorizationDisabled()) {
5327     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5328                             "ScalableVectorizationDisabled", ORE, TheLoop);
5329     return ElementCount::getScalable(0);
5330   }
5331 
5332   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
5333 
5334   auto MaxScalableVF = ElementCount::getScalable(
5335       std::numeric_limits<ElementCount::ScalarTy>::max());
5336 
5337   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5338   // FIXME: While for scalable vectors this is currently sufficient, this should
5339   // be replaced by a more detailed mechanism that filters out specific VFs,
5340   // instead of invalidating vectorization for a whole set of VFs based on the
5341   // MaxVF.
5342 
5343   // Disable scalable vectorization if the loop contains unsupported reductions.
5344   if (!canVectorizeReductions(MaxScalableVF)) {
5345     reportVectorizationInfo(
5346         "Scalable vectorization not supported for the reduction "
5347         "operations found in this loop.",
5348         "ScalableVFUnfeasible", ORE, TheLoop);
5349     return ElementCount::getScalable(0);
5350   }
5351 
5352   // Disable scalable vectorization if the loop contains any instructions
5353   // with element types not supported for scalable vectors.
5354   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5355         return !Ty->isVoidTy() &&
5356                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5357       })) {
5358     reportVectorizationInfo("Scalable vectorization is not supported "
5359                             "for all element types found in this loop.",
5360                             "ScalableVFUnfeasible", ORE, TheLoop);
5361     return ElementCount::getScalable(0);
5362   }
5363 
5364   if (Legal->isSafeForAnyVectorWidth())
5365     return MaxScalableVF;
5366 
5367   // Limit MaxScalableVF by the maximum safe dependence distance.
5368   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5369   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5370     unsigned VScaleMax = TheFunction->getFnAttribute(Attribute::VScaleRange)
5371                              .getVScaleRangeArgs()
5372                              .second;
5373     if (VScaleMax > 0)
5374       MaxVScale = VScaleMax;
5375   }
5376   MaxScalableVF = ElementCount::getScalable(
5377       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5378   if (!MaxScalableVF)
5379     reportVectorizationInfo(
5380         "Max legal vector width too small, scalable vectorization "
5381         "unfeasible.",
5382         "ScalableVFUnfeasible", ORE, TheLoop);
5383 
5384   return MaxScalableVF;
5385 }
5386 
5387 FixedScalableVFPair
5388 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5389                                                  ElementCount UserVF) {
5390   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5391   unsigned SmallestType, WidestType;
5392   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5393 
5394   // Get the maximum safe dependence distance in bits computed by LAA.
5395   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5396   // the memory accesses that is most restrictive (involved in the smallest
5397   // dependence distance).
5398   unsigned MaxSafeElements =
5399       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5400 
5401   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5402   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5403 
5404   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5405                     << ".\n");
5406   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5407                     << ".\n");
5408 
5409   // First analyze the UserVF, fall back if the UserVF should be ignored.
5410   if (UserVF) {
5411     auto MaxSafeUserVF =
5412         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5413 
5414     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
5415       // If `VF=vscale x N` is safe, then so is `VF=N`
5416       if (UserVF.isScalable())
5417         return FixedScalableVFPair(
5418             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
5419       else
5420         return UserVF;
5421     }
5422 
5423     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5424 
5425     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5426     // is better to ignore the hint and let the compiler choose a suitable VF.
5427     if (!UserVF.isScalable()) {
5428       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5429                         << " is unsafe, clamping to max safe VF="
5430                         << MaxSafeFixedVF << ".\n");
5431       ORE->emit([&]() {
5432         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5433                                           TheLoop->getStartLoc(),
5434                                           TheLoop->getHeader())
5435                << "User-specified vectorization factor "
5436                << ore::NV("UserVectorizationFactor", UserVF)
5437                << " is unsafe, clamping to maximum safe vectorization factor "
5438                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5439       });
5440       return MaxSafeFixedVF;
5441     }
5442 
5443     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5444       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5445                         << " is ignored because scalable vectors are not "
5446                            "available.\n");
5447       ORE->emit([&]() {
5448         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5449                                           TheLoop->getStartLoc(),
5450                                           TheLoop->getHeader())
5451                << "User-specified vectorization factor "
5452                << ore::NV("UserVectorizationFactor", UserVF)
5453                << " is ignored because the target does not support scalable "
5454                   "vectors. The compiler will pick a more suitable value.";
5455       });
5456     } else {
5457       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5458                         << " is unsafe. Ignoring scalable UserVF.\n");
5459       ORE->emit([&]() {
5460         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5461                                           TheLoop->getStartLoc(),
5462                                           TheLoop->getHeader())
5463                << "User-specified vectorization factor "
5464                << ore::NV("UserVectorizationFactor", UserVF)
5465                << " is unsafe. Ignoring the hint to let the compiler pick a "
5466                   "more suitable value.";
5467       });
5468     }
5469   }
5470 
5471   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5472                     << " / " << WidestType << " bits.\n");
5473 
5474   FixedScalableVFPair Result(ElementCount::getFixed(1),
5475                              ElementCount::getScalable(0));
5476   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5477                                            WidestType, MaxSafeFixedVF))
5478     Result.FixedVF = MaxVF;
5479 
5480   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5481                                            WidestType, MaxSafeScalableVF))
5482     if (MaxVF.isScalable()) {
5483       Result.ScalableVF = MaxVF;
5484       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5485                         << "\n");
5486     }
5487 
5488   return Result;
5489 }
5490 
5491 FixedScalableVFPair
5492 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5493   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5494     // TODO: It may by useful to do since it's still likely to be dynamically
5495     // uniform if the target can skip.
5496     reportVectorizationFailure(
5497         "Not inserting runtime ptr check for divergent target",
5498         "runtime pointer checks needed. Not enabled for divergent target",
5499         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5500     return FixedScalableVFPair::getNone();
5501   }
5502 
5503   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5504   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5505   if (TC == 1) {
5506     reportVectorizationFailure("Single iteration (non) loop",
5507         "loop trip count is one, irrelevant for vectorization",
5508         "SingleIterationLoop", ORE, TheLoop);
5509     return FixedScalableVFPair::getNone();
5510   }
5511 
5512   switch (ScalarEpilogueStatus) {
5513   case CM_ScalarEpilogueAllowed:
5514     return computeFeasibleMaxVF(TC, UserVF);
5515   case CM_ScalarEpilogueNotAllowedUsePredicate:
5516     LLVM_FALLTHROUGH;
5517   case CM_ScalarEpilogueNotNeededUsePredicate:
5518     LLVM_DEBUG(
5519         dbgs() << "LV: vector predicate hint/switch found.\n"
5520                << "LV: Not allowing scalar epilogue, creating predicated "
5521                << "vector loop.\n");
5522     break;
5523   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5524     // fallthrough as a special case of OptForSize
5525   case CM_ScalarEpilogueNotAllowedOptSize:
5526     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5527       LLVM_DEBUG(
5528           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5529     else
5530       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5531                         << "count.\n");
5532 
5533     // Bail if runtime checks are required, which are not good when optimising
5534     // for size.
5535     if (runtimeChecksRequired())
5536       return FixedScalableVFPair::getNone();
5537 
5538     break;
5539   }
5540 
5541   // The only loops we can vectorize without a scalar epilogue, are loops with
5542   // a bottom-test and a single exiting block. We'd have to handle the fact
5543   // that not every instruction executes on the last iteration.  This will
5544   // require a lane mask which varies through the vector loop body.  (TODO)
5545   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5546     // If there was a tail-folding hint/switch, but we can't fold the tail by
5547     // masking, fallback to a vectorization with a scalar epilogue.
5548     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5549       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5550                            "scalar epilogue instead.\n");
5551       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5552       return computeFeasibleMaxVF(TC, UserVF);
5553     }
5554     return FixedScalableVFPair::getNone();
5555   }
5556 
5557   // Now try the tail folding
5558 
5559   // Invalidate interleave groups that require an epilogue if we can't mask
5560   // the interleave-group.
5561   if (!useMaskedInterleavedAccesses(TTI)) {
5562     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5563            "No decisions should have been taken at this point");
5564     // Note: There is no need to invalidate any cost modeling decisions here, as
5565     // non where taken so far.
5566     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5567   }
5568 
5569   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5570   // Avoid tail folding if the trip count is known to be a multiple of any VF
5571   // we chose.
5572   // FIXME: The condition below pessimises the case for fixed-width vectors,
5573   // when scalable VFs are also candidates for vectorization.
5574   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5575     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5576     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5577            "MaxFixedVF must be a power of 2");
5578     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5579                                    : MaxFixedVF.getFixedValue();
5580     ScalarEvolution *SE = PSE.getSE();
5581     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5582     const SCEV *ExitCount = SE->getAddExpr(
5583         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5584     const SCEV *Rem = SE->getURemExpr(
5585         SE->applyLoopGuards(ExitCount, TheLoop),
5586         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5587     if (Rem->isZero()) {
5588       // Accept MaxFixedVF if we do not have a tail.
5589       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5590       return MaxFactors;
5591     }
5592   }
5593 
5594   // For scalable vectors, don't use tail folding as this is currently not yet
5595   // supported. The code is likely to have ended up here if the tripcount is
5596   // low, in which case it makes sense not to use scalable vectors.
5597   if (MaxFactors.ScalableVF.isVector())
5598     MaxFactors.ScalableVF = ElementCount::getScalable(0);
5599 
5600   // If we don't know the precise trip count, or if the trip count that we
5601   // found modulo the vectorization factor is not zero, try to fold the tail
5602   // by masking.
5603   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5604   if (Legal->prepareToFoldTailByMasking()) {
5605     FoldTailByMasking = true;
5606     return MaxFactors;
5607   }
5608 
5609   // If there was a tail-folding hint/switch, but we can't fold the tail by
5610   // masking, fallback to a vectorization with a scalar epilogue.
5611   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5612     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5613                          "scalar epilogue instead.\n");
5614     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5615     return MaxFactors;
5616   }
5617 
5618   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5619     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5620     return FixedScalableVFPair::getNone();
5621   }
5622 
5623   if (TC == 0) {
5624     reportVectorizationFailure(
5625         "Unable to calculate the loop count due to complex control flow",
5626         "unable to calculate the loop count due to complex control flow",
5627         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5628     return FixedScalableVFPair::getNone();
5629   }
5630 
5631   reportVectorizationFailure(
5632       "Cannot optimize for size and vectorize at the same time.",
5633       "cannot optimize for size and vectorize at the same time. "
5634       "Enable vectorization of this loop with '#pragma clang loop "
5635       "vectorize(enable)' when compiling with -Os/-Oz",
5636       "NoTailLoopWithOptForSize", ORE, TheLoop);
5637   return FixedScalableVFPair::getNone();
5638 }
5639 
5640 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5641     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5642     const ElementCount &MaxSafeVF) {
5643   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5644   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5645       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5646                            : TargetTransformInfo::RGK_FixedWidthVector);
5647 
5648   // Convenience function to return the minimum of two ElementCounts.
5649   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5650     assert((LHS.isScalable() == RHS.isScalable()) &&
5651            "Scalable flags must match");
5652     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5653   };
5654 
5655   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5656   // Note that both WidestRegister and WidestType may not be a powers of 2.
5657   auto MaxVectorElementCount = ElementCount::get(
5658       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5659       ComputeScalableMaxVF);
5660   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5661   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5662                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5663 
5664   if (!MaxVectorElementCount) {
5665     LLVM_DEBUG(dbgs() << "LV: The target has no "
5666                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5667                       << " vector registers.\n");
5668     return ElementCount::getFixed(1);
5669   }
5670 
5671   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5672   if (ConstTripCount &&
5673       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5674       isPowerOf2_32(ConstTripCount)) {
5675     // We need to clamp the VF to be the ConstTripCount. There is no point in
5676     // choosing a higher viable VF as done in the loop below. If
5677     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5678     // the TC is less than or equal to the known number of lanes.
5679     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5680                       << ConstTripCount << "\n");
5681     return TripCountEC;
5682   }
5683 
5684   ElementCount MaxVF = MaxVectorElementCount;
5685   if (TTI.shouldMaximizeVectorBandwidth() ||
5686       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5687     auto MaxVectorElementCountMaxBW = ElementCount::get(
5688         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5689         ComputeScalableMaxVF);
5690     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5691 
5692     // Collect all viable vectorization factors larger than the default MaxVF
5693     // (i.e. MaxVectorElementCount).
5694     SmallVector<ElementCount, 8> VFs;
5695     for (ElementCount VS = MaxVectorElementCount * 2;
5696          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5697       VFs.push_back(VS);
5698 
5699     // For each VF calculate its register usage.
5700     auto RUs = calculateRegisterUsage(VFs);
5701 
5702     // Select the largest VF which doesn't require more registers than existing
5703     // ones.
5704     for (int i = RUs.size() - 1; i >= 0; --i) {
5705       bool Selected = true;
5706       for (auto &pair : RUs[i].MaxLocalUsers) {
5707         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5708         if (pair.second > TargetNumRegisters)
5709           Selected = false;
5710       }
5711       if (Selected) {
5712         MaxVF = VFs[i];
5713         break;
5714       }
5715     }
5716     if (ElementCount MinVF =
5717             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5718       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5719         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5720                           << ") with target's minimum: " << MinVF << '\n');
5721         MaxVF = MinVF;
5722       }
5723     }
5724   }
5725   return MaxVF;
5726 }
5727 
5728 bool LoopVectorizationCostModel::isMoreProfitable(
5729     const VectorizationFactor &A, const VectorizationFactor &B) const {
5730   InstructionCost CostA = A.Cost;
5731   InstructionCost CostB = B.Cost;
5732 
5733   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5734 
5735   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5736       MaxTripCount) {
5737     // If we are folding the tail and the trip count is a known (possibly small)
5738     // constant, the trip count will be rounded up to an integer number of
5739     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5740     // which we compare directly. When not folding the tail, the total cost will
5741     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5742     // approximated with the per-lane cost below instead of using the tripcount
5743     // as here.
5744     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5745     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5746     return RTCostA < RTCostB;
5747   }
5748 
5749   // Improve estimate for the vector width if it is scalable.
5750   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5751   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5752   if (Optional<unsigned> VScale = TTI.getVScaleForTuning()) {
5753     if (A.Width.isScalable())
5754       EstimatedWidthA *= VScale.getValue();
5755     if (B.Width.isScalable())
5756       EstimatedWidthB *= VScale.getValue();
5757   }
5758 
5759   // When set to preferred, for now assume vscale may be larger than 1 (or the
5760   // one being tuned for), so that scalable vectorization is slightly favorable
5761   // over fixed-width vectorization.
5762   if (Hints->isScalableVectorizationPreferred())
5763     if (A.Width.isScalable() && !B.Width.isScalable())
5764       return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5765 
5766   // To avoid the need for FP division:
5767   //      (CostA / A.Width) < (CostB / B.Width)
5768   // <=>  (CostA * B.Width) < (CostB * A.Width)
5769   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5770 }
5771 
5772 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5773     const ElementCountSet &VFCandidates) {
5774   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5775   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5776   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5777   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5778          "Expected Scalar VF to be a candidate");
5779 
5780   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5781   VectorizationFactor ChosenFactor = ScalarCost;
5782 
5783   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5784   if (ForceVectorization && VFCandidates.size() > 1) {
5785     // Ignore scalar width, because the user explicitly wants vectorization.
5786     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5787     // evaluation.
5788     ChosenFactor.Cost = InstructionCost::getMax();
5789   }
5790 
5791   SmallVector<InstructionVFPair> InvalidCosts;
5792   for (const auto &i : VFCandidates) {
5793     // The cost for scalar VF=1 is already calculated, so ignore it.
5794     if (i.isScalar())
5795       continue;
5796 
5797     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5798     VectorizationFactor Candidate(i, C.first);
5799 
5800 #ifndef NDEBUG
5801     unsigned AssumedMinimumVscale = 1;
5802     if (Optional<unsigned> VScale = TTI.getVScaleForTuning())
5803       AssumedMinimumVscale = VScale.getValue();
5804     unsigned Width =
5805         Candidate.Width.isScalable()
5806             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5807             : Candidate.Width.getFixedValue();
5808     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5809                       << " costs: " << (Candidate.Cost / Width));
5810     if (i.isScalable())
5811       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5812                         << AssumedMinimumVscale << ")");
5813     LLVM_DEBUG(dbgs() << ".\n");
5814 #endif
5815 
5816     if (!C.second && !ForceVectorization) {
5817       LLVM_DEBUG(
5818           dbgs() << "LV: Not considering vector loop of width " << i
5819                  << " because it will not generate any vector instructions.\n");
5820       continue;
5821     }
5822 
5823     // If profitable add it to ProfitableVF list.
5824     if (isMoreProfitable(Candidate, ScalarCost))
5825       ProfitableVFs.push_back(Candidate);
5826 
5827     if (isMoreProfitable(Candidate, ChosenFactor))
5828       ChosenFactor = Candidate;
5829   }
5830 
5831   // Emit a report of VFs with invalid costs in the loop.
5832   if (!InvalidCosts.empty()) {
5833     // Group the remarks per instruction, keeping the instruction order from
5834     // InvalidCosts.
5835     std::map<Instruction *, unsigned> Numbering;
5836     unsigned I = 0;
5837     for (auto &Pair : InvalidCosts)
5838       if (!Numbering.count(Pair.first))
5839         Numbering[Pair.first] = I++;
5840 
5841     // Sort the list, first on instruction(number) then on VF.
5842     llvm::sort(InvalidCosts,
5843                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5844                  if (Numbering[A.first] != Numbering[B.first])
5845                    return Numbering[A.first] < Numbering[B.first];
5846                  ElementCountComparator ECC;
5847                  return ECC(A.second, B.second);
5848                });
5849 
5850     // For a list of ordered instruction-vf pairs:
5851     //   [(load, vf1), (load, vf2), (store, vf1)]
5852     // Group the instructions together to emit separate remarks for:
5853     //   load  (vf1, vf2)
5854     //   store (vf1)
5855     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5856     auto Subset = ArrayRef<InstructionVFPair>();
5857     do {
5858       if (Subset.empty())
5859         Subset = Tail.take_front(1);
5860 
5861       Instruction *I = Subset.front().first;
5862 
5863       // If the next instruction is different, or if there are no other pairs,
5864       // emit a remark for the collated subset. e.g.
5865       //   [(load, vf1), (load, vf2))]
5866       // to emit:
5867       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5868       if (Subset == Tail || Tail[Subset.size()].first != I) {
5869         std::string OutString;
5870         raw_string_ostream OS(OutString);
5871         assert(!Subset.empty() && "Unexpected empty range");
5872         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5873         for (auto &Pair : Subset)
5874           OS << (Pair.second == Subset.front().second ? "" : ", ")
5875              << Pair.second;
5876         OS << "):";
5877         if (auto *CI = dyn_cast<CallInst>(I))
5878           OS << " call to " << CI->getCalledFunction()->getName();
5879         else
5880           OS << " " << I->getOpcodeName();
5881         OS.flush();
5882         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5883         Tail = Tail.drop_front(Subset.size());
5884         Subset = {};
5885       } else
5886         // Grow the subset by one element
5887         Subset = Tail.take_front(Subset.size() + 1);
5888     } while (!Tail.empty());
5889   }
5890 
5891   if (!EnableCondStoresVectorization && NumPredStores) {
5892     reportVectorizationFailure("There are conditional stores.",
5893         "store that is conditionally executed prevents vectorization",
5894         "ConditionalStore", ORE, TheLoop);
5895     ChosenFactor = ScalarCost;
5896   }
5897 
5898   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5899                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
5900              << "LV: Vectorization seems to be not beneficial, "
5901              << "but was forced by a user.\n");
5902   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5903   return ChosenFactor;
5904 }
5905 
5906 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5907     const Loop &L, ElementCount VF) const {
5908   // Cross iteration phis such as reductions need special handling and are
5909   // currently unsupported.
5910   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
5911         return Legal->isFirstOrderRecurrence(&Phi) ||
5912                Legal->isReductionVariable(&Phi);
5913       }))
5914     return false;
5915 
5916   // Phis with uses outside of the loop require special handling and are
5917   // currently unsupported.
5918   for (auto &Entry : Legal->getInductionVars()) {
5919     // Look for uses of the value of the induction at the last iteration.
5920     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5921     for (User *U : PostInc->users())
5922       if (!L.contains(cast<Instruction>(U)))
5923         return false;
5924     // Look for uses of penultimate value of the induction.
5925     for (User *U : Entry.first->users())
5926       if (!L.contains(cast<Instruction>(U)))
5927         return false;
5928   }
5929 
5930   // Induction variables that are widened require special handling that is
5931   // currently not supported.
5932   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5933         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5934                  this->isProfitableToScalarize(Entry.first, VF));
5935       }))
5936     return false;
5937 
5938   // Epilogue vectorization code has not been auditted to ensure it handles
5939   // non-latch exits properly.  It may be fine, but it needs auditted and
5940   // tested.
5941   if (L.getExitingBlock() != L.getLoopLatch())
5942     return false;
5943 
5944   return true;
5945 }
5946 
5947 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5948     const ElementCount VF) const {
5949   // FIXME: We need a much better cost-model to take different parameters such
5950   // as register pressure, code size increase and cost of extra branches into
5951   // account. For now we apply a very crude heuristic and only consider loops
5952   // with vectorization factors larger than a certain value.
5953   // We also consider epilogue vectorization unprofitable for targets that don't
5954   // consider interleaving beneficial (eg. MVE).
5955   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5956     return false;
5957   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
5958     return true;
5959   return false;
5960 }
5961 
5962 VectorizationFactor
5963 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5964     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5965   VectorizationFactor Result = VectorizationFactor::Disabled();
5966   if (!EnableEpilogueVectorization) {
5967     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5968     return Result;
5969   }
5970 
5971   if (!isScalarEpilogueAllowed()) {
5972     LLVM_DEBUG(
5973         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5974                   "allowed.\n";);
5975     return Result;
5976   }
5977 
5978   // Not really a cost consideration, but check for unsupported cases here to
5979   // simplify the logic.
5980   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5981     LLVM_DEBUG(
5982         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5983                   "not a supported candidate.\n";);
5984     return Result;
5985   }
5986 
5987   if (EpilogueVectorizationForceVF > 1) {
5988     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5989     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5990     if (LVP.hasPlanWithVF(ForcedEC))
5991       return {ForcedEC, 0};
5992     else {
5993       LLVM_DEBUG(
5994           dbgs()
5995               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5996       return Result;
5997     }
5998   }
5999 
6000   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6001       TheLoop->getHeader()->getParent()->hasMinSize()) {
6002     LLVM_DEBUG(
6003         dbgs()
6004             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6005     return Result;
6006   }
6007 
6008   auto FixedMainLoopVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
6009   if (MainLoopVF.isScalable())
6010     LLVM_DEBUG(
6011         dbgs() << "LEV: Epilogue vectorization using scalable vectors not "
6012                   "yet supported. Converting to fixed-width (VF="
6013                << FixedMainLoopVF << ") instead\n");
6014 
6015   if (!isEpilogueVectorizationProfitable(FixedMainLoopVF)) {
6016     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
6017                          "this loop\n");
6018     return Result;
6019   }
6020 
6021   for (auto &NextVF : ProfitableVFs)
6022     if (ElementCount::isKnownLT(NextVF.Width, FixedMainLoopVF) &&
6023         (Result.Width.getFixedValue() == 1 ||
6024          isMoreProfitable(NextVF, Result)) &&
6025         LVP.hasPlanWithVF(NextVF.Width))
6026       Result = NextVF;
6027 
6028   if (Result != VectorizationFactor::Disabled())
6029     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6030                       << Result.Width.getFixedValue() << "\n";);
6031   return Result;
6032 }
6033 
6034 std::pair<unsigned, unsigned>
6035 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6036   unsigned MinWidth = -1U;
6037   unsigned MaxWidth = 8;
6038   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6039   for (Type *T : ElementTypesInLoop) {
6040     MinWidth = std::min<unsigned>(
6041         MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6042     MaxWidth = std::max<unsigned>(
6043         MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6044   }
6045   return {MinWidth, MaxWidth};
6046 }
6047 
6048 void LoopVectorizationCostModel::collectElementTypesForWidening() {
6049   ElementTypesInLoop.clear();
6050   // For each block.
6051   for (BasicBlock *BB : TheLoop->blocks()) {
6052     // For each instruction in the loop.
6053     for (Instruction &I : BB->instructionsWithoutDebug()) {
6054       Type *T = I.getType();
6055 
6056       // Skip ignored values.
6057       if (ValuesToIgnore.count(&I))
6058         continue;
6059 
6060       // Only examine Loads, Stores and PHINodes.
6061       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6062         continue;
6063 
6064       // Examine PHI nodes that are reduction variables. Update the type to
6065       // account for the recurrence type.
6066       if (auto *PN = dyn_cast<PHINode>(&I)) {
6067         if (!Legal->isReductionVariable(PN))
6068           continue;
6069         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6070         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6071             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6072                                       RdxDesc.getRecurrenceType(),
6073                                       TargetTransformInfo::ReductionFlags()))
6074           continue;
6075         T = RdxDesc.getRecurrenceType();
6076       }
6077 
6078       // Examine the stored values.
6079       if (auto *ST = dyn_cast<StoreInst>(&I))
6080         T = ST->getValueOperand()->getType();
6081 
6082       // Ignore loaded pointer types and stored pointer types that are not
6083       // vectorizable.
6084       //
6085       // FIXME: The check here attempts to predict whether a load or store will
6086       //        be vectorized. We only know this for certain after a VF has
6087       //        been selected. Here, we assume that if an access can be
6088       //        vectorized, it will be. We should also look at extending this
6089       //        optimization to non-pointer types.
6090       //
6091       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6092           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6093         continue;
6094 
6095       ElementTypesInLoop.insert(T);
6096     }
6097   }
6098 }
6099 
6100 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6101                                                            unsigned LoopCost) {
6102   // -- The interleave heuristics --
6103   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6104   // There are many micro-architectural considerations that we can't predict
6105   // at this level. For example, frontend pressure (on decode or fetch) due to
6106   // code size, or the number and capabilities of the execution ports.
6107   //
6108   // We use the following heuristics to select the interleave count:
6109   // 1. If the code has reductions, then we interleave to break the cross
6110   // iteration dependency.
6111   // 2. If the loop is really small, then we interleave to reduce the loop
6112   // overhead.
6113   // 3. We don't interleave if we think that we will spill registers to memory
6114   // due to the increased register pressure.
6115 
6116   if (!isScalarEpilogueAllowed())
6117     return 1;
6118 
6119   // We used the distance for the interleave count.
6120   if (Legal->getMaxSafeDepDistBytes() != -1U)
6121     return 1;
6122 
6123   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6124   const bool HasReductions = !Legal->getReductionVars().empty();
6125   // Do not interleave loops with a relatively small known or estimated trip
6126   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6127   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6128   // because with the above conditions interleaving can expose ILP and break
6129   // cross iteration dependences for reductions.
6130   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6131       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6132     return 1;
6133 
6134   RegisterUsage R = calculateRegisterUsage({VF})[0];
6135   // We divide by these constants so assume that we have at least one
6136   // instruction that uses at least one register.
6137   for (auto& pair : R.MaxLocalUsers) {
6138     pair.second = std::max(pair.second, 1U);
6139   }
6140 
6141   // We calculate the interleave count using the following formula.
6142   // Subtract the number of loop invariants from the number of available
6143   // registers. These registers are used by all of the interleaved instances.
6144   // Next, divide the remaining registers by the number of registers that is
6145   // required by the loop, in order to estimate how many parallel instances
6146   // fit without causing spills. All of this is rounded down if necessary to be
6147   // a power of two. We want power of two interleave count to simplify any
6148   // addressing operations or alignment considerations.
6149   // We also want power of two interleave counts to ensure that the induction
6150   // variable of the vector loop wraps to zero, when tail is folded by masking;
6151   // this currently happens when OptForSize, in which case IC is set to 1 above.
6152   unsigned IC = UINT_MAX;
6153 
6154   for (auto& pair : R.MaxLocalUsers) {
6155     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6156     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6157                       << " registers of "
6158                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6159     if (VF.isScalar()) {
6160       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6161         TargetNumRegisters = ForceTargetNumScalarRegs;
6162     } else {
6163       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6164         TargetNumRegisters = ForceTargetNumVectorRegs;
6165     }
6166     unsigned MaxLocalUsers = pair.second;
6167     unsigned LoopInvariantRegs = 0;
6168     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6169       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6170 
6171     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6172     // Don't count the induction variable as interleaved.
6173     if (EnableIndVarRegisterHeur) {
6174       TmpIC =
6175           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6176                         std::max(1U, (MaxLocalUsers - 1)));
6177     }
6178 
6179     IC = std::min(IC, TmpIC);
6180   }
6181 
6182   // Clamp the interleave ranges to reasonable counts.
6183   unsigned MaxInterleaveCount =
6184       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6185 
6186   // Check if the user has overridden the max.
6187   if (VF.isScalar()) {
6188     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6189       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6190   } else {
6191     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6192       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6193   }
6194 
6195   // If trip count is known or estimated compile time constant, limit the
6196   // interleave count to be less than the trip count divided by VF, provided it
6197   // is at least 1.
6198   //
6199   // For scalable vectors we can't know if interleaving is beneficial. It may
6200   // not be beneficial for small loops if none of the lanes in the second vector
6201   // iterations is enabled. However, for larger loops, there is likely to be a
6202   // similar benefit as for fixed-width vectors. For now, we choose to leave
6203   // the InterleaveCount as if vscale is '1', although if some information about
6204   // the vector is known (e.g. min vector size), we can make a better decision.
6205   if (BestKnownTC) {
6206     MaxInterleaveCount =
6207         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6208     // Make sure MaxInterleaveCount is greater than 0.
6209     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6210   }
6211 
6212   assert(MaxInterleaveCount > 0 &&
6213          "Maximum interleave count must be greater than 0");
6214 
6215   // Clamp the calculated IC to be between the 1 and the max interleave count
6216   // that the target and trip count allows.
6217   if (IC > MaxInterleaveCount)
6218     IC = MaxInterleaveCount;
6219   else
6220     // Make sure IC is greater than 0.
6221     IC = std::max(1u, IC);
6222 
6223   assert(IC > 0 && "Interleave count must be greater than 0.");
6224 
6225   // If we did not calculate the cost for VF (because the user selected the VF)
6226   // then we calculate the cost of VF here.
6227   if (LoopCost == 0) {
6228     InstructionCost C = expectedCost(VF).first;
6229     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
6230     LoopCost = *C.getValue();
6231   }
6232 
6233   assert(LoopCost && "Non-zero loop cost expected");
6234 
6235   // Interleave if we vectorized this loop and there is a reduction that could
6236   // benefit from interleaving.
6237   if (VF.isVector() && HasReductions) {
6238     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6239     return IC;
6240   }
6241 
6242   // Note that if we've already vectorized the loop we will have done the
6243   // runtime check and so interleaving won't require further checks.
6244   bool InterleavingRequiresRuntimePointerCheck =
6245       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6246 
6247   // We want to interleave small loops in order to reduce the loop overhead and
6248   // potentially expose ILP opportunities.
6249   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6250                     << "LV: IC is " << IC << '\n'
6251                     << "LV: VF is " << VF << '\n');
6252   const bool AggressivelyInterleaveReductions =
6253       TTI.enableAggressiveInterleaving(HasReductions);
6254   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6255     // We assume that the cost overhead is 1 and we use the cost model
6256     // to estimate the cost of the loop and interleave until the cost of the
6257     // loop overhead is about 5% of the cost of the loop.
6258     unsigned SmallIC =
6259         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6260 
6261     // Interleave until store/load ports (estimated by max interleave count) are
6262     // saturated.
6263     unsigned NumStores = Legal->getNumStores();
6264     unsigned NumLoads = Legal->getNumLoads();
6265     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6266     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6267 
6268     // There is little point in interleaving for reductions containing selects
6269     // and compares when VF=1 since it may just create more overhead than it's
6270     // worth for loops with small trip counts. This is because we still have to
6271     // do the final reduction after the loop.
6272     bool HasSelectCmpReductions =
6273         HasReductions &&
6274         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6275           const RecurrenceDescriptor &RdxDesc = Reduction.second;
6276           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
6277               RdxDesc.getRecurrenceKind());
6278         });
6279     if (HasSelectCmpReductions) {
6280       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
6281       return 1;
6282     }
6283 
6284     // If we have a scalar reduction (vector reductions are already dealt with
6285     // by this point), we can increase the critical path length if the loop
6286     // we're interleaving is inside another loop. For tree-wise reductions
6287     // set the limit to 2, and for ordered reductions it's best to disable
6288     // interleaving entirely.
6289     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6290       bool HasOrderedReductions =
6291           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6292             const RecurrenceDescriptor &RdxDesc = Reduction.second;
6293             return RdxDesc.isOrdered();
6294           });
6295       if (HasOrderedReductions) {
6296         LLVM_DEBUG(
6297             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
6298         return 1;
6299       }
6300 
6301       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6302       SmallIC = std::min(SmallIC, F);
6303       StoresIC = std::min(StoresIC, F);
6304       LoadsIC = std::min(LoadsIC, F);
6305     }
6306 
6307     if (EnableLoadStoreRuntimeInterleave &&
6308         std::max(StoresIC, LoadsIC) > SmallIC) {
6309       LLVM_DEBUG(
6310           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6311       return std::max(StoresIC, LoadsIC);
6312     }
6313 
6314     // If there are scalar reductions and TTI has enabled aggressive
6315     // interleaving for reductions, we will interleave to expose ILP.
6316     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6317         AggressivelyInterleaveReductions) {
6318       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6319       // Interleave no less than SmallIC but not as aggressive as the normal IC
6320       // to satisfy the rare situation when resources are too limited.
6321       return std::max(IC / 2, SmallIC);
6322     } else {
6323       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6324       return SmallIC;
6325     }
6326   }
6327 
6328   // Interleave if this is a large loop (small loops are already dealt with by
6329   // this point) that could benefit from interleaving.
6330   if (AggressivelyInterleaveReductions) {
6331     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6332     return IC;
6333   }
6334 
6335   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6336   return 1;
6337 }
6338 
6339 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6340 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6341   // This function calculates the register usage by measuring the highest number
6342   // of values that are alive at a single location. Obviously, this is a very
6343   // rough estimation. We scan the loop in a topological order in order and
6344   // assign a number to each instruction. We use RPO to ensure that defs are
6345   // met before their users. We assume that each instruction that has in-loop
6346   // users starts an interval. We record every time that an in-loop value is
6347   // used, so we have a list of the first and last occurrences of each
6348   // instruction. Next, we transpose this data structure into a multi map that
6349   // holds the list of intervals that *end* at a specific location. This multi
6350   // map allows us to perform a linear search. We scan the instructions linearly
6351   // and record each time that a new interval starts, by placing it in a set.
6352   // If we find this value in the multi-map then we remove it from the set.
6353   // The max register usage is the maximum size of the set.
6354   // We also search for instructions that are defined outside the loop, but are
6355   // used inside the loop. We need this number separately from the max-interval
6356   // usage number because when we unroll, loop-invariant values do not take
6357   // more register.
6358   LoopBlocksDFS DFS(TheLoop);
6359   DFS.perform(LI);
6360 
6361   RegisterUsage RU;
6362 
6363   // Each 'key' in the map opens a new interval. The values
6364   // of the map are the index of the 'last seen' usage of the
6365   // instruction that is the key.
6366   using IntervalMap = DenseMap<Instruction *, unsigned>;
6367 
6368   // Maps instruction to its index.
6369   SmallVector<Instruction *, 64> IdxToInstr;
6370   // Marks the end of each interval.
6371   IntervalMap EndPoint;
6372   // Saves the list of instruction indices that are used in the loop.
6373   SmallPtrSet<Instruction *, 8> Ends;
6374   // Saves the list of values that are used in the loop but are
6375   // defined outside the loop, such as arguments and constants.
6376   SmallPtrSet<Value *, 8> LoopInvariants;
6377 
6378   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6379     for (Instruction &I : BB->instructionsWithoutDebug()) {
6380       IdxToInstr.push_back(&I);
6381 
6382       // Save the end location of each USE.
6383       for (Value *U : I.operands()) {
6384         auto *Instr = dyn_cast<Instruction>(U);
6385 
6386         // Ignore non-instruction values such as arguments, constants, etc.
6387         if (!Instr)
6388           continue;
6389 
6390         // If this instruction is outside the loop then record it and continue.
6391         if (!TheLoop->contains(Instr)) {
6392           LoopInvariants.insert(Instr);
6393           continue;
6394         }
6395 
6396         // Overwrite previous end points.
6397         EndPoint[Instr] = IdxToInstr.size();
6398         Ends.insert(Instr);
6399       }
6400     }
6401   }
6402 
6403   // Saves the list of intervals that end with the index in 'key'.
6404   using InstrList = SmallVector<Instruction *, 2>;
6405   DenseMap<unsigned, InstrList> TransposeEnds;
6406 
6407   // Transpose the EndPoints to a list of values that end at each index.
6408   for (auto &Interval : EndPoint)
6409     TransposeEnds[Interval.second].push_back(Interval.first);
6410 
6411   SmallPtrSet<Instruction *, 8> OpenIntervals;
6412   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6413   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6414 
6415   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6416 
6417   // A lambda that gets the register usage for the given type and VF.
6418   const auto &TTICapture = TTI;
6419   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6420     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6421       return 0;
6422     InstructionCost::CostType RegUsage =
6423         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6424     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6425            "Nonsensical values for register usage.");
6426     return RegUsage;
6427   };
6428 
6429   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6430     Instruction *I = IdxToInstr[i];
6431 
6432     // Remove all of the instructions that end at this location.
6433     InstrList &List = TransposeEnds[i];
6434     for (Instruction *ToRemove : List)
6435       OpenIntervals.erase(ToRemove);
6436 
6437     // Ignore instructions that are never used within the loop.
6438     if (!Ends.count(I))
6439       continue;
6440 
6441     // Skip ignored values.
6442     if (ValuesToIgnore.count(I))
6443       continue;
6444 
6445     // For each VF find the maximum usage of registers.
6446     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6447       // Count the number of live intervals.
6448       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6449 
6450       if (VFs[j].isScalar()) {
6451         for (auto Inst : OpenIntervals) {
6452           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6453           if (RegUsage.find(ClassID) == RegUsage.end())
6454             RegUsage[ClassID] = 1;
6455           else
6456             RegUsage[ClassID] += 1;
6457         }
6458       } else {
6459         collectUniformsAndScalars(VFs[j]);
6460         for (auto Inst : OpenIntervals) {
6461           // Skip ignored values for VF > 1.
6462           if (VecValuesToIgnore.count(Inst))
6463             continue;
6464           if (isScalarAfterVectorization(Inst, VFs[j])) {
6465             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6466             if (RegUsage.find(ClassID) == RegUsage.end())
6467               RegUsage[ClassID] = 1;
6468             else
6469               RegUsage[ClassID] += 1;
6470           } else {
6471             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6472             if (RegUsage.find(ClassID) == RegUsage.end())
6473               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6474             else
6475               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6476           }
6477         }
6478       }
6479 
6480       for (auto& pair : RegUsage) {
6481         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6482           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6483         else
6484           MaxUsages[j][pair.first] = pair.second;
6485       }
6486     }
6487 
6488     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6489                       << OpenIntervals.size() << '\n');
6490 
6491     // Add the current instruction to the list of open intervals.
6492     OpenIntervals.insert(I);
6493   }
6494 
6495   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6496     SmallMapVector<unsigned, unsigned, 4> Invariant;
6497 
6498     for (auto Inst : LoopInvariants) {
6499       unsigned Usage =
6500           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6501       unsigned ClassID =
6502           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6503       if (Invariant.find(ClassID) == Invariant.end())
6504         Invariant[ClassID] = Usage;
6505       else
6506         Invariant[ClassID] += Usage;
6507     }
6508 
6509     LLVM_DEBUG({
6510       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6511       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6512              << " item\n";
6513       for (const auto &pair : MaxUsages[i]) {
6514         dbgs() << "LV(REG): RegisterClass: "
6515                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6516                << " registers\n";
6517       }
6518       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6519              << " item\n";
6520       for (const auto &pair : Invariant) {
6521         dbgs() << "LV(REG): RegisterClass: "
6522                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6523                << " registers\n";
6524       }
6525     });
6526 
6527     RU.LoopInvariantRegs = Invariant;
6528     RU.MaxLocalUsers = MaxUsages[i];
6529     RUs[i] = RU;
6530   }
6531 
6532   return RUs;
6533 }
6534 
6535 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6536   // TODO: Cost model for emulated masked load/store is completely
6537   // broken. This hack guides the cost model to use an artificially
6538   // high enough value to practically disable vectorization with such
6539   // operations, except where previously deployed legality hack allowed
6540   // using very low cost values. This is to avoid regressions coming simply
6541   // from moving "masked load/store" check from legality to cost model.
6542   // Masked Load/Gather emulation was previously never allowed.
6543   // Limited number of Masked Store/Scatter emulation was allowed.
6544   assert(isPredicatedInst(I) &&
6545          "Expecting a scalar emulated instruction");
6546   return isa<LoadInst>(I) ||
6547          (isa<StoreInst>(I) &&
6548           NumPredStores > NumberOfStoresToPredicate);
6549 }
6550 
6551 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6552   // If we aren't vectorizing the loop, or if we've already collected the
6553   // instructions to scalarize, there's nothing to do. Collection may already
6554   // have occurred if we have a user-selected VF and are now computing the
6555   // expected cost for interleaving.
6556   if (VF.isScalar() || VF.isZero() ||
6557       InstsToScalarize.find(VF) != InstsToScalarize.end())
6558     return;
6559 
6560   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6561   // not profitable to scalarize any instructions, the presence of VF in the
6562   // map will indicate that we've analyzed it already.
6563   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6564 
6565   // Find all the instructions that are scalar with predication in the loop and
6566   // determine if it would be better to not if-convert the blocks they are in.
6567   // If so, we also record the instructions to scalarize.
6568   for (BasicBlock *BB : TheLoop->blocks()) {
6569     if (!blockNeedsPredicationForAnyReason(BB))
6570       continue;
6571     for (Instruction &I : *BB)
6572       if (isScalarWithPredication(&I)) {
6573         ScalarCostsTy ScalarCosts;
6574         // Do not apply discount if scalable, because that would lead to
6575         // invalid scalarization costs.
6576         // Do not apply discount logic if hacked cost is needed
6577         // for emulated masked memrefs.
6578         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I) &&
6579             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6580           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6581         // Remember that BB will remain after vectorization.
6582         PredicatedBBsAfterVectorization.insert(BB);
6583       }
6584   }
6585 }
6586 
6587 int LoopVectorizationCostModel::computePredInstDiscount(
6588     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6589   assert(!isUniformAfterVectorization(PredInst, VF) &&
6590          "Instruction marked uniform-after-vectorization will be predicated");
6591 
6592   // Initialize the discount to zero, meaning that the scalar version and the
6593   // vector version cost the same.
6594   InstructionCost Discount = 0;
6595 
6596   // Holds instructions to analyze. The instructions we visit are mapped in
6597   // ScalarCosts. Those instructions are the ones that would be scalarized if
6598   // we find that the scalar version costs less.
6599   SmallVector<Instruction *, 8> Worklist;
6600 
6601   // Returns true if the given instruction can be scalarized.
6602   auto canBeScalarized = [&](Instruction *I) -> bool {
6603     // We only attempt to scalarize instructions forming a single-use chain
6604     // from the original predicated block that would otherwise be vectorized.
6605     // Although not strictly necessary, we give up on instructions we know will
6606     // already be scalar to avoid traversing chains that are unlikely to be
6607     // beneficial.
6608     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6609         isScalarAfterVectorization(I, VF))
6610       return false;
6611 
6612     // If the instruction is scalar with predication, it will be analyzed
6613     // separately. We ignore it within the context of PredInst.
6614     if (isScalarWithPredication(I))
6615       return false;
6616 
6617     // If any of the instruction's operands are uniform after vectorization,
6618     // the instruction cannot be scalarized. This prevents, for example, a
6619     // masked load from being scalarized.
6620     //
6621     // We assume we will only emit a value for lane zero of an instruction
6622     // marked uniform after vectorization, rather than VF identical values.
6623     // Thus, if we scalarize an instruction that uses a uniform, we would
6624     // create uses of values corresponding to the lanes we aren't emitting code
6625     // for. This behavior can be changed by allowing getScalarValue to clone
6626     // the lane zero values for uniforms rather than asserting.
6627     for (Use &U : I->operands())
6628       if (auto *J = dyn_cast<Instruction>(U.get()))
6629         if (isUniformAfterVectorization(J, VF))
6630           return false;
6631 
6632     // Otherwise, we can scalarize the instruction.
6633     return true;
6634   };
6635 
6636   // Compute the expected cost discount from scalarizing the entire expression
6637   // feeding the predicated instruction. We currently only consider expressions
6638   // that are single-use instruction chains.
6639   Worklist.push_back(PredInst);
6640   while (!Worklist.empty()) {
6641     Instruction *I = Worklist.pop_back_val();
6642 
6643     // If we've already analyzed the instruction, there's nothing to do.
6644     if (ScalarCosts.find(I) != ScalarCosts.end())
6645       continue;
6646 
6647     // Compute the cost of the vector instruction. Note that this cost already
6648     // includes the scalarization overhead of the predicated instruction.
6649     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6650 
6651     // Compute the cost of the scalarized instruction. This cost is the cost of
6652     // the instruction as if it wasn't if-converted and instead remained in the
6653     // predicated block. We will scale this cost by block probability after
6654     // computing the scalarization overhead.
6655     InstructionCost ScalarCost =
6656         VF.getFixedValue() *
6657         getInstructionCost(I, ElementCount::getFixed(1)).first;
6658 
6659     // Compute the scalarization overhead of needed insertelement instructions
6660     // and phi nodes.
6661     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6662       ScalarCost += TTI.getScalarizationOverhead(
6663           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6664           APInt::getAllOnes(VF.getFixedValue()), true, false);
6665       ScalarCost +=
6666           VF.getFixedValue() *
6667           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6668     }
6669 
6670     // Compute the scalarization overhead of needed extractelement
6671     // instructions. For each of the instruction's operands, if the operand can
6672     // be scalarized, add it to the worklist; otherwise, account for the
6673     // overhead.
6674     for (Use &U : I->operands())
6675       if (auto *J = dyn_cast<Instruction>(U.get())) {
6676         assert(VectorType::isValidElementType(J->getType()) &&
6677                "Instruction has non-scalar type");
6678         if (canBeScalarized(J))
6679           Worklist.push_back(J);
6680         else if (needsExtract(J, VF)) {
6681           ScalarCost += TTI.getScalarizationOverhead(
6682               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6683               APInt::getAllOnes(VF.getFixedValue()), false, true);
6684         }
6685       }
6686 
6687     // Scale the total scalar cost by block probability.
6688     ScalarCost /= getReciprocalPredBlockProb();
6689 
6690     // Compute the discount. A non-negative discount means the vector version
6691     // of the instruction costs more, and scalarizing would be beneficial.
6692     Discount += VectorCost - ScalarCost;
6693     ScalarCosts[I] = ScalarCost;
6694   }
6695 
6696   return *Discount.getValue();
6697 }
6698 
6699 LoopVectorizationCostModel::VectorizationCostTy
6700 LoopVectorizationCostModel::expectedCost(
6701     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6702   VectorizationCostTy Cost;
6703 
6704   // For each block.
6705   for (BasicBlock *BB : TheLoop->blocks()) {
6706     VectorizationCostTy BlockCost;
6707 
6708     // For each instruction in the old loop.
6709     for (Instruction &I : BB->instructionsWithoutDebug()) {
6710       // Skip ignored values.
6711       if (ValuesToIgnore.count(&I) ||
6712           (VF.isVector() && VecValuesToIgnore.count(&I)))
6713         continue;
6714 
6715       VectorizationCostTy C = getInstructionCost(&I, VF);
6716 
6717       // Check if we should override the cost.
6718       if (C.first.isValid() &&
6719           ForceTargetInstructionCost.getNumOccurrences() > 0)
6720         C.first = InstructionCost(ForceTargetInstructionCost);
6721 
6722       // Keep a list of instructions with invalid costs.
6723       if (Invalid && !C.first.isValid())
6724         Invalid->emplace_back(&I, VF);
6725 
6726       BlockCost.first += C.first;
6727       BlockCost.second |= C.second;
6728       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6729                         << " for VF " << VF << " For instruction: " << I
6730                         << '\n');
6731     }
6732 
6733     // If we are vectorizing a predicated block, it will have been
6734     // if-converted. This means that the block's instructions (aside from
6735     // stores and instructions that may divide by zero) will now be
6736     // unconditionally executed. For the scalar case, we may not always execute
6737     // the predicated block, if it is an if-else block. Thus, scale the block's
6738     // cost by the probability of executing it. blockNeedsPredication from
6739     // Legal is used so as to not include all blocks in tail folded loops.
6740     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6741       BlockCost.first /= getReciprocalPredBlockProb();
6742 
6743     Cost.first += BlockCost.first;
6744     Cost.second |= BlockCost.second;
6745   }
6746 
6747   return Cost;
6748 }
6749 
6750 /// Gets Address Access SCEV after verifying that the access pattern
6751 /// is loop invariant except the induction variable dependence.
6752 ///
6753 /// This SCEV can be sent to the Target in order to estimate the address
6754 /// calculation cost.
6755 static const SCEV *getAddressAccessSCEV(
6756               Value *Ptr,
6757               LoopVectorizationLegality *Legal,
6758               PredicatedScalarEvolution &PSE,
6759               const Loop *TheLoop) {
6760 
6761   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6762   if (!Gep)
6763     return nullptr;
6764 
6765   // We are looking for a gep with all loop invariant indices except for one
6766   // which should be an induction variable.
6767   auto SE = PSE.getSE();
6768   unsigned NumOperands = Gep->getNumOperands();
6769   for (unsigned i = 1; i < NumOperands; ++i) {
6770     Value *Opd = Gep->getOperand(i);
6771     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6772         !Legal->isInductionVariable(Opd))
6773       return nullptr;
6774   }
6775 
6776   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6777   return PSE.getSCEV(Ptr);
6778 }
6779 
6780 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6781   return Legal->hasStride(I->getOperand(0)) ||
6782          Legal->hasStride(I->getOperand(1));
6783 }
6784 
6785 InstructionCost
6786 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6787                                                         ElementCount VF) {
6788   assert(VF.isVector() &&
6789          "Scalarization cost of instruction implies vectorization.");
6790   if (VF.isScalable())
6791     return InstructionCost::getInvalid();
6792 
6793   Type *ValTy = getLoadStoreType(I);
6794   auto SE = PSE.getSE();
6795 
6796   unsigned AS = getLoadStoreAddressSpace(I);
6797   Value *Ptr = getLoadStorePointerOperand(I);
6798   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6799   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6800   //       that it is being called from this specific place.
6801 
6802   // Figure out whether the access is strided and get the stride value
6803   // if it's known in compile time
6804   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6805 
6806   // Get the cost of the scalar memory instruction and address computation.
6807   InstructionCost Cost =
6808       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6809 
6810   // Don't pass *I here, since it is scalar but will actually be part of a
6811   // vectorized loop where the user of it is a vectorized instruction.
6812   const Align Alignment = getLoadStoreAlignment(I);
6813   Cost += VF.getKnownMinValue() *
6814           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6815                               AS, TTI::TCK_RecipThroughput);
6816 
6817   // Get the overhead of the extractelement and insertelement instructions
6818   // we might create due to scalarization.
6819   Cost += getScalarizationOverhead(I, VF);
6820 
6821   // If we have a predicated load/store, it will need extra i1 extracts and
6822   // conditional branches, but may not be executed for each vector lane. Scale
6823   // the cost by the probability of executing the predicated block.
6824   if (isPredicatedInst(I)) {
6825     Cost /= getReciprocalPredBlockProb();
6826 
6827     // Add the cost of an i1 extract and a branch
6828     auto *Vec_i1Ty =
6829         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6830     Cost += TTI.getScalarizationOverhead(
6831         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6832         /*Insert=*/false, /*Extract=*/true);
6833     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6834 
6835     if (useEmulatedMaskMemRefHack(I))
6836       // Artificially setting to a high enough value to practically disable
6837       // vectorization with such operations.
6838       Cost = 3000000;
6839   }
6840 
6841   return Cost;
6842 }
6843 
6844 InstructionCost
6845 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6846                                                     ElementCount VF) {
6847   Type *ValTy = getLoadStoreType(I);
6848   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6849   Value *Ptr = getLoadStorePointerOperand(I);
6850   unsigned AS = getLoadStoreAddressSpace(I);
6851   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6852   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6853 
6854   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6855          "Stride should be 1 or -1 for consecutive memory access");
6856   const Align Alignment = getLoadStoreAlignment(I);
6857   InstructionCost Cost = 0;
6858   if (Legal->isMaskRequired(I))
6859     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6860                                       CostKind);
6861   else
6862     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6863                                 CostKind, I);
6864 
6865   bool Reverse = ConsecutiveStride < 0;
6866   if (Reverse)
6867     Cost +=
6868         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6869   return Cost;
6870 }
6871 
6872 InstructionCost
6873 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6874                                                 ElementCount VF) {
6875   assert(Legal->isUniformMemOp(*I));
6876 
6877   Type *ValTy = getLoadStoreType(I);
6878   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6879   const Align Alignment = getLoadStoreAlignment(I);
6880   unsigned AS = getLoadStoreAddressSpace(I);
6881   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6882   if (isa<LoadInst>(I)) {
6883     return TTI.getAddressComputationCost(ValTy) +
6884            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6885                                CostKind) +
6886            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6887   }
6888   StoreInst *SI = cast<StoreInst>(I);
6889 
6890   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6891   return TTI.getAddressComputationCost(ValTy) +
6892          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6893                              CostKind) +
6894          (isLoopInvariantStoreValue
6895               ? 0
6896               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6897                                        VF.getKnownMinValue() - 1));
6898 }
6899 
6900 InstructionCost
6901 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6902                                                  ElementCount VF) {
6903   Type *ValTy = getLoadStoreType(I);
6904   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6905   const Align Alignment = getLoadStoreAlignment(I);
6906   const Value *Ptr = getLoadStorePointerOperand(I);
6907 
6908   return TTI.getAddressComputationCost(VectorTy) +
6909          TTI.getGatherScatterOpCost(
6910              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6911              TargetTransformInfo::TCK_RecipThroughput, I);
6912 }
6913 
6914 InstructionCost
6915 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6916                                                    ElementCount VF) {
6917   // TODO: Once we have support for interleaving with scalable vectors
6918   // we can calculate the cost properly here.
6919   if (VF.isScalable())
6920     return InstructionCost::getInvalid();
6921 
6922   Type *ValTy = getLoadStoreType(I);
6923   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6924   unsigned AS = getLoadStoreAddressSpace(I);
6925 
6926   auto Group = getInterleavedAccessGroup(I);
6927   assert(Group && "Fail to get an interleaved access group.");
6928 
6929   unsigned InterleaveFactor = Group->getFactor();
6930   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6931 
6932   // Holds the indices of existing members in the interleaved group.
6933   SmallVector<unsigned, 4> Indices;
6934   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6935     if (Group->getMember(IF))
6936       Indices.push_back(IF);
6937 
6938   // Calculate the cost of the whole interleaved group.
6939   bool UseMaskForGaps =
6940       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6941       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6942   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6943       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6944       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6945 
6946   if (Group->isReverse()) {
6947     // TODO: Add support for reversed masked interleaved access.
6948     assert(!Legal->isMaskRequired(I) &&
6949            "Reverse masked interleaved access not supported.");
6950     Cost +=
6951         Group->getNumMembers() *
6952         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6953   }
6954   return Cost;
6955 }
6956 
6957 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6958     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6959   using namespace llvm::PatternMatch;
6960   // Early exit for no inloop reductions
6961   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6962     return None;
6963   auto *VectorTy = cast<VectorType>(Ty);
6964 
6965   // We are looking for a pattern of, and finding the minimal acceptable cost:
6966   //  reduce(mul(ext(A), ext(B))) or
6967   //  reduce(mul(A, B)) or
6968   //  reduce(ext(A)) or
6969   //  reduce(A).
6970   // The basic idea is that we walk down the tree to do that, finding the root
6971   // reduction instruction in InLoopReductionImmediateChains. From there we find
6972   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6973   // of the components. If the reduction cost is lower then we return it for the
6974   // reduction instruction and 0 for the other instructions in the pattern. If
6975   // it is not we return an invalid cost specifying the orignal cost method
6976   // should be used.
6977   Instruction *RetI = I;
6978   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6979     if (!RetI->hasOneUser())
6980       return None;
6981     RetI = RetI->user_back();
6982   }
6983   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6984       RetI->user_back()->getOpcode() == Instruction::Add) {
6985     if (!RetI->hasOneUser())
6986       return None;
6987     RetI = RetI->user_back();
6988   }
6989 
6990   // Test if the found instruction is a reduction, and if not return an invalid
6991   // cost specifying the parent to use the original cost modelling.
6992   if (!InLoopReductionImmediateChains.count(RetI))
6993     return None;
6994 
6995   // Find the reduction this chain is a part of and calculate the basic cost of
6996   // the reduction on its own.
6997   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6998   Instruction *ReductionPhi = LastChain;
6999   while (!isa<PHINode>(ReductionPhi))
7000     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7001 
7002   const RecurrenceDescriptor &RdxDesc =
7003       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7004 
7005   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
7006       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
7007 
7008   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
7009   // normal fmul instruction to the cost of the fadd reduction.
7010   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
7011     BaseCost +=
7012         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
7013 
7014   // If we're using ordered reductions then we can just return the base cost
7015   // here, since getArithmeticReductionCost calculates the full ordered
7016   // reduction cost when FP reassociation is not allowed.
7017   if (useOrderedReductions(RdxDesc))
7018     return BaseCost;
7019 
7020   // Get the operand that was not the reduction chain and match it to one of the
7021   // patterns, returning the better cost if it is found.
7022   Instruction *RedOp = RetI->getOperand(1) == LastChain
7023                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7024                            : dyn_cast<Instruction>(RetI->getOperand(1));
7025 
7026   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7027 
7028   Instruction *Op0, *Op1;
7029   if (RedOp &&
7030       match(RedOp,
7031             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
7032       match(Op0, m_ZExtOrSExt(m_Value())) &&
7033       Op0->getOpcode() == Op1->getOpcode() &&
7034       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7035       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
7036       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
7037 
7038     // Matched reduce(ext(mul(ext(A), ext(B)))
7039     // Note that the extend opcodes need to all match, or if A==B they will have
7040     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
7041     // which is equally fine.
7042     bool IsUnsigned = isa<ZExtInst>(Op0);
7043     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7044     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
7045 
7046     InstructionCost ExtCost =
7047         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
7048                              TTI::CastContextHint::None, CostKind, Op0);
7049     InstructionCost MulCost =
7050         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
7051     InstructionCost Ext2Cost =
7052         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
7053                              TTI::CastContextHint::None, CostKind, RedOp);
7054 
7055     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7056         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7057         CostKind);
7058 
7059     if (RedCost.isValid() &&
7060         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
7061       return I == RetI ? RedCost : 0;
7062   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
7063              !TheLoop->isLoopInvariant(RedOp)) {
7064     // Matched reduce(ext(A))
7065     bool IsUnsigned = isa<ZExtInst>(RedOp);
7066     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7067     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7068         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7069         CostKind);
7070 
7071     InstructionCost ExtCost =
7072         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7073                              TTI::CastContextHint::None, CostKind, RedOp);
7074     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7075       return I == RetI ? RedCost : 0;
7076   } else if (RedOp &&
7077              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
7078     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
7079         Op0->getOpcode() == Op1->getOpcode() &&
7080         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7081         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7082       bool IsUnsigned = isa<ZExtInst>(Op0);
7083       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7084       // Matched reduce(mul(ext, ext))
7085       InstructionCost ExtCost =
7086           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7087                                TTI::CastContextHint::None, CostKind, Op0);
7088       InstructionCost MulCost =
7089           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7090 
7091       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7092           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7093           CostKind);
7094 
7095       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7096         return I == RetI ? RedCost : 0;
7097     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
7098       // Matched reduce(mul())
7099       InstructionCost MulCost =
7100           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7101 
7102       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7103           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7104           CostKind);
7105 
7106       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7107         return I == RetI ? RedCost : 0;
7108     }
7109   }
7110 
7111   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
7112 }
7113 
7114 InstructionCost
7115 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7116                                                      ElementCount VF) {
7117   // Calculate scalar cost only. Vectorization cost should be ready at this
7118   // moment.
7119   if (VF.isScalar()) {
7120     Type *ValTy = getLoadStoreType(I);
7121     const Align Alignment = getLoadStoreAlignment(I);
7122     unsigned AS = getLoadStoreAddressSpace(I);
7123 
7124     return TTI.getAddressComputationCost(ValTy) +
7125            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7126                                TTI::TCK_RecipThroughput, I);
7127   }
7128   return getWideningCost(I, VF);
7129 }
7130 
7131 LoopVectorizationCostModel::VectorizationCostTy
7132 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7133                                                ElementCount VF) {
7134   // If we know that this instruction will remain uniform, check the cost of
7135   // the scalar version.
7136   if (isUniformAfterVectorization(I, VF))
7137     VF = ElementCount::getFixed(1);
7138 
7139   if (VF.isVector() && isProfitableToScalarize(I, VF))
7140     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7141 
7142   // Forced scalars do not have any scalarization overhead.
7143   auto ForcedScalar = ForcedScalars.find(VF);
7144   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7145     auto InstSet = ForcedScalar->second;
7146     if (InstSet.count(I))
7147       return VectorizationCostTy(
7148           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7149            VF.getKnownMinValue()),
7150           false);
7151   }
7152 
7153   Type *VectorTy;
7154   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7155 
7156   bool TypeNotScalarized = false;
7157   if (VF.isVector() && VectorTy->isVectorTy()) {
7158     unsigned NumParts = TTI.getNumberOfParts(VectorTy);
7159     if (NumParts)
7160       TypeNotScalarized = NumParts < VF.getKnownMinValue();
7161     else
7162       C = InstructionCost::getInvalid();
7163   }
7164   return VectorizationCostTy(C, TypeNotScalarized);
7165 }
7166 
7167 InstructionCost
7168 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7169                                                      ElementCount VF) const {
7170 
7171   // There is no mechanism yet to create a scalable scalarization loop,
7172   // so this is currently Invalid.
7173   if (VF.isScalable())
7174     return InstructionCost::getInvalid();
7175 
7176   if (VF.isScalar())
7177     return 0;
7178 
7179   InstructionCost Cost = 0;
7180   Type *RetTy = ToVectorTy(I->getType(), VF);
7181   if (!RetTy->isVoidTy() &&
7182       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7183     Cost += TTI.getScalarizationOverhead(
7184         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
7185         false);
7186 
7187   // Some targets keep addresses scalar.
7188   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7189     return Cost;
7190 
7191   // Some targets support efficient element stores.
7192   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7193     return Cost;
7194 
7195   // Collect operands to consider.
7196   CallInst *CI = dyn_cast<CallInst>(I);
7197   Instruction::op_range Ops = CI ? CI->args() : I->operands();
7198 
7199   // Skip operands that do not require extraction/scalarization and do not incur
7200   // any overhead.
7201   SmallVector<Type *> Tys;
7202   for (auto *V : filterExtractingOperands(Ops, VF))
7203     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7204   return Cost + TTI.getOperandsScalarizationOverhead(
7205                     filterExtractingOperands(Ops, VF), Tys);
7206 }
7207 
7208 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7209   if (VF.isScalar())
7210     return;
7211   NumPredStores = 0;
7212   for (BasicBlock *BB : TheLoop->blocks()) {
7213     // For each instruction in the old loop.
7214     for (Instruction &I : *BB) {
7215       Value *Ptr =  getLoadStorePointerOperand(&I);
7216       if (!Ptr)
7217         continue;
7218 
7219       // TODO: We should generate better code and update the cost model for
7220       // predicated uniform stores. Today they are treated as any other
7221       // predicated store (see added test cases in
7222       // invariant-store-vectorization.ll).
7223       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7224         NumPredStores++;
7225 
7226       if (Legal->isUniformMemOp(I)) {
7227         // TODO: Avoid replicating loads and stores instead of
7228         // relying on instcombine to remove them.
7229         // Load: Scalar load + broadcast
7230         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7231         InstructionCost Cost;
7232         if (isa<StoreInst>(&I) && VF.isScalable() &&
7233             isLegalGatherOrScatter(&I)) {
7234           Cost = getGatherScatterCost(&I, VF);
7235           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7236         } else {
7237           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7238                  "Cannot yet scalarize uniform stores");
7239           Cost = getUniformMemOpCost(&I, VF);
7240           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7241         }
7242         continue;
7243       }
7244 
7245       // We assume that widening is the best solution when possible.
7246       if (memoryInstructionCanBeWidened(&I, VF)) {
7247         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7248         int ConsecutiveStride = Legal->isConsecutivePtr(
7249             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
7250         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7251                "Expected consecutive stride.");
7252         InstWidening Decision =
7253             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7254         setWideningDecision(&I, VF, Decision, Cost);
7255         continue;
7256       }
7257 
7258       // Choose between Interleaving, Gather/Scatter or Scalarization.
7259       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7260       unsigned NumAccesses = 1;
7261       if (isAccessInterleaved(&I)) {
7262         auto Group = getInterleavedAccessGroup(&I);
7263         assert(Group && "Fail to get an interleaved access group.");
7264 
7265         // Make one decision for the whole group.
7266         if (getWideningDecision(&I, VF) != CM_Unknown)
7267           continue;
7268 
7269         NumAccesses = Group->getNumMembers();
7270         if (interleavedAccessCanBeWidened(&I, VF))
7271           InterleaveCost = getInterleaveGroupCost(&I, VF);
7272       }
7273 
7274       InstructionCost GatherScatterCost =
7275           isLegalGatherOrScatter(&I)
7276               ? getGatherScatterCost(&I, VF) * NumAccesses
7277               : InstructionCost::getInvalid();
7278 
7279       InstructionCost ScalarizationCost =
7280           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7281 
7282       // Choose better solution for the current VF,
7283       // write down this decision and use it during vectorization.
7284       InstructionCost Cost;
7285       InstWidening Decision;
7286       if (InterleaveCost <= GatherScatterCost &&
7287           InterleaveCost < ScalarizationCost) {
7288         Decision = CM_Interleave;
7289         Cost = InterleaveCost;
7290       } else if (GatherScatterCost < ScalarizationCost) {
7291         Decision = CM_GatherScatter;
7292         Cost = GatherScatterCost;
7293       } else {
7294         Decision = CM_Scalarize;
7295         Cost = ScalarizationCost;
7296       }
7297       // If the instructions belongs to an interleave group, the whole group
7298       // receives the same decision. The whole group receives the cost, but
7299       // the cost will actually be assigned to one instruction.
7300       if (auto Group = getInterleavedAccessGroup(&I))
7301         setWideningDecision(Group, VF, Decision, Cost);
7302       else
7303         setWideningDecision(&I, VF, Decision, Cost);
7304     }
7305   }
7306 
7307   // Make sure that any load of address and any other address computation
7308   // remains scalar unless there is gather/scatter support. This avoids
7309   // inevitable extracts into address registers, and also has the benefit of
7310   // activating LSR more, since that pass can't optimize vectorized
7311   // addresses.
7312   if (TTI.prefersVectorizedAddressing())
7313     return;
7314 
7315   // Start with all scalar pointer uses.
7316   SmallPtrSet<Instruction *, 8> AddrDefs;
7317   for (BasicBlock *BB : TheLoop->blocks())
7318     for (Instruction &I : *BB) {
7319       Instruction *PtrDef =
7320         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7321       if (PtrDef && TheLoop->contains(PtrDef) &&
7322           getWideningDecision(&I, VF) != CM_GatherScatter)
7323         AddrDefs.insert(PtrDef);
7324     }
7325 
7326   // Add all instructions used to generate the addresses.
7327   SmallVector<Instruction *, 4> Worklist;
7328   append_range(Worklist, AddrDefs);
7329   while (!Worklist.empty()) {
7330     Instruction *I = Worklist.pop_back_val();
7331     for (auto &Op : I->operands())
7332       if (auto *InstOp = dyn_cast<Instruction>(Op))
7333         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7334             AddrDefs.insert(InstOp).second)
7335           Worklist.push_back(InstOp);
7336   }
7337 
7338   for (auto *I : AddrDefs) {
7339     if (isa<LoadInst>(I)) {
7340       // Setting the desired widening decision should ideally be handled in
7341       // by cost functions, but since this involves the task of finding out
7342       // if the loaded register is involved in an address computation, it is
7343       // instead changed here when we know this is the case.
7344       InstWidening Decision = getWideningDecision(I, VF);
7345       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7346         // Scalarize a widened load of address.
7347         setWideningDecision(
7348             I, VF, CM_Scalarize,
7349             (VF.getKnownMinValue() *
7350              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7351       else if (auto Group = getInterleavedAccessGroup(I)) {
7352         // Scalarize an interleave group of address loads.
7353         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7354           if (Instruction *Member = Group->getMember(I))
7355             setWideningDecision(
7356                 Member, VF, CM_Scalarize,
7357                 (VF.getKnownMinValue() *
7358                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7359         }
7360       }
7361     } else
7362       // Make sure I gets scalarized and a cost estimate without
7363       // scalarization overhead.
7364       ForcedScalars[VF].insert(I);
7365   }
7366 }
7367 
7368 InstructionCost
7369 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7370                                                Type *&VectorTy) {
7371   Type *RetTy = I->getType();
7372   if (canTruncateToMinimalBitwidth(I, VF))
7373     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7374   auto SE = PSE.getSE();
7375   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7376 
7377   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7378                                                 ElementCount VF) -> bool {
7379     if (VF.isScalar())
7380       return true;
7381 
7382     auto Scalarized = InstsToScalarize.find(VF);
7383     assert(Scalarized != InstsToScalarize.end() &&
7384            "VF not yet analyzed for scalarization profitability");
7385     return !Scalarized->second.count(I) &&
7386            llvm::all_of(I->users(), [&](User *U) {
7387              auto *UI = cast<Instruction>(U);
7388              return !Scalarized->second.count(UI);
7389            });
7390   };
7391   (void) hasSingleCopyAfterVectorization;
7392 
7393   if (isScalarAfterVectorization(I, VF)) {
7394     // With the exception of GEPs and PHIs, after scalarization there should
7395     // only be one copy of the instruction generated in the loop. This is
7396     // because the VF is either 1, or any instructions that need scalarizing
7397     // have already been dealt with by the the time we get here. As a result,
7398     // it means we don't have to multiply the instruction cost by VF.
7399     assert(I->getOpcode() == Instruction::GetElementPtr ||
7400            I->getOpcode() == Instruction::PHI ||
7401            (I->getOpcode() == Instruction::BitCast &&
7402             I->getType()->isPointerTy()) ||
7403            hasSingleCopyAfterVectorization(I, VF));
7404     VectorTy = RetTy;
7405   } else
7406     VectorTy = ToVectorTy(RetTy, VF);
7407 
7408   // TODO: We need to estimate the cost of intrinsic calls.
7409   switch (I->getOpcode()) {
7410   case Instruction::GetElementPtr:
7411     // We mark this instruction as zero-cost because the cost of GEPs in
7412     // vectorized code depends on whether the corresponding memory instruction
7413     // is scalarized or not. Therefore, we handle GEPs with the memory
7414     // instruction cost.
7415     return 0;
7416   case Instruction::Br: {
7417     // In cases of scalarized and predicated instructions, there will be VF
7418     // predicated blocks in the vectorized loop. Each branch around these
7419     // blocks requires also an extract of its vector compare i1 element.
7420     bool ScalarPredicatedBB = false;
7421     BranchInst *BI = cast<BranchInst>(I);
7422     if (VF.isVector() && BI->isConditional() &&
7423         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7424          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7425       ScalarPredicatedBB = true;
7426 
7427     if (ScalarPredicatedBB) {
7428       // Not possible to scalarize scalable vector with predicated instructions.
7429       if (VF.isScalable())
7430         return InstructionCost::getInvalid();
7431       // Return cost for branches around scalarized and predicated blocks.
7432       auto *Vec_i1Ty =
7433           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7434       return (
7435           TTI.getScalarizationOverhead(
7436               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7437           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7438     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7439       // The back-edge branch will remain, as will all scalar branches.
7440       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7441     else
7442       // This branch will be eliminated by if-conversion.
7443       return 0;
7444     // Note: We currently assume zero cost for an unconditional branch inside
7445     // a predicated block since it will become a fall-through, although we
7446     // may decide in the future to call TTI for all branches.
7447   }
7448   case Instruction::PHI: {
7449     auto *Phi = cast<PHINode>(I);
7450 
7451     // First-order recurrences are replaced by vector shuffles inside the loop.
7452     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7453     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7454       return TTI.getShuffleCost(
7455           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7456           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7457 
7458     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7459     // converted into select instructions. We require N - 1 selects per phi
7460     // node, where N is the number of incoming values.
7461     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7462       return (Phi->getNumIncomingValues() - 1) *
7463              TTI.getCmpSelInstrCost(
7464                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7465                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7466                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7467 
7468     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7469   }
7470   case Instruction::UDiv:
7471   case Instruction::SDiv:
7472   case Instruction::URem:
7473   case Instruction::SRem:
7474     // If we have a predicated instruction, it may not be executed for each
7475     // vector lane. Get the scalarization cost and scale this amount by the
7476     // probability of executing the predicated block. If the instruction is not
7477     // predicated, we fall through to the next case.
7478     if (VF.isVector() && isScalarWithPredication(I)) {
7479       InstructionCost Cost = 0;
7480 
7481       // These instructions have a non-void type, so account for the phi nodes
7482       // that we will create. This cost is likely to be zero. The phi node
7483       // cost, if any, should be scaled by the block probability because it
7484       // models a copy at the end of each predicated block.
7485       Cost += VF.getKnownMinValue() *
7486               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7487 
7488       // The cost of the non-predicated instruction.
7489       Cost += VF.getKnownMinValue() *
7490               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7491 
7492       // The cost of insertelement and extractelement instructions needed for
7493       // scalarization.
7494       Cost += getScalarizationOverhead(I, VF);
7495 
7496       // Scale the cost by the probability of executing the predicated blocks.
7497       // This assumes the predicated block for each vector lane is equally
7498       // likely.
7499       return Cost / getReciprocalPredBlockProb();
7500     }
7501     LLVM_FALLTHROUGH;
7502   case Instruction::Add:
7503   case Instruction::FAdd:
7504   case Instruction::Sub:
7505   case Instruction::FSub:
7506   case Instruction::Mul:
7507   case Instruction::FMul:
7508   case Instruction::FDiv:
7509   case Instruction::FRem:
7510   case Instruction::Shl:
7511   case Instruction::LShr:
7512   case Instruction::AShr:
7513   case Instruction::And:
7514   case Instruction::Or:
7515   case Instruction::Xor: {
7516     // Since we will replace the stride by 1 the multiplication should go away.
7517     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7518       return 0;
7519 
7520     // Detect reduction patterns
7521     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7522       return *RedCost;
7523 
7524     // Certain instructions can be cheaper to vectorize if they have a constant
7525     // second vector operand. One example of this are shifts on x86.
7526     Value *Op2 = I->getOperand(1);
7527     TargetTransformInfo::OperandValueProperties Op2VP;
7528     TargetTransformInfo::OperandValueKind Op2VK =
7529         TTI.getOperandInfo(Op2, Op2VP);
7530     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7531       Op2VK = TargetTransformInfo::OK_UniformValue;
7532 
7533     SmallVector<const Value *, 4> Operands(I->operand_values());
7534     return TTI.getArithmeticInstrCost(
7535         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7536         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7537   }
7538   case Instruction::FNeg: {
7539     return TTI.getArithmeticInstrCost(
7540         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7541         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7542         TargetTransformInfo::OP_None, I->getOperand(0), I);
7543   }
7544   case Instruction::Select: {
7545     SelectInst *SI = cast<SelectInst>(I);
7546     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7547     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7548 
7549     const Value *Op0, *Op1;
7550     using namespace llvm::PatternMatch;
7551     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7552                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7553       // select x, y, false --> x & y
7554       // select x, true, y --> x | y
7555       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7556       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7557       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7558       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7559       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7560               Op1->getType()->getScalarSizeInBits() == 1);
7561 
7562       SmallVector<const Value *, 2> Operands{Op0, Op1};
7563       return TTI.getArithmeticInstrCost(
7564           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7565           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7566     }
7567 
7568     Type *CondTy = SI->getCondition()->getType();
7569     if (!ScalarCond)
7570       CondTy = VectorType::get(CondTy, VF);
7571 
7572     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7573     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7574       Pred = Cmp->getPredicate();
7575     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7576                                   CostKind, I);
7577   }
7578   case Instruction::ICmp:
7579   case Instruction::FCmp: {
7580     Type *ValTy = I->getOperand(0)->getType();
7581     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7582     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7583       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7584     VectorTy = ToVectorTy(ValTy, VF);
7585     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7586                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7587                                   I);
7588   }
7589   case Instruction::Store:
7590   case Instruction::Load: {
7591     ElementCount Width = VF;
7592     if (Width.isVector()) {
7593       InstWidening Decision = getWideningDecision(I, Width);
7594       assert(Decision != CM_Unknown &&
7595              "CM decision should be taken at this point");
7596       if (Decision == CM_Scalarize)
7597         Width = ElementCount::getFixed(1);
7598     }
7599     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7600     return getMemoryInstructionCost(I, VF);
7601   }
7602   case Instruction::BitCast:
7603     if (I->getType()->isPointerTy())
7604       return 0;
7605     LLVM_FALLTHROUGH;
7606   case Instruction::ZExt:
7607   case Instruction::SExt:
7608   case Instruction::FPToUI:
7609   case Instruction::FPToSI:
7610   case Instruction::FPExt:
7611   case Instruction::PtrToInt:
7612   case Instruction::IntToPtr:
7613   case Instruction::SIToFP:
7614   case Instruction::UIToFP:
7615   case Instruction::Trunc:
7616   case Instruction::FPTrunc: {
7617     // Computes the CastContextHint from a Load/Store instruction.
7618     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7619       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7620              "Expected a load or a store!");
7621 
7622       if (VF.isScalar() || !TheLoop->contains(I))
7623         return TTI::CastContextHint::Normal;
7624 
7625       switch (getWideningDecision(I, VF)) {
7626       case LoopVectorizationCostModel::CM_GatherScatter:
7627         return TTI::CastContextHint::GatherScatter;
7628       case LoopVectorizationCostModel::CM_Interleave:
7629         return TTI::CastContextHint::Interleave;
7630       case LoopVectorizationCostModel::CM_Scalarize:
7631       case LoopVectorizationCostModel::CM_Widen:
7632         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7633                                         : TTI::CastContextHint::Normal;
7634       case LoopVectorizationCostModel::CM_Widen_Reverse:
7635         return TTI::CastContextHint::Reversed;
7636       case LoopVectorizationCostModel::CM_Unknown:
7637         llvm_unreachable("Instr did not go through cost modelling?");
7638       }
7639 
7640       llvm_unreachable("Unhandled case!");
7641     };
7642 
7643     unsigned Opcode = I->getOpcode();
7644     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7645     // For Trunc, the context is the only user, which must be a StoreInst.
7646     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7647       if (I->hasOneUse())
7648         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7649           CCH = ComputeCCH(Store);
7650     }
7651     // For Z/Sext, the context is the operand, which must be a LoadInst.
7652     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7653              Opcode == Instruction::FPExt) {
7654       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7655         CCH = ComputeCCH(Load);
7656     }
7657 
7658     // We optimize the truncation of induction variables having constant
7659     // integer steps. The cost of these truncations is the same as the scalar
7660     // operation.
7661     if (isOptimizableIVTruncate(I, VF)) {
7662       auto *Trunc = cast<TruncInst>(I);
7663       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7664                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7665     }
7666 
7667     // Detect reduction patterns
7668     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7669       return *RedCost;
7670 
7671     Type *SrcScalarTy = I->getOperand(0)->getType();
7672     Type *SrcVecTy =
7673         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7674     if (canTruncateToMinimalBitwidth(I, VF)) {
7675       // This cast is going to be shrunk. This may remove the cast or it might
7676       // turn it into slightly different cast. For example, if MinBW == 16,
7677       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7678       //
7679       // Calculate the modified src and dest types.
7680       Type *MinVecTy = VectorTy;
7681       if (Opcode == Instruction::Trunc) {
7682         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7683         VectorTy =
7684             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7685       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7686         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7687         VectorTy =
7688             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7689       }
7690     }
7691 
7692     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7693   }
7694   case Instruction::Call: {
7695     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7696       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7697         return *RedCost;
7698     bool NeedToScalarize;
7699     CallInst *CI = cast<CallInst>(I);
7700     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7701     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7702       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7703       return std::min(CallCost, IntrinsicCost);
7704     }
7705     return CallCost;
7706   }
7707   case Instruction::ExtractValue:
7708     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7709   case Instruction::Alloca:
7710     // We cannot easily widen alloca to a scalable alloca, as
7711     // the result would need to be a vector of pointers.
7712     if (VF.isScalable())
7713       return InstructionCost::getInvalid();
7714     LLVM_FALLTHROUGH;
7715   default:
7716     // This opcode is unknown. Assume that it is the same as 'mul'.
7717     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7718   } // end of switch.
7719 }
7720 
7721 char LoopVectorize::ID = 0;
7722 
7723 static const char lv_name[] = "Loop Vectorization";
7724 
7725 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7726 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7727 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7728 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7729 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7730 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7731 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7732 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7733 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7734 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7735 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7736 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7737 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7738 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7739 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7740 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7741 
7742 namespace llvm {
7743 
7744 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7745 
7746 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7747                               bool VectorizeOnlyWhenForced) {
7748   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7749 }
7750 
7751 } // end namespace llvm
7752 
7753 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7754   // Check if the pointer operand of a load or store instruction is
7755   // consecutive.
7756   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7757     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7758   return false;
7759 }
7760 
7761 void LoopVectorizationCostModel::collectValuesToIgnore() {
7762   // Ignore ephemeral values.
7763   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7764 
7765   // Ignore type-promoting instructions we identified during reduction
7766   // detection.
7767   for (auto &Reduction : Legal->getReductionVars()) {
7768     RecurrenceDescriptor &RedDes = Reduction.second;
7769     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7770     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7771   }
7772   // Ignore type-casting instructions we identified during induction
7773   // detection.
7774   for (auto &Induction : Legal->getInductionVars()) {
7775     InductionDescriptor &IndDes = Induction.second;
7776     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7777     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7778   }
7779 }
7780 
7781 void LoopVectorizationCostModel::collectInLoopReductions() {
7782   for (auto &Reduction : Legal->getReductionVars()) {
7783     PHINode *Phi = Reduction.first;
7784     RecurrenceDescriptor &RdxDesc = Reduction.second;
7785 
7786     // We don't collect reductions that are type promoted (yet).
7787     if (RdxDesc.getRecurrenceType() != Phi->getType())
7788       continue;
7789 
7790     // If the target would prefer this reduction to happen "in-loop", then we
7791     // want to record it as such.
7792     unsigned Opcode = RdxDesc.getOpcode();
7793     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7794         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7795                                    TargetTransformInfo::ReductionFlags()))
7796       continue;
7797 
7798     // Check that we can correctly put the reductions into the loop, by
7799     // finding the chain of operations that leads from the phi to the loop
7800     // exit value.
7801     SmallVector<Instruction *, 4> ReductionOperations =
7802         RdxDesc.getReductionOpChain(Phi, TheLoop);
7803     bool InLoop = !ReductionOperations.empty();
7804     if (InLoop) {
7805       InLoopReductionChains[Phi] = ReductionOperations;
7806       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7807       Instruction *LastChain = Phi;
7808       for (auto *I : ReductionOperations) {
7809         InLoopReductionImmediateChains[I] = LastChain;
7810         LastChain = I;
7811       }
7812     }
7813     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7814                       << " reduction for phi: " << *Phi << "\n");
7815   }
7816 }
7817 
7818 // TODO: we could return a pair of values that specify the max VF and
7819 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7820 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7821 // doesn't have a cost model that can choose which plan to execute if
7822 // more than one is generated.
7823 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7824                                  LoopVectorizationCostModel &CM) {
7825   unsigned WidestType;
7826   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7827   return WidestVectorRegBits / WidestType;
7828 }
7829 
7830 VectorizationFactor
7831 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7832   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7833   ElementCount VF = UserVF;
7834   // Outer loop handling: They may require CFG and instruction level
7835   // transformations before even evaluating whether vectorization is profitable.
7836   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7837   // the vectorization pipeline.
7838   if (!OrigLoop->isInnermost()) {
7839     // If the user doesn't provide a vectorization factor, determine a
7840     // reasonable one.
7841     if (UserVF.isZero()) {
7842       VF = ElementCount::getFixed(determineVPlanVF(
7843           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7844               .getFixedSize(),
7845           CM));
7846       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7847 
7848       // Make sure we have a VF > 1 for stress testing.
7849       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7850         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7851                           << "overriding computed VF.\n");
7852         VF = ElementCount::getFixed(4);
7853       }
7854     }
7855     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7856     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7857            "VF needs to be a power of two");
7858     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7859                       << "VF " << VF << " to build VPlans.\n");
7860     buildVPlans(VF, VF);
7861 
7862     // For VPlan build stress testing, we bail out after VPlan construction.
7863     if (VPlanBuildStressTest)
7864       return VectorizationFactor::Disabled();
7865 
7866     return {VF, 0 /*Cost*/};
7867   }
7868 
7869   LLVM_DEBUG(
7870       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7871                 "VPlan-native path.\n");
7872   return VectorizationFactor::Disabled();
7873 }
7874 
7875 Optional<VectorizationFactor>
7876 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7877   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7878   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7879   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7880     return None;
7881 
7882   // Invalidate interleave groups if all blocks of loop will be predicated.
7883   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7884       !useMaskedInterleavedAccesses(*TTI)) {
7885     LLVM_DEBUG(
7886         dbgs()
7887         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7888            "which requires masked-interleaved support.\n");
7889     if (CM.InterleaveInfo.invalidateGroups())
7890       // Invalidating interleave groups also requires invalidating all decisions
7891       // based on them, which includes widening decisions and uniform and scalar
7892       // values.
7893       CM.invalidateCostModelingDecisions();
7894   }
7895 
7896   ElementCount MaxUserVF =
7897       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7898   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7899   if (!UserVF.isZero() && UserVFIsLegal) {
7900     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7901            "VF needs to be a power of two");
7902     // Collect the instructions (and their associated costs) that will be more
7903     // profitable to scalarize.
7904     if (CM.selectUserVectorizationFactor(UserVF)) {
7905       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7906       CM.collectInLoopReductions();
7907       buildVPlansWithVPRecipes(UserVF, UserVF);
7908       LLVM_DEBUG(printPlans(dbgs()));
7909       return {{UserVF, 0}};
7910     } else
7911       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7912                               "InvalidCost", ORE, OrigLoop);
7913   }
7914 
7915   // Populate the set of Vectorization Factor Candidates.
7916   ElementCountSet VFCandidates;
7917   for (auto VF = ElementCount::getFixed(1);
7918        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7919     VFCandidates.insert(VF);
7920   for (auto VF = ElementCount::getScalable(1);
7921        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7922     VFCandidates.insert(VF);
7923 
7924   for (const auto &VF : VFCandidates) {
7925     // Collect Uniform and Scalar instructions after vectorization with VF.
7926     CM.collectUniformsAndScalars(VF);
7927 
7928     // Collect the instructions (and their associated costs) that will be more
7929     // profitable to scalarize.
7930     if (VF.isVector())
7931       CM.collectInstsToScalarize(VF);
7932   }
7933 
7934   CM.collectInLoopReductions();
7935   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7936   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7937 
7938   LLVM_DEBUG(printPlans(dbgs()));
7939   if (!MaxFactors.hasVector())
7940     return VectorizationFactor::Disabled();
7941 
7942   // Select the optimal vectorization factor.
7943   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
7944 
7945   // Check if it is profitable to vectorize with runtime checks.
7946   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7947   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
7948     bool PragmaThresholdReached =
7949         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7950     bool ThresholdReached =
7951         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
7952     if ((ThresholdReached && !Hints.allowReordering()) ||
7953         PragmaThresholdReached) {
7954       ORE->emit([&]() {
7955         return OptimizationRemarkAnalysisAliasing(
7956                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
7957                    OrigLoop->getHeader())
7958                << "loop not vectorized: cannot prove it is safe to reorder "
7959                   "memory operations";
7960       });
7961       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7962       Hints.emitRemarkWithHints();
7963       return VectorizationFactor::Disabled();
7964     }
7965   }
7966   return SelectedVF;
7967 }
7968 
7969 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7970   assert(count_if(VPlans,
7971                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7972              1 &&
7973          "Best VF has not a single VPlan.");
7974 
7975   for (const VPlanPtr &Plan : VPlans) {
7976     if (Plan->hasVF(VF))
7977       return *Plan.get();
7978   }
7979   llvm_unreachable("No plan found!");
7980 }
7981 
7982 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7983                                            VPlan &BestVPlan,
7984                                            InnerLoopVectorizer &ILV,
7985                                            DominatorTree *DT) {
7986   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7987                     << '\n');
7988 
7989   // Perform the actual loop transformation.
7990 
7991   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7992   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7993   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7994   State.TripCount = ILV.getOrCreateTripCount(nullptr);
7995   State.CanonicalIV = ILV.Induction;
7996   ILV.collectPoisonGeneratingRecipes(State);
7997 
7998   ILV.printDebugTracesAtStart();
7999 
8000   //===------------------------------------------------===//
8001   //
8002   // Notice: any optimization or new instruction that go
8003   // into the code below should also be implemented in
8004   // the cost-model.
8005   //
8006   //===------------------------------------------------===//
8007 
8008   // 2. Copy and widen instructions from the old loop into the new loop.
8009   BestVPlan.execute(&State);
8010 
8011   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8012   //    predication, updating analyses.
8013   ILV.fixVectorizedLoop(State);
8014 
8015   ILV.printDebugTracesAtEnd();
8016 }
8017 
8018 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8019 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8020   for (const auto &Plan : VPlans)
8021     if (PrintVPlansInDotFormat)
8022       Plan->printDOT(O);
8023     else
8024       Plan->print(O);
8025 }
8026 #endif
8027 
8028 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8029     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8030 
8031   // We create new control-flow for the vectorized loop, so the original exit
8032   // conditions will be dead after vectorization if it's only used by the
8033   // terminator
8034   SmallVector<BasicBlock*> ExitingBlocks;
8035   OrigLoop->getExitingBlocks(ExitingBlocks);
8036   for (auto *BB : ExitingBlocks) {
8037     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8038     if (!Cmp || !Cmp->hasOneUse())
8039       continue;
8040 
8041     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8042     if (!DeadInstructions.insert(Cmp).second)
8043       continue;
8044 
8045     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8046     // TODO: can recurse through operands in general
8047     for (Value *Op : Cmp->operands()) {
8048       if (isa<TruncInst>(Op) && Op->hasOneUse())
8049           DeadInstructions.insert(cast<Instruction>(Op));
8050     }
8051   }
8052 
8053   // We create new "steps" for induction variable updates to which the original
8054   // induction variables map. An original update instruction will be dead if
8055   // all its users except the induction variable are dead.
8056   auto *Latch = OrigLoop->getLoopLatch();
8057   for (auto &Induction : Legal->getInductionVars()) {
8058     PHINode *Ind = Induction.first;
8059     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8060 
8061     // If the tail is to be folded by masking, the primary induction variable,
8062     // if exists, isn't dead: it will be used for masking. Don't kill it.
8063     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8064       continue;
8065 
8066     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8067           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8068         }))
8069       DeadInstructions.insert(IndUpdate);
8070 
8071     // We record as "Dead" also the type-casting instructions we had identified
8072     // during induction analysis. We don't need any handling for them in the
8073     // vectorized loop because we have proven that, under a proper runtime
8074     // test guarding the vectorized loop, the value of the phi, and the casted
8075     // value of the phi, are the same. The last instruction in this casting chain
8076     // will get its scalar/vector/widened def from the scalar/vector/widened def
8077     // of the respective phi node. Any other casts in the induction def-use chain
8078     // have no other uses outside the phi update chain, and will be ignored.
8079     InductionDescriptor &IndDes = Induction.second;
8080     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8081     DeadInstructions.insert(Casts.begin(), Casts.end());
8082   }
8083 }
8084 
8085 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8086 
8087 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8088 
8089 Value *InnerLoopUnroller::getStepVector(Value *Val, Value *StartIdx,
8090                                         Value *Step,
8091                                         Instruction::BinaryOps BinOp) {
8092   // When unrolling and the VF is 1, we only need to add a simple scalar.
8093   Type *Ty = Val->getType();
8094   assert(!Ty->isVectorTy() && "Val must be a scalar");
8095 
8096   if (Ty->isFloatingPointTy()) {
8097     // Floating-point operations inherit FMF via the builder's flags.
8098     Value *MulOp = Builder.CreateFMul(StartIdx, Step);
8099     return Builder.CreateBinOp(BinOp, Val, MulOp);
8100   }
8101   return Builder.CreateAdd(Val, Builder.CreateMul(StartIdx, Step), "induction");
8102 }
8103 
8104 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8105   SmallVector<Metadata *, 4> MDs;
8106   // Reserve first location for self reference to the LoopID metadata node.
8107   MDs.push_back(nullptr);
8108   bool IsUnrollMetadata = false;
8109   MDNode *LoopID = L->getLoopID();
8110   if (LoopID) {
8111     // First find existing loop unrolling disable metadata.
8112     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8113       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8114       if (MD) {
8115         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8116         IsUnrollMetadata =
8117             S && S->getString().startswith("llvm.loop.unroll.disable");
8118       }
8119       MDs.push_back(LoopID->getOperand(i));
8120     }
8121   }
8122 
8123   if (!IsUnrollMetadata) {
8124     // Add runtime unroll disable metadata.
8125     LLVMContext &Context = L->getHeader()->getContext();
8126     SmallVector<Metadata *, 1> DisableOperands;
8127     DisableOperands.push_back(
8128         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8129     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8130     MDs.push_back(DisableNode);
8131     MDNode *NewLoopID = MDNode::get(Context, MDs);
8132     // Set operand 0 to refer to the loop id itself.
8133     NewLoopID->replaceOperandWith(0, NewLoopID);
8134     L->setLoopID(NewLoopID);
8135   }
8136 }
8137 
8138 //===--------------------------------------------------------------------===//
8139 // EpilogueVectorizerMainLoop
8140 //===--------------------------------------------------------------------===//
8141 
8142 /// This function is partially responsible for generating the control flow
8143 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8144 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8145   MDNode *OrigLoopID = OrigLoop->getLoopID();
8146   Loop *Lp = createVectorLoopSkeleton("");
8147 
8148   // Generate the code to check the minimum iteration count of the vector
8149   // epilogue (see below).
8150   EPI.EpilogueIterationCountCheck =
8151       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8152   EPI.EpilogueIterationCountCheck->setName("iter.check");
8153 
8154   // Generate the code to check any assumptions that we've made for SCEV
8155   // expressions.
8156   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8157 
8158   // Generate the code that checks at runtime if arrays overlap. We put the
8159   // checks into a separate block to make the more common case of few elements
8160   // faster.
8161   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8162 
8163   // Generate the iteration count check for the main loop, *after* the check
8164   // for the epilogue loop, so that the path-length is shorter for the case
8165   // that goes directly through the vector epilogue. The longer-path length for
8166   // the main loop is compensated for, by the gain from vectorizing the larger
8167   // trip count. Note: the branch will get updated later on when we vectorize
8168   // the epilogue.
8169   EPI.MainLoopIterationCountCheck =
8170       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8171 
8172   // Generate the induction variable.
8173   OldInduction = Legal->getPrimaryInduction();
8174   Type *IdxTy = Legal->getWidestInductionType();
8175   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8176 
8177   IRBuilder<> B(&*Lp->getLoopPreheader()->getFirstInsertionPt());
8178   Value *Step = getRuntimeVF(B, IdxTy, VF * UF);
8179   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8180   EPI.VectorTripCount = CountRoundDown;
8181   Induction =
8182       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8183                               getDebugLocFromInstOrOperands(OldInduction));
8184 
8185   // Skip induction resume value creation here because they will be created in
8186   // the second pass. If we created them here, they wouldn't be used anyway,
8187   // because the vplan in the second pass still contains the inductions from the
8188   // original loop.
8189 
8190   return completeLoopSkeleton(Lp, OrigLoopID);
8191 }
8192 
8193 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8194   LLVM_DEBUG({
8195     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8196            << "Main Loop VF:" << EPI.MainLoopVF
8197            << ", Main Loop UF:" << EPI.MainLoopUF
8198            << ", Epilogue Loop VF:" << EPI.EpilogueVF
8199            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8200   });
8201 }
8202 
8203 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8204   DEBUG_WITH_TYPE(VerboseDebug, {
8205     dbgs() << "intermediate fn:\n"
8206            << *OrigLoop->getHeader()->getParent() << "\n";
8207   });
8208 }
8209 
8210 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8211     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8212   assert(L && "Expected valid Loop.");
8213   assert(Bypass && "Expected valid bypass basic block.");
8214   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
8215   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8216   Value *Count = getOrCreateTripCount(L);
8217   // Reuse existing vector loop preheader for TC checks.
8218   // Note that new preheader block is generated for vector loop.
8219   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8220   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8221 
8222   // Generate code to check if the loop's trip count is less than VF * UF of the
8223   // main vector loop.
8224   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8225       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8226 
8227   Value *CheckMinIters = Builder.CreateICmp(
8228       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
8229       "min.iters.check");
8230 
8231   if (!ForEpilogue)
8232     TCCheckBlock->setName("vector.main.loop.iter.check");
8233 
8234   // Create new preheader for vector loop.
8235   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8236                                    DT, LI, nullptr, "vector.ph");
8237 
8238   if (ForEpilogue) {
8239     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8240                                  DT->getNode(Bypass)->getIDom()) &&
8241            "TC check is expected to dominate Bypass");
8242 
8243     // Update dominator for Bypass & LoopExit.
8244     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8245     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8246       // For loops with multiple exits, there's no edge from the middle block
8247       // to exit blocks (as the epilogue must run) and thus no need to update
8248       // the immediate dominator of the exit blocks.
8249       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8250 
8251     LoopBypassBlocks.push_back(TCCheckBlock);
8252 
8253     // Save the trip count so we don't have to regenerate it in the
8254     // vec.epilog.iter.check. This is safe to do because the trip count
8255     // generated here dominates the vector epilog iter check.
8256     EPI.TripCount = Count;
8257   }
8258 
8259   ReplaceInstWithInst(
8260       TCCheckBlock->getTerminator(),
8261       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8262 
8263   return TCCheckBlock;
8264 }
8265 
8266 //===--------------------------------------------------------------------===//
8267 // EpilogueVectorizerEpilogueLoop
8268 //===--------------------------------------------------------------------===//
8269 
8270 /// This function is partially responsible for generating the control flow
8271 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8272 BasicBlock *
8273 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8274   MDNode *OrigLoopID = OrigLoop->getLoopID();
8275   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8276 
8277   // Now, compare the remaining count and if there aren't enough iterations to
8278   // execute the vectorized epilogue skip to the scalar part.
8279   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8280   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8281   LoopVectorPreHeader =
8282       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8283                  LI, nullptr, "vec.epilog.ph");
8284   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8285                                           VecEpilogueIterationCountCheck);
8286 
8287   // Adjust the control flow taking the state info from the main loop
8288   // vectorization into account.
8289   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8290          "expected this to be saved from the previous pass.");
8291   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8292       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8293 
8294   DT->changeImmediateDominator(LoopVectorPreHeader,
8295                                EPI.MainLoopIterationCountCheck);
8296 
8297   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8298       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8299 
8300   if (EPI.SCEVSafetyCheck)
8301     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8302         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8303   if (EPI.MemSafetyCheck)
8304     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8305         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8306 
8307   DT->changeImmediateDominator(
8308       VecEpilogueIterationCountCheck,
8309       VecEpilogueIterationCountCheck->getSinglePredecessor());
8310 
8311   DT->changeImmediateDominator(LoopScalarPreHeader,
8312                                EPI.EpilogueIterationCountCheck);
8313   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8314     // If there is an epilogue which must run, there's no edge from the
8315     // middle block to exit blocks  and thus no need to update the immediate
8316     // dominator of the exit blocks.
8317     DT->changeImmediateDominator(LoopExitBlock,
8318                                  EPI.EpilogueIterationCountCheck);
8319 
8320   // Keep track of bypass blocks, as they feed start values to the induction
8321   // phis in the scalar loop preheader.
8322   if (EPI.SCEVSafetyCheck)
8323     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8324   if (EPI.MemSafetyCheck)
8325     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8326   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8327 
8328   // Generate a resume induction for the vector epilogue and put it in the
8329   // vector epilogue preheader
8330   Type *IdxTy = Legal->getWidestInductionType();
8331   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8332                                          LoopVectorPreHeader->getFirstNonPHI());
8333   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8334   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8335                            EPI.MainLoopIterationCountCheck);
8336 
8337   // Generate the induction variable.
8338   OldInduction = Legal->getPrimaryInduction();
8339   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8340   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8341   Value *StartIdx = EPResumeVal;
8342   Induction =
8343       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8344                               getDebugLocFromInstOrOperands(OldInduction));
8345 
8346   // Generate induction resume values. These variables save the new starting
8347   // indexes for the scalar loop. They are used to test if there are any tail
8348   // iterations left once the vector loop has completed.
8349   // Note that when the vectorized epilogue is skipped due to iteration count
8350   // check, then the resume value for the induction variable comes from
8351   // the trip count of the main vector loop, hence passing the AdditionalBypass
8352   // argument.
8353   createInductionResumeValues(Lp, CountRoundDown,
8354                               {VecEpilogueIterationCountCheck,
8355                                EPI.VectorTripCount} /* AdditionalBypass */);
8356 
8357   AddRuntimeUnrollDisableMetaData(Lp);
8358   return completeLoopSkeleton(Lp, OrigLoopID);
8359 }
8360 
8361 BasicBlock *
8362 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8363     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8364 
8365   assert(EPI.TripCount &&
8366          "Expected trip count to have been safed in the first pass.");
8367   assert(
8368       (!isa<Instruction>(EPI.TripCount) ||
8369        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8370       "saved trip count does not dominate insertion point.");
8371   Value *TC = EPI.TripCount;
8372   IRBuilder<> Builder(Insert->getTerminator());
8373   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8374 
8375   // Generate code to check if the loop's trip count is less than VF * UF of the
8376   // vector epilogue loop.
8377   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8378       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8379 
8380   Value *CheckMinIters =
8381       Builder.CreateICmp(P, Count,
8382                          createStepForVF(Builder, Count->getType(),
8383                                          EPI.EpilogueVF, EPI.EpilogueUF),
8384                          "min.epilog.iters.check");
8385 
8386   ReplaceInstWithInst(
8387       Insert->getTerminator(),
8388       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8389 
8390   LoopBypassBlocks.push_back(Insert);
8391   return Insert;
8392 }
8393 
8394 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8395   LLVM_DEBUG({
8396     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8397            << "Epilogue Loop VF:" << EPI.EpilogueVF
8398            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8399   });
8400 }
8401 
8402 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8403   DEBUG_WITH_TYPE(VerboseDebug, {
8404     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
8405   });
8406 }
8407 
8408 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8409     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8410   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8411   bool PredicateAtRangeStart = Predicate(Range.Start);
8412 
8413   for (ElementCount TmpVF = Range.Start * 2;
8414        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8415     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8416       Range.End = TmpVF;
8417       break;
8418     }
8419 
8420   return PredicateAtRangeStart;
8421 }
8422 
8423 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8424 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8425 /// of VF's starting at a given VF and extending it as much as possible. Each
8426 /// vectorization decision can potentially shorten this sub-range during
8427 /// buildVPlan().
8428 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8429                                            ElementCount MaxVF) {
8430   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8431   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8432     VFRange SubRange = {VF, MaxVFPlusOne};
8433     VPlans.push_back(buildVPlan(SubRange));
8434     VF = SubRange.End;
8435   }
8436 }
8437 
8438 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8439                                          VPlanPtr &Plan) {
8440   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8441 
8442   // Look for cached value.
8443   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8444   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8445   if (ECEntryIt != EdgeMaskCache.end())
8446     return ECEntryIt->second;
8447 
8448   VPValue *SrcMask = createBlockInMask(Src, Plan);
8449 
8450   // The terminator has to be a branch inst!
8451   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8452   assert(BI && "Unexpected terminator found");
8453 
8454   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8455     return EdgeMaskCache[Edge] = SrcMask;
8456 
8457   // If source is an exiting block, we know the exit edge is dynamically dead
8458   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8459   // adding uses of an otherwise potentially dead instruction.
8460   if (OrigLoop->isLoopExiting(Src))
8461     return EdgeMaskCache[Edge] = SrcMask;
8462 
8463   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8464   assert(EdgeMask && "No Edge Mask found for condition");
8465 
8466   if (BI->getSuccessor(0) != Dst)
8467     EdgeMask = Builder.createNot(EdgeMask);
8468 
8469   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8470     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8471     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8472     // The select version does not introduce new UB if SrcMask is false and
8473     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8474     VPValue *False = Plan->getOrAddVPValue(
8475         ConstantInt::getFalse(BI->getCondition()->getType()));
8476     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8477   }
8478 
8479   return EdgeMaskCache[Edge] = EdgeMask;
8480 }
8481 
8482 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8483   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8484 
8485   // Look for cached value.
8486   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8487   if (BCEntryIt != BlockMaskCache.end())
8488     return BCEntryIt->second;
8489 
8490   // All-one mask is modelled as no-mask following the convention for masked
8491   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8492   VPValue *BlockMask = nullptr;
8493 
8494   if (OrigLoop->getHeader() == BB) {
8495     if (!CM.blockNeedsPredicationForAnyReason(BB))
8496       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8497 
8498     // Create the block in mask as the first non-phi instruction in the block.
8499     VPBuilder::InsertPointGuard Guard(Builder);
8500     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8501     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8502 
8503     // Introduce the early-exit compare IV <= BTC to form header block mask.
8504     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8505     // Start by constructing the desired canonical IV.
8506     VPValue *IV = nullptr;
8507     if (Legal->getPrimaryInduction())
8508       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8509     else {
8510       auto *IVRecipe = new VPWidenCanonicalIVRecipe();
8511       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8512       IV = IVRecipe;
8513     }
8514     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8515     bool TailFolded = !CM.isScalarEpilogueAllowed();
8516 
8517     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8518       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8519       // as a second argument, we only pass the IV here and extract the
8520       // tripcount from the transform state where codegen of the VP instructions
8521       // happen.
8522       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8523     } else {
8524       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8525     }
8526     return BlockMaskCache[BB] = BlockMask;
8527   }
8528 
8529   // This is the block mask. We OR all incoming edges.
8530   for (auto *Predecessor : predecessors(BB)) {
8531     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8532     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8533       return BlockMaskCache[BB] = EdgeMask;
8534 
8535     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8536       BlockMask = EdgeMask;
8537       continue;
8538     }
8539 
8540     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8541   }
8542 
8543   return BlockMaskCache[BB] = BlockMask;
8544 }
8545 
8546 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8547                                                 ArrayRef<VPValue *> Operands,
8548                                                 VFRange &Range,
8549                                                 VPlanPtr &Plan) {
8550   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8551          "Must be called with either a load or store");
8552 
8553   auto willWiden = [&](ElementCount VF) -> bool {
8554     if (VF.isScalar())
8555       return false;
8556     LoopVectorizationCostModel::InstWidening Decision =
8557         CM.getWideningDecision(I, VF);
8558     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8559            "CM decision should be taken at this point.");
8560     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8561       return true;
8562     if (CM.isScalarAfterVectorization(I, VF) ||
8563         CM.isProfitableToScalarize(I, VF))
8564       return false;
8565     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8566   };
8567 
8568   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8569     return nullptr;
8570 
8571   VPValue *Mask = nullptr;
8572   if (Legal->isMaskRequired(I))
8573     Mask = createBlockInMask(I->getParent(), Plan);
8574 
8575   // Determine if the pointer operand of the access is either consecutive or
8576   // reverse consecutive.
8577   LoopVectorizationCostModel::InstWidening Decision =
8578       CM.getWideningDecision(I, Range.Start);
8579   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8580   bool Consecutive =
8581       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8582 
8583   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8584     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8585                                               Consecutive, Reverse);
8586 
8587   StoreInst *Store = cast<StoreInst>(I);
8588   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8589                                             Mask, Consecutive, Reverse);
8590 }
8591 
8592 VPWidenIntOrFpInductionRecipe *
8593 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8594                                            ArrayRef<VPValue *> Operands) const {
8595   // Check if this is an integer or fp induction. If so, build the recipe that
8596   // produces its scalar and vector values.
8597   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8598   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8599       II.getKind() == InductionDescriptor::IK_FpInduction) {
8600     assert(II.getStartValue() ==
8601            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8602     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8603     return new VPWidenIntOrFpInductionRecipe(
8604         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8605   }
8606 
8607   return nullptr;
8608 }
8609 
8610 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8611     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8612     VPlan &Plan) const {
8613   // Optimize the special case where the source is a constant integer
8614   // induction variable. Notice that we can only optimize the 'trunc' case
8615   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8616   // (c) other casts depend on pointer size.
8617 
8618   // Determine whether \p K is a truncation based on an induction variable that
8619   // can be optimized.
8620   auto isOptimizableIVTruncate =
8621       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8622     return [=](ElementCount VF) -> bool {
8623       return CM.isOptimizableIVTruncate(K, VF);
8624     };
8625   };
8626 
8627   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8628           isOptimizableIVTruncate(I), Range)) {
8629 
8630     InductionDescriptor II =
8631         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8632     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8633     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8634                                              Start, I);
8635   }
8636   return nullptr;
8637 }
8638 
8639 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8640                                                 ArrayRef<VPValue *> Operands,
8641                                                 VPlanPtr &Plan) {
8642   // If all incoming values are equal, the incoming VPValue can be used directly
8643   // instead of creating a new VPBlendRecipe.
8644   VPValue *FirstIncoming = Operands[0];
8645   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8646         return FirstIncoming == Inc;
8647       })) {
8648     return Operands[0];
8649   }
8650 
8651   // We know that all PHIs in non-header blocks are converted into selects, so
8652   // we don't have to worry about the insertion order and we can just use the
8653   // builder. At this point we generate the predication tree. There may be
8654   // duplications since this is a simple recursive scan, but future
8655   // optimizations will clean it up.
8656   SmallVector<VPValue *, 2> OperandsWithMask;
8657   unsigned NumIncoming = Phi->getNumIncomingValues();
8658 
8659   for (unsigned In = 0; In < NumIncoming; In++) {
8660     VPValue *EdgeMask =
8661       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8662     assert((EdgeMask || NumIncoming == 1) &&
8663            "Multiple predecessors with one having a full mask");
8664     OperandsWithMask.push_back(Operands[In]);
8665     if (EdgeMask)
8666       OperandsWithMask.push_back(EdgeMask);
8667   }
8668   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8669 }
8670 
8671 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8672                                                    ArrayRef<VPValue *> Operands,
8673                                                    VFRange &Range) const {
8674 
8675   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8676       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8677       Range);
8678 
8679   if (IsPredicated)
8680     return nullptr;
8681 
8682   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8683   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8684              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8685              ID == Intrinsic::pseudoprobe ||
8686              ID == Intrinsic::experimental_noalias_scope_decl))
8687     return nullptr;
8688 
8689   auto willWiden = [&](ElementCount VF) -> bool {
8690     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8691     // The following case may be scalarized depending on the VF.
8692     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8693     // version of the instruction.
8694     // Is it beneficial to perform intrinsic call compared to lib call?
8695     bool NeedToScalarize = false;
8696     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8697     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8698     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8699     return UseVectorIntrinsic || !NeedToScalarize;
8700   };
8701 
8702   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8703     return nullptr;
8704 
8705   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8706   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8707 }
8708 
8709 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8710   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8711          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8712   // Instruction should be widened, unless it is scalar after vectorization,
8713   // scalarization is profitable or it is predicated.
8714   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8715     return CM.isScalarAfterVectorization(I, VF) ||
8716            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8717   };
8718   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8719                                                              Range);
8720 }
8721 
8722 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8723                                            ArrayRef<VPValue *> Operands) const {
8724   auto IsVectorizableOpcode = [](unsigned Opcode) {
8725     switch (Opcode) {
8726     case Instruction::Add:
8727     case Instruction::And:
8728     case Instruction::AShr:
8729     case Instruction::BitCast:
8730     case Instruction::FAdd:
8731     case Instruction::FCmp:
8732     case Instruction::FDiv:
8733     case Instruction::FMul:
8734     case Instruction::FNeg:
8735     case Instruction::FPExt:
8736     case Instruction::FPToSI:
8737     case Instruction::FPToUI:
8738     case Instruction::FPTrunc:
8739     case Instruction::FRem:
8740     case Instruction::FSub:
8741     case Instruction::ICmp:
8742     case Instruction::IntToPtr:
8743     case Instruction::LShr:
8744     case Instruction::Mul:
8745     case Instruction::Or:
8746     case Instruction::PtrToInt:
8747     case Instruction::SDiv:
8748     case Instruction::Select:
8749     case Instruction::SExt:
8750     case Instruction::Shl:
8751     case Instruction::SIToFP:
8752     case Instruction::SRem:
8753     case Instruction::Sub:
8754     case Instruction::Trunc:
8755     case Instruction::UDiv:
8756     case Instruction::UIToFP:
8757     case Instruction::URem:
8758     case Instruction::Xor:
8759     case Instruction::ZExt:
8760       return true;
8761     }
8762     return false;
8763   };
8764 
8765   if (!IsVectorizableOpcode(I->getOpcode()))
8766     return nullptr;
8767 
8768   // Success: widen this instruction.
8769   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8770 }
8771 
8772 void VPRecipeBuilder::fixHeaderPhis() {
8773   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8774   for (VPWidenPHIRecipe *R : PhisToFix) {
8775     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8776     VPRecipeBase *IncR =
8777         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8778     R->addOperand(IncR->getVPSingleValue());
8779   }
8780 }
8781 
8782 VPBasicBlock *VPRecipeBuilder::handleReplication(
8783     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8784     VPlanPtr &Plan) {
8785   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8786       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8787       Range);
8788 
8789   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8790       [&](ElementCount VF) { return CM.isPredicatedInst(I, IsUniform); },
8791       Range);
8792 
8793   // Even if the instruction is not marked as uniform, there are certain
8794   // intrinsic calls that can be effectively treated as such, so we check for
8795   // them here. Conservatively, we only do this for scalable vectors, since
8796   // for fixed-width VFs we can always fall back on full scalarization.
8797   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8798     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8799     case Intrinsic::assume:
8800     case Intrinsic::lifetime_start:
8801     case Intrinsic::lifetime_end:
8802       // For scalable vectors if one of the operands is variant then we still
8803       // want to mark as uniform, which will generate one instruction for just
8804       // the first lane of the vector. We can't scalarize the call in the same
8805       // way as for fixed-width vectors because we don't know how many lanes
8806       // there are.
8807       //
8808       // The reasons for doing it this way for scalable vectors are:
8809       //   1. For the assume intrinsic generating the instruction for the first
8810       //      lane is still be better than not generating any at all. For
8811       //      example, the input may be a splat across all lanes.
8812       //   2. For the lifetime start/end intrinsics the pointer operand only
8813       //      does anything useful when the input comes from a stack object,
8814       //      which suggests it should always be uniform. For non-stack objects
8815       //      the effect is to poison the object, which still allows us to
8816       //      remove the call.
8817       IsUniform = true;
8818       break;
8819     default:
8820       break;
8821     }
8822   }
8823 
8824   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8825                                        IsUniform, IsPredicated);
8826   setRecipe(I, Recipe);
8827   Plan->addVPValue(I, Recipe);
8828 
8829   // Find if I uses a predicated instruction. If so, it will use its scalar
8830   // value. Avoid hoisting the insert-element which packs the scalar value into
8831   // a vector value, as that happens iff all users use the vector value.
8832   for (VPValue *Op : Recipe->operands()) {
8833     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8834     if (!PredR)
8835       continue;
8836     auto *RepR =
8837         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8838     assert(RepR->isPredicated() &&
8839            "expected Replicate recipe to be predicated");
8840     RepR->setAlsoPack(false);
8841   }
8842 
8843   // Finalize the recipe for Instr, first if it is not predicated.
8844   if (!IsPredicated) {
8845     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8846     VPBB->appendRecipe(Recipe);
8847     return VPBB;
8848   }
8849   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8850   assert(VPBB->getSuccessors().empty() &&
8851          "VPBB has successors when handling predicated replication.");
8852   // Record predicated instructions for above packing optimizations.
8853   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8854   VPBlockUtils::insertBlockAfter(Region, VPBB);
8855   auto *RegSucc = new VPBasicBlock();
8856   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8857   return RegSucc;
8858 }
8859 
8860 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8861                                                       VPRecipeBase *PredRecipe,
8862                                                       VPlanPtr &Plan) {
8863   // Instructions marked for predication are replicated and placed under an
8864   // if-then construct to prevent side-effects.
8865 
8866   // Generate recipes to compute the block mask for this region.
8867   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8868 
8869   // Build the triangular if-then region.
8870   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8871   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8872   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8873   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8874   auto *PHIRecipe = Instr->getType()->isVoidTy()
8875                         ? nullptr
8876                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8877   if (PHIRecipe) {
8878     Plan->removeVPValueFor(Instr);
8879     Plan->addVPValue(Instr, PHIRecipe);
8880   }
8881   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8882   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8883   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8884 
8885   // Note: first set Entry as region entry and then connect successors starting
8886   // from it in order, to propagate the "parent" of each VPBasicBlock.
8887   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8888   VPBlockUtils::connectBlocks(Pred, Exit);
8889 
8890   return Region;
8891 }
8892 
8893 VPRecipeOrVPValueTy
8894 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8895                                         ArrayRef<VPValue *> Operands,
8896                                         VFRange &Range, VPlanPtr &Plan) {
8897   // First, check for specific widening recipes that deal with calls, memory
8898   // operations, inductions and Phi nodes.
8899   if (auto *CI = dyn_cast<CallInst>(Instr))
8900     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8901 
8902   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8903     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8904 
8905   VPRecipeBase *Recipe;
8906   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8907     if (Phi->getParent() != OrigLoop->getHeader())
8908       return tryToBlend(Phi, Operands, Plan);
8909     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8910       return toVPRecipeResult(Recipe);
8911 
8912     VPWidenPHIRecipe *PhiRecipe = nullptr;
8913     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
8914       VPValue *StartV = Operands[0];
8915       if (Legal->isReductionVariable(Phi)) {
8916         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8917         assert(RdxDesc.getRecurrenceStartValue() ==
8918                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8919         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8920                                              CM.isInLoopReduction(Phi),
8921                                              CM.useOrderedReductions(RdxDesc));
8922       } else {
8923         PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8924       }
8925 
8926       // Record the incoming value from the backedge, so we can add the incoming
8927       // value from the backedge after all recipes have been created.
8928       recordRecipeOf(cast<Instruction>(
8929           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8930       PhisToFix.push_back(PhiRecipe);
8931     } else {
8932       // TODO: record start and backedge value for remaining pointer induction
8933       // phis.
8934       assert(Phi->getType()->isPointerTy() &&
8935              "only pointer phis should be handled here");
8936       PhiRecipe = new VPWidenPHIRecipe(Phi);
8937     }
8938 
8939     return toVPRecipeResult(PhiRecipe);
8940   }
8941 
8942   if (isa<TruncInst>(Instr) &&
8943       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8944                                                Range, *Plan)))
8945     return toVPRecipeResult(Recipe);
8946 
8947   if (!shouldWiden(Instr, Range))
8948     return nullptr;
8949 
8950   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8951     return toVPRecipeResult(new VPWidenGEPRecipe(
8952         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8953 
8954   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8955     bool InvariantCond =
8956         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8957     return toVPRecipeResult(new VPWidenSelectRecipe(
8958         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8959   }
8960 
8961   return toVPRecipeResult(tryToWiden(Instr, Operands));
8962 }
8963 
8964 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8965                                                         ElementCount MaxVF) {
8966   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8967 
8968   // Collect instructions from the original loop that will become trivially dead
8969   // in the vectorized loop. We don't need to vectorize these instructions. For
8970   // example, original induction update instructions can become dead because we
8971   // separately emit induction "steps" when generating code for the new loop.
8972   // Similarly, we create a new latch condition when setting up the structure
8973   // of the new loop, so the old one can become dead.
8974   SmallPtrSet<Instruction *, 4> DeadInstructions;
8975   collectTriviallyDeadInstructions(DeadInstructions);
8976 
8977   // Add assume instructions we need to drop to DeadInstructions, to prevent
8978   // them from being added to the VPlan.
8979   // TODO: We only need to drop assumes in blocks that get flattend. If the
8980   // control flow is preserved, we should keep them.
8981   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8982   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8983 
8984   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8985   // Dead instructions do not need sinking. Remove them from SinkAfter.
8986   for (Instruction *I : DeadInstructions)
8987     SinkAfter.erase(I);
8988 
8989   // Cannot sink instructions after dead instructions (there won't be any
8990   // recipes for them). Instead, find the first non-dead previous instruction.
8991   for (auto &P : Legal->getSinkAfter()) {
8992     Instruction *SinkTarget = P.second;
8993     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8994     (void)FirstInst;
8995     while (DeadInstructions.contains(SinkTarget)) {
8996       assert(
8997           SinkTarget != FirstInst &&
8998           "Must find a live instruction (at least the one feeding the "
8999           "first-order recurrence PHI) before reaching beginning of the block");
9000       SinkTarget = SinkTarget->getPrevNode();
9001       assert(SinkTarget != P.first &&
9002              "sink source equals target, no sinking required");
9003     }
9004     P.second = SinkTarget;
9005   }
9006 
9007   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9008   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9009     VFRange SubRange = {VF, MaxVFPlusOne};
9010     VPlans.push_back(
9011         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9012     VF = SubRange.End;
9013   }
9014 }
9015 
9016 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9017     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9018     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9019 
9020   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9021 
9022   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9023 
9024   // ---------------------------------------------------------------------------
9025   // Pre-construction: record ingredients whose recipes we'll need to further
9026   // process after constructing the initial VPlan.
9027   // ---------------------------------------------------------------------------
9028 
9029   // Mark instructions we'll need to sink later and their targets as
9030   // ingredients whose recipe we'll need to record.
9031   for (auto &Entry : SinkAfter) {
9032     RecipeBuilder.recordRecipeOf(Entry.first);
9033     RecipeBuilder.recordRecipeOf(Entry.second);
9034   }
9035   for (auto &Reduction : CM.getInLoopReductionChains()) {
9036     PHINode *Phi = Reduction.first;
9037     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9038     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9039 
9040     RecipeBuilder.recordRecipeOf(Phi);
9041     for (auto &R : ReductionOperations) {
9042       RecipeBuilder.recordRecipeOf(R);
9043       // For min/max reducitons, where we have a pair of icmp/select, we also
9044       // need to record the ICmp recipe, so it can be removed later.
9045       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9046              "Only min/max recurrences allowed for inloop reductions");
9047       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9048         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9049     }
9050   }
9051 
9052   // For each interleave group which is relevant for this (possibly trimmed)
9053   // Range, add it to the set of groups to be later applied to the VPlan and add
9054   // placeholders for its members' Recipes which we'll be replacing with a
9055   // single VPInterleaveRecipe.
9056   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9057     auto applyIG = [IG, this](ElementCount VF) -> bool {
9058       return (VF.isVector() && // Query is illegal for VF == 1
9059               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9060                   LoopVectorizationCostModel::CM_Interleave);
9061     };
9062     if (!getDecisionAndClampRange(applyIG, Range))
9063       continue;
9064     InterleaveGroups.insert(IG);
9065     for (unsigned i = 0; i < IG->getFactor(); i++)
9066       if (Instruction *Member = IG->getMember(i))
9067         RecipeBuilder.recordRecipeOf(Member);
9068   };
9069 
9070   // ---------------------------------------------------------------------------
9071   // Build initial VPlan: Scan the body of the loop in a topological order to
9072   // visit each basic block after having visited its predecessor basic blocks.
9073   // ---------------------------------------------------------------------------
9074 
9075   auto Plan = std::make_unique<VPlan>();
9076 
9077   // Scan the body of the loop in a topological order to visit each basic block
9078   // after having visited its predecessor basic blocks.
9079   LoopBlocksDFS DFS(OrigLoop);
9080   DFS.perform(LI);
9081 
9082   VPBasicBlock *VPBB = nullptr;
9083   VPBasicBlock *HeaderVPBB = nullptr;
9084   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
9085   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9086     // Relevant instructions from basic block BB will be grouped into VPRecipe
9087     // ingredients and fill a new VPBasicBlock.
9088     unsigned VPBBsForBB = 0;
9089     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9090     if (VPBB)
9091       VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9092     else {
9093       auto *TopRegion = new VPRegionBlock("vector loop");
9094       TopRegion->setEntry(FirstVPBBForBB);
9095       Plan->setEntry(TopRegion);
9096       HeaderVPBB = FirstVPBBForBB;
9097     }
9098     VPBB = FirstVPBBForBB;
9099     Builder.setInsertPoint(VPBB);
9100 
9101     // Introduce each ingredient into VPlan.
9102     // TODO: Model and preserve debug instrinsics in VPlan.
9103     for (Instruction &I : BB->instructionsWithoutDebug()) {
9104       Instruction *Instr = &I;
9105 
9106       // First filter out irrelevant instructions, to ensure no recipes are
9107       // built for them.
9108       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9109         continue;
9110 
9111       SmallVector<VPValue *, 4> Operands;
9112       auto *Phi = dyn_cast<PHINode>(Instr);
9113       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9114         Operands.push_back(Plan->getOrAddVPValue(
9115             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9116       } else {
9117         auto OpRange = Plan->mapToVPValues(Instr->operands());
9118         Operands = {OpRange.begin(), OpRange.end()};
9119       }
9120       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9121               Instr, Operands, Range, Plan)) {
9122         // If Instr can be simplified to an existing VPValue, use it.
9123         if (RecipeOrValue.is<VPValue *>()) {
9124           auto *VPV = RecipeOrValue.get<VPValue *>();
9125           Plan->addVPValue(Instr, VPV);
9126           // If the re-used value is a recipe, register the recipe for the
9127           // instruction, in case the recipe for Instr needs to be recorded.
9128           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9129             RecipeBuilder.setRecipe(Instr, R);
9130           continue;
9131         }
9132         // Otherwise, add the new recipe.
9133         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9134         for (auto *Def : Recipe->definedValues()) {
9135           auto *UV = Def->getUnderlyingValue();
9136           Plan->addVPValue(UV, Def);
9137         }
9138 
9139         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
9140             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
9141           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
9142           // of the header block. That can happen for truncates of induction
9143           // variables. Those recipes are moved to the phi section of the header
9144           // block after applying SinkAfter, which relies on the original
9145           // position of the trunc.
9146           assert(isa<TruncInst>(Instr));
9147           InductionsToMove.push_back(
9148               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
9149         }
9150         RecipeBuilder.setRecipe(Instr, Recipe);
9151         VPBB->appendRecipe(Recipe);
9152         continue;
9153       }
9154 
9155       // Otherwise, if all widening options failed, Instruction is to be
9156       // replicated. This may create a successor for VPBB.
9157       VPBasicBlock *NextVPBB =
9158           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9159       if (NextVPBB != VPBB) {
9160         VPBB = NextVPBB;
9161         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9162                                     : "");
9163       }
9164     }
9165   }
9166 
9167   assert(isa<VPRegionBlock>(Plan->getEntry()) &&
9168          !Plan->getEntry()->getEntryBasicBlock()->empty() &&
9169          "entry block must be set to a VPRegionBlock having a non-empty entry "
9170          "VPBasicBlock");
9171   cast<VPRegionBlock>(Plan->getEntry())->setExit(VPBB);
9172   RecipeBuilder.fixHeaderPhis();
9173 
9174   // ---------------------------------------------------------------------------
9175   // Transform initial VPlan: Apply previously taken decisions, in order, to
9176   // bring the VPlan to its final state.
9177   // ---------------------------------------------------------------------------
9178 
9179   // Apply Sink-After legal constraints.
9180   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9181     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9182     if (Region && Region->isReplicator()) {
9183       assert(Region->getNumSuccessors() == 1 &&
9184              Region->getNumPredecessors() == 1 && "Expected SESE region!");
9185       assert(R->getParent()->size() == 1 &&
9186              "A recipe in an original replicator region must be the only "
9187              "recipe in its block");
9188       return Region;
9189     }
9190     return nullptr;
9191   };
9192   for (auto &Entry : SinkAfter) {
9193     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9194     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9195 
9196     auto *TargetRegion = GetReplicateRegion(Target);
9197     auto *SinkRegion = GetReplicateRegion(Sink);
9198     if (!SinkRegion) {
9199       // If the sink source is not a replicate region, sink the recipe directly.
9200       if (TargetRegion) {
9201         // The target is in a replication region, make sure to move Sink to
9202         // the block after it, not into the replication region itself.
9203         VPBasicBlock *NextBlock =
9204             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9205         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9206       } else
9207         Sink->moveAfter(Target);
9208       continue;
9209     }
9210 
9211     // The sink source is in a replicate region. Unhook the region from the CFG.
9212     auto *SinkPred = SinkRegion->getSinglePredecessor();
9213     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9214     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9215     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9216     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9217 
9218     if (TargetRegion) {
9219       // The target recipe is also in a replicate region, move the sink region
9220       // after the target region.
9221       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9222       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9223       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9224       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9225     } else {
9226       // The sink source is in a replicate region, we need to move the whole
9227       // replicate region, which should only contain a single recipe in the
9228       // main block.
9229       auto *SplitBlock =
9230           Target->getParent()->splitAt(std::next(Target->getIterator()));
9231 
9232       auto *SplitPred = SplitBlock->getSinglePredecessor();
9233 
9234       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9235       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9236       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9237       if (VPBB == SplitPred)
9238         VPBB = SplitBlock;
9239     }
9240   }
9241 
9242   // Now that sink-after is done, move induction recipes for optimized truncates
9243   // to the phi section of the header block.
9244   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
9245     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
9246 
9247   // Adjust the recipes for any inloop reductions.
9248   adjustRecipesForReductions(VPBB, Plan, RecipeBuilder, Range.Start);
9249 
9250   // Introduce a recipe to combine the incoming and previous values of a
9251   // first-order recurrence.
9252   for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9253     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
9254     if (!RecurPhi)
9255       continue;
9256 
9257     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
9258     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
9259     auto *Region = GetReplicateRegion(PrevRecipe);
9260     if (Region)
9261       InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
9262     if (Region || PrevRecipe->isPhi())
9263       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
9264     else
9265       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
9266 
9267     auto *RecurSplice = cast<VPInstruction>(
9268         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
9269                              {RecurPhi, RecurPhi->getBackedgeValue()}));
9270 
9271     RecurPhi->replaceAllUsesWith(RecurSplice);
9272     // Set the first operand of RecurSplice to RecurPhi again, after replacing
9273     // all users.
9274     RecurSplice->setOperand(0, RecurPhi);
9275   }
9276 
9277   // Interleave memory: for each Interleave Group we marked earlier as relevant
9278   // for this VPlan, replace the Recipes widening its memory instructions with a
9279   // single VPInterleaveRecipe at its insertion point.
9280   for (auto IG : InterleaveGroups) {
9281     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9282         RecipeBuilder.getRecipe(IG->getInsertPos()));
9283     SmallVector<VPValue *, 4> StoredValues;
9284     for (unsigned i = 0; i < IG->getFactor(); ++i)
9285       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9286         auto *StoreR =
9287             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9288         StoredValues.push_back(StoreR->getStoredValue());
9289       }
9290 
9291     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9292                                         Recipe->getMask());
9293     VPIG->insertBefore(Recipe);
9294     unsigned J = 0;
9295     for (unsigned i = 0; i < IG->getFactor(); ++i)
9296       if (Instruction *Member = IG->getMember(i)) {
9297         if (!Member->getType()->isVoidTy()) {
9298           VPValue *OriginalV = Plan->getVPValue(Member);
9299           Plan->removeVPValueFor(Member);
9300           Plan->addVPValue(Member, VPIG->getVPValue(J));
9301           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9302           J++;
9303         }
9304         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9305       }
9306   }
9307 
9308   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9309   // in ways that accessing values using original IR values is incorrect.
9310   Plan->disableValue2VPValue();
9311 
9312   VPlanTransforms::sinkScalarOperands(*Plan);
9313   VPlanTransforms::mergeReplicateRegions(*Plan);
9314 
9315   std::string PlanName;
9316   raw_string_ostream RSO(PlanName);
9317   ElementCount VF = Range.Start;
9318   Plan->addVF(VF);
9319   RSO << "Initial VPlan for VF={" << VF;
9320   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9321     Plan->addVF(VF);
9322     RSO << "," << VF;
9323   }
9324   RSO << "},UF>=1";
9325   RSO.flush();
9326   Plan->setName(PlanName);
9327 
9328   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9329   return Plan;
9330 }
9331 
9332 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9333   // Outer loop handling: They may require CFG and instruction level
9334   // transformations before even evaluating whether vectorization is profitable.
9335   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9336   // the vectorization pipeline.
9337   assert(!OrigLoop->isInnermost());
9338   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9339 
9340   // Create new empty VPlan
9341   auto Plan = std::make_unique<VPlan>();
9342 
9343   // Build hierarchical CFG
9344   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9345   HCFGBuilder.buildHierarchicalCFG();
9346 
9347   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9348        VF *= 2)
9349     Plan->addVF(VF);
9350 
9351   if (EnableVPlanPredication) {
9352     VPlanPredicator VPP(*Plan);
9353     VPP.predicate();
9354 
9355     // Avoid running transformation to recipes until masked code generation in
9356     // VPlan-native path is in place.
9357     return Plan;
9358   }
9359 
9360   SmallPtrSet<Instruction *, 1> DeadInstructions;
9361   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9362                                              Legal->getInductionVars(),
9363                                              DeadInstructions, *PSE.getSE());
9364   return Plan;
9365 }
9366 
9367 // Adjust the recipes for reductions. For in-loop reductions the chain of
9368 // instructions leading from the loop exit instr to the phi need to be converted
9369 // to reductions, with one operand being vector and the other being the scalar
9370 // reduction chain. For other reductions, a select is introduced between the phi
9371 // and live-out recipes when folding the tail.
9372 void LoopVectorizationPlanner::adjustRecipesForReductions(
9373     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9374     ElementCount MinVF) {
9375   for (auto &Reduction : CM.getInLoopReductionChains()) {
9376     PHINode *Phi = Reduction.first;
9377     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9378     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9379 
9380     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9381       continue;
9382 
9383     // ReductionOperations are orders top-down from the phi's use to the
9384     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9385     // which of the two operands will remain scalar and which will be reduced.
9386     // For minmax the chain will be the select instructions.
9387     Instruction *Chain = Phi;
9388     for (Instruction *R : ReductionOperations) {
9389       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9390       RecurKind Kind = RdxDesc.getRecurrenceKind();
9391 
9392       VPValue *ChainOp = Plan->getVPValue(Chain);
9393       unsigned FirstOpId;
9394       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9395              "Only min/max recurrences allowed for inloop reductions");
9396       // Recognize a call to the llvm.fmuladd intrinsic.
9397       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9398       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9399              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9400       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9401         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9402                "Expected to replace a VPWidenSelectSC");
9403         FirstOpId = 1;
9404       } else {
9405         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9406                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9407                "Expected to replace a VPWidenSC");
9408         FirstOpId = 0;
9409       }
9410       unsigned VecOpId =
9411           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9412       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9413 
9414       auto *CondOp = CM.foldTailByMasking()
9415                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9416                          : nullptr;
9417 
9418       if (IsFMulAdd) {
9419         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9420         // need to create an fmul recipe to use as the vector operand for the
9421         // fadd reduction.
9422         VPInstruction *FMulRecipe = new VPInstruction(
9423             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9424         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9425         WidenRecipe->getParent()->insert(FMulRecipe,
9426                                          WidenRecipe->getIterator());
9427         VecOp = FMulRecipe;
9428       }
9429       VPReductionRecipe *RedRecipe =
9430           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9431       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9432       Plan->removeVPValueFor(R);
9433       Plan->addVPValue(R, RedRecipe);
9434       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9435       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9436       WidenRecipe->eraseFromParent();
9437 
9438       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9439         VPRecipeBase *CompareRecipe =
9440             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9441         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9442                "Expected to replace a VPWidenSC");
9443         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9444                "Expected no remaining users");
9445         CompareRecipe->eraseFromParent();
9446       }
9447       Chain = R;
9448     }
9449   }
9450 
9451   // If tail is folded by masking, introduce selects between the phi
9452   // and the live-out instruction of each reduction, at the end of the latch.
9453   if (CM.foldTailByMasking()) {
9454     for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9455       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9456       if (!PhiR || PhiR->isInLoop())
9457         continue;
9458       Builder.setInsertPoint(LatchVPBB);
9459       VPValue *Cond =
9460           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9461       VPValue *Red = PhiR->getBackedgeValue();
9462       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9463     }
9464   }
9465 }
9466 
9467 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9468 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9469                                VPSlotTracker &SlotTracker) const {
9470   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9471   IG->getInsertPos()->printAsOperand(O, false);
9472   O << ", ";
9473   getAddr()->printAsOperand(O, SlotTracker);
9474   VPValue *Mask = getMask();
9475   if (Mask) {
9476     O << ", ";
9477     Mask->printAsOperand(O, SlotTracker);
9478   }
9479 
9480   unsigned OpIdx = 0;
9481   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9482     if (!IG->getMember(i))
9483       continue;
9484     if (getNumStoreOperands() > 0) {
9485       O << "\n" << Indent << "  store ";
9486       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9487       O << " to index " << i;
9488     } else {
9489       O << "\n" << Indent << "  ";
9490       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9491       O << " = load from index " << i;
9492     }
9493     ++OpIdx;
9494   }
9495 }
9496 #endif
9497 
9498 void VPWidenCallRecipe::execute(VPTransformState &State) {
9499   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9500                                   *this, State);
9501 }
9502 
9503 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9504   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9505   State.ILV->setDebugLocFromInst(&I);
9506 
9507   // The condition can be loop invariant  but still defined inside the
9508   // loop. This means that we can't just use the original 'cond' value.
9509   // We have to take the 'vectorized' value and pick the first lane.
9510   // Instcombine will make this a no-op.
9511   auto *InvarCond =
9512       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9513 
9514   for (unsigned Part = 0; Part < State.UF; ++Part) {
9515     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9516     Value *Op0 = State.get(getOperand(1), Part);
9517     Value *Op1 = State.get(getOperand(2), Part);
9518     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9519     State.set(this, Sel, Part);
9520     State.ILV->addMetadata(Sel, &I);
9521   }
9522 }
9523 
9524 void VPWidenRecipe::execute(VPTransformState &State) {
9525   auto &I = *cast<Instruction>(getUnderlyingValue());
9526   auto &Builder = State.Builder;
9527   switch (I.getOpcode()) {
9528   case Instruction::Call:
9529   case Instruction::Br:
9530   case Instruction::PHI:
9531   case Instruction::GetElementPtr:
9532   case Instruction::Select:
9533     llvm_unreachable("This instruction is handled by a different recipe.");
9534   case Instruction::UDiv:
9535   case Instruction::SDiv:
9536   case Instruction::SRem:
9537   case Instruction::URem:
9538   case Instruction::Add:
9539   case Instruction::FAdd:
9540   case Instruction::Sub:
9541   case Instruction::FSub:
9542   case Instruction::FNeg:
9543   case Instruction::Mul:
9544   case Instruction::FMul:
9545   case Instruction::FDiv:
9546   case Instruction::FRem:
9547   case Instruction::Shl:
9548   case Instruction::LShr:
9549   case Instruction::AShr:
9550   case Instruction::And:
9551   case Instruction::Or:
9552   case Instruction::Xor: {
9553     // Just widen unops and binops.
9554     State.ILV->setDebugLocFromInst(&I);
9555 
9556     for (unsigned Part = 0; Part < State.UF; ++Part) {
9557       SmallVector<Value *, 2> Ops;
9558       for (VPValue *VPOp : operands())
9559         Ops.push_back(State.get(VPOp, Part));
9560 
9561       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9562 
9563       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9564         VecOp->copyIRFlags(&I);
9565 
9566         // If the instruction is vectorized and was in a basic block that needed
9567         // predication, we can't propagate poison-generating flags (nuw/nsw,
9568         // exact, etc.). The control flow has been linearized and the
9569         // instruction is no longer guarded by the predicate, which could make
9570         // the flag properties to no longer hold.
9571         if (State.MayGeneratePoisonRecipes.count(this) > 0)
9572           VecOp->dropPoisonGeneratingFlags();
9573       }
9574 
9575       // Use this vector value for all users of the original instruction.
9576       State.set(this, V, Part);
9577       State.ILV->addMetadata(V, &I);
9578     }
9579 
9580     break;
9581   }
9582   case Instruction::ICmp:
9583   case Instruction::FCmp: {
9584     // Widen compares. Generate vector compares.
9585     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9586     auto *Cmp = cast<CmpInst>(&I);
9587     State.ILV->setDebugLocFromInst(Cmp);
9588     for (unsigned Part = 0; Part < State.UF; ++Part) {
9589       Value *A = State.get(getOperand(0), Part);
9590       Value *B = State.get(getOperand(1), Part);
9591       Value *C = nullptr;
9592       if (FCmp) {
9593         // Propagate fast math flags.
9594         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9595         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9596         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9597       } else {
9598         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9599       }
9600       State.set(this, C, Part);
9601       State.ILV->addMetadata(C, &I);
9602     }
9603 
9604     break;
9605   }
9606 
9607   case Instruction::ZExt:
9608   case Instruction::SExt:
9609   case Instruction::FPToUI:
9610   case Instruction::FPToSI:
9611   case Instruction::FPExt:
9612   case Instruction::PtrToInt:
9613   case Instruction::IntToPtr:
9614   case Instruction::SIToFP:
9615   case Instruction::UIToFP:
9616   case Instruction::Trunc:
9617   case Instruction::FPTrunc:
9618   case Instruction::BitCast: {
9619     auto *CI = cast<CastInst>(&I);
9620     State.ILV->setDebugLocFromInst(CI);
9621 
9622     /// Vectorize casts.
9623     Type *DestTy = (State.VF.isScalar())
9624                        ? CI->getType()
9625                        : VectorType::get(CI->getType(), State.VF);
9626 
9627     for (unsigned Part = 0; Part < State.UF; ++Part) {
9628       Value *A = State.get(getOperand(0), Part);
9629       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9630       State.set(this, Cast, Part);
9631       State.ILV->addMetadata(Cast, &I);
9632     }
9633     break;
9634   }
9635   default:
9636     // This instruction is not vectorized by simple widening.
9637     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9638     llvm_unreachable("Unhandled instruction!");
9639   } // end of switch.
9640 }
9641 
9642 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9643   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9644   // Construct a vector GEP by widening the operands of the scalar GEP as
9645   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9646   // results in a vector of pointers when at least one operand of the GEP
9647   // is vector-typed. Thus, to keep the representation compact, we only use
9648   // vector-typed operands for loop-varying values.
9649 
9650   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9651     // If we are vectorizing, but the GEP has only loop-invariant operands,
9652     // the GEP we build (by only using vector-typed operands for
9653     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9654     // produce a vector of pointers, we need to either arbitrarily pick an
9655     // operand to broadcast, or broadcast a clone of the original GEP.
9656     // Here, we broadcast a clone of the original.
9657     //
9658     // TODO: If at some point we decide to scalarize instructions having
9659     //       loop-invariant operands, this special case will no longer be
9660     //       required. We would add the scalarization decision to
9661     //       collectLoopScalars() and teach getVectorValue() to broadcast
9662     //       the lane-zero scalar value.
9663     auto *Clone = State.Builder.Insert(GEP->clone());
9664     for (unsigned Part = 0; Part < State.UF; ++Part) {
9665       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9666       State.set(this, EntryPart, Part);
9667       State.ILV->addMetadata(EntryPart, GEP);
9668     }
9669   } else {
9670     // If the GEP has at least one loop-varying operand, we are sure to
9671     // produce a vector of pointers. But if we are only unrolling, we want
9672     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9673     // produce with the code below will be scalar (if VF == 1) or vector
9674     // (otherwise). Note that for the unroll-only case, we still maintain
9675     // values in the vector mapping with initVector, as we do for other
9676     // instructions.
9677     for (unsigned Part = 0; Part < State.UF; ++Part) {
9678       // The pointer operand of the new GEP. If it's loop-invariant, we
9679       // won't broadcast it.
9680       auto *Ptr = IsPtrLoopInvariant
9681                       ? State.get(getOperand(0), VPIteration(0, 0))
9682                       : State.get(getOperand(0), Part);
9683 
9684       // Collect all the indices for the new GEP. If any index is
9685       // loop-invariant, we won't broadcast it.
9686       SmallVector<Value *, 4> Indices;
9687       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9688         VPValue *Operand = getOperand(I);
9689         if (IsIndexLoopInvariant[I - 1])
9690           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9691         else
9692           Indices.push_back(State.get(Operand, Part));
9693       }
9694 
9695       // If the GEP instruction is vectorized and was in a basic block that
9696       // needed predication, we can't propagate the poison-generating 'inbounds'
9697       // flag. The control flow has been linearized and the GEP is no longer
9698       // guarded by the predicate, which could make the 'inbounds' properties to
9699       // no longer hold.
9700       bool IsInBounds =
9701           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9702 
9703       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9704       // but it should be a vector, otherwise.
9705       auto *NewGEP = IsInBounds
9706                          ? State.Builder.CreateInBoundsGEP(
9707                                GEP->getSourceElementType(), Ptr, Indices)
9708                          : State.Builder.CreateGEP(GEP->getSourceElementType(),
9709                                                    Ptr, Indices);
9710       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9711              "NewGEP is not a pointer vector");
9712       State.set(this, NewGEP, Part);
9713       State.ILV->addMetadata(NewGEP, GEP);
9714     }
9715   }
9716 }
9717 
9718 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9719   assert(!State.Instance && "Int or FP induction being replicated.");
9720   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9721                                    getTruncInst(), getVPValue(0),
9722                                    getCastValue(), State);
9723 }
9724 
9725 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9726   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9727                                  State);
9728 }
9729 
9730 void VPBlendRecipe::execute(VPTransformState &State) {
9731   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9732   // We know that all PHIs in non-header blocks are converted into
9733   // selects, so we don't have to worry about the insertion order and we
9734   // can just use the builder.
9735   // At this point we generate the predication tree. There may be
9736   // duplications since this is a simple recursive scan, but future
9737   // optimizations will clean it up.
9738 
9739   unsigned NumIncoming = getNumIncomingValues();
9740 
9741   // Generate a sequence of selects of the form:
9742   // SELECT(Mask3, In3,
9743   //        SELECT(Mask2, In2,
9744   //               SELECT(Mask1, In1,
9745   //                      In0)))
9746   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9747   // are essentially undef are taken from In0.
9748   InnerLoopVectorizer::VectorParts Entry(State.UF);
9749   for (unsigned In = 0; In < NumIncoming; ++In) {
9750     for (unsigned Part = 0; Part < State.UF; ++Part) {
9751       // We might have single edge PHIs (blocks) - use an identity
9752       // 'select' for the first PHI operand.
9753       Value *In0 = State.get(getIncomingValue(In), Part);
9754       if (In == 0)
9755         Entry[Part] = In0; // Initialize with the first incoming value.
9756       else {
9757         // Select between the current value and the previous incoming edge
9758         // based on the incoming mask.
9759         Value *Cond = State.get(getMask(In), Part);
9760         Entry[Part] =
9761             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9762       }
9763     }
9764   }
9765   for (unsigned Part = 0; Part < State.UF; ++Part)
9766     State.set(this, Entry[Part], Part);
9767 }
9768 
9769 void VPInterleaveRecipe::execute(VPTransformState &State) {
9770   assert(!State.Instance && "Interleave group being replicated.");
9771   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9772                                       getStoredValues(), getMask());
9773 }
9774 
9775 void VPReductionRecipe::execute(VPTransformState &State) {
9776   assert(!State.Instance && "Reduction being replicated.");
9777   Value *PrevInChain = State.get(getChainOp(), 0);
9778   RecurKind Kind = RdxDesc->getRecurrenceKind();
9779   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9780   // Propagate the fast-math flags carried by the underlying instruction.
9781   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9782   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9783   for (unsigned Part = 0; Part < State.UF; ++Part) {
9784     Value *NewVecOp = State.get(getVecOp(), Part);
9785     if (VPValue *Cond = getCondOp()) {
9786       Value *NewCond = State.get(Cond, Part);
9787       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9788       Value *Iden = RdxDesc->getRecurrenceIdentity(
9789           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9790       Value *IdenVec =
9791           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9792       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9793       NewVecOp = Select;
9794     }
9795     Value *NewRed;
9796     Value *NextInChain;
9797     if (IsOrdered) {
9798       if (State.VF.isVector())
9799         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9800                                         PrevInChain);
9801       else
9802         NewRed = State.Builder.CreateBinOp(
9803             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9804             NewVecOp);
9805       PrevInChain = NewRed;
9806     } else {
9807       PrevInChain = State.get(getChainOp(), Part);
9808       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9809     }
9810     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9811       NextInChain =
9812           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9813                          NewRed, PrevInChain);
9814     } else if (IsOrdered)
9815       NextInChain = NewRed;
9816     else
9817       NextInChain = State.Builder.CreateBinOp(
9818           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9819           PrevInChain);
9820     State.set(this, NextInChain, Part);
9821   }
9822 }
9823 
9824 void VPReplicateRecipe::execute(VPTransformState &State) {
9825   if (State.Instance) { // Generate a single instance.
9826     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9827     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9828                                     IsPredicated, State);
9829     // Insert scalar instance packing it into a vector.
9830     if (AlsoPack && State.VF.isVector()) {
9831       // If we're constructing lane 0, initialize to start from poison.
9832       if (State.Instance->Lane.isFirstLane()) {
9833         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9834         Value *Poison = PoisonValue::get(
9835             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9836         State.set(this, Poison, State.Instance->Part);
9837       }
9838       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9839     }
9840     return;
9841   }
9842 
9843   // Generate scalar instances for all VF lanes of all UF parts, unless the
9844   // instruction is uniform inwhich case generate only the first lane for each
9845   // of the UF parts.
9846   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9847   assert((!State.VF.isScalable() || IsUniform) &&
9848          "Can't scalarize a scalable vector");
9849   for (unsigned Part = 0; Part < State.UF; ++Part)
9850     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9851       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9852                                       VPIteration(Part, Lane), IsPredicated,
9853                                       State);
9854 }
9855 
9856 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9857   assert(State.Instance && "Branch on Mask works only on single instance.");
9858 
9859   unsigned Part = State.Instance->Part;
9860   unsigned Lane = State.Instance->Lane.getKnownLane();
9861 
9862   Value *ConditionBit = nullptr;
9863   VPValue *BlockInMask = getMask();
9864   if (BlockInMask) {
9865     ConditionBit = State.get(BlockInMask, Part);
9866     if (ConditionBit->getType()->isVectorTy())
9867       ConditionBit = State.Builder.CreateExtractElement(
9868           ConditionBit, State.Builder.getInt32(Lane));
9869   } else // Block in mask is all-one.
9870     ConditionBit = State.Builder.getTrue();
9871 
9872   // Replace the temporary unreachable terminator with a new conditional branch,
9873   // whose two destinations will be set later when they are created.
9874   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9875   assert(isa<UnreachableInst>(CurrentTerminator) &&
9876          "Expected to replace unreachable terminator with conditional branch.");
9877   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9878   CondBr->setSuccessor(0, nullptr);
9879   ReplaceInstWithInst(CurrentTerminator, CondBr);
9880 }
9881 
9882 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9883   assert(State.Instance && "Predicated instruction PHI works per instance.");
9884   Instruction *ScalarPredInst =
9885       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9886   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9887   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9888   assert(PredicatingBB && "Predicated block has no single predecessor.");
9889   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9890          "operand must be VPReplicateRecipe");
9891 
9892   // By current pack/unpack logic we need to generate only a single phi node: if
9893   // a vector value for the predicated instruction exists at this point it means
9894   // the instruction has vector users only, and a phi for the vector value is
9895   // needed. In this case the recipe of the predicated instruction is marked to
9896   // also do that packing, thereby "hoisting" the insert-element sequence.
9897   // Otherwise, a phi node for the scalar value is needed.
9898   unsigned Part = State.Instance->Part;
9899   if (State.hasVectorValue(getOperand(0), Part)) {
9900     Value *VectorValue = State.get(getOperand(0), Part);
9901     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9902     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9903     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9904     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9905     if (State.hasVectorValue(this, Part))
9906       State.reset(this, VPhi, Part);
9907     else
9908       State.set(this, VPhi, Part);
9909     // NOTE: Currently we need to update the value of the operand, so the next
9910     // predicated iteration inserts its generated value in the correct vector.
9911     State.reset(getOperand(0), VPhi, Part);
9912   } else {
9913     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9914     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9915     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9916                      PredicatingBB);
9917     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9918     if (State.hasScalarValue(this, *State.Instance))
9919       State.reset(this, Phi, *State.Instance);
9920     else
9921       State.set(this, Phi, *State.Instance);
9922     // NOTE: Currently we need to update the value of the operand, so the next
9923     // predicated iteration inserts its generated value in the correct vector.
9924     State.reset(getOperand(0), Phi, *State.Instance);
9925   }
9926 }
9927 
9928 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9929   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9930 
9931   // Attempt to issue a wide load.
9932   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9933   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9934 
9935   assert((LI || SI) && "Invalid Load/Store instruction");
9936   assert((!SI || StoredValue) && "No stored value provided for widened store");
9937   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9938 
9939   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9940 
9941   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9942   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9943   bool CreateGatherScatter = !Consecutive;
9944 
9945   auto &Builder = State.Builder;
9946   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9947   bool isMaskRequired = getMask();
9948   if (isMaskRequired)
9949     for (unsigned Part = 0; Part < State.UF; ++Part)
9950       BlockInMaskParts[Part] = State.get(getMask(), Part);
9951 
9952   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9953     // Calculate the pointer for the specific unroll-part.
9954     GetElementPtrInst *PartPtr = nullptr;
9955 
9956     bool InBounds = false;
9957     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9958       InBounds = gep->isInBounds();
9959     if (Reverse) {
9960       // If the address is consecutive but reversed, then the
9961       // wide store needs to start at the last vector element.
9962       // RunTimeVF =  VScale * VF.getKnownMinValue()
9963       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9964       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9965       // NumElt = -Part * RunTimeVF
9966       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9967       // LastLane = 1 - RunTimeVF
9968       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9969       PartPtr =
9970           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9971       PartPtr->setIsInBounds(InBounds);
9972       PartPtr = cast<GetElementPtrInst>(
9973           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9974       PartPtr->setIsInBounds(InBounds);
9975       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
9976         BlockInMaskParts[Part] =
9977             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
9978     } else {
9979       Value *Increment =
9980           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
9981       PartPtr = cast<GetElementPtrInst>(
9982           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
9983       PartPtr->setIsInBounds(InBounds);
9984     }
9985 
9986     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
9987     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
9988   };
9989 
9990   // Handle Stores:
9991   if (SI) {
9992     State.ILV->setDebugLocFromInst(SI);
9993 
9994     for (unsigned Part = 0; Part < State.UF; ++Part) {
9995       Instruction *NewSI = nullptr;
9996       Value *StoredVal = State.get(StoredValue, Part);
9997       if (CreateGatherScatter) {
9998         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9999         Value *VectorGep = State.get(getAddr(), Part);
10000         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
10001                                             MaskPart);
10002       } else {
10003         if (Reverse) {
10004           // If we store to reverse consecutive memory locations, then we need
10005           // to reverse the order of elements in the stored value.
10006           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
10007           // We don't want to update the value in the map as it might be used in
10008           // another expression. So don't call resetVectorValue(StoredVal).
10009         }
10010         auto *VecPtr =
10011             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10012         if (isMaskRequired)
10013           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
10014                                             BlockInMaskParts[Part]);
10015         else
10016           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
10017       }
10018       State.ILV->addMetadata(NewSI, SI);
10019     }
10020     return;
10021   }
10022 
10023   // Handle loads.
10024   assert(LI && "Must have a load instruction");
10025   State.ILV->setDebugLocFromInst(LI);
10026   for (unsigned Part = 0; Part < State.UF; ++Part) {
10027     Value *NewLI;
10028     if (CreateGatherScatter) {
10029       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10030       Value *VectorGep = State.get(getAddr(), Part);
10031       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
10032                                          nullptr, "wide.masked.gather");
10033       State.ILV->addMetadata(NewLI, LI);
10034     } else {
10035       auto *VecPtr =
10036           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10037       if (isMaskRequired)
10038         NewLI = Builder.CreateMaskedLoad(
10039             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
10040             PoisonValue::get(DataTy), "wide.masked.load");
10041       else
10042         NewLI =
10043             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
10044 
10045       // Add metadata to the load, but setVectorValue to the reverse shuffle.
10046       State.ILV->addMetadata(NewLI, LI);
10047       if (Reverse)
10048         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
10049     }
10050 
10051     State.set(getVPSingleValue(), NewLI, Part);
10052   }
10053 }
10054 
10055 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10056 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10057 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10058 // for predication.
10059 static ScalarEpilogueLowering getScalarEpilogueLowering(
10060     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10061     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10062     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10063     LoopVectorizationLegality &LVL) {
10064   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10065   // don't look at hints or options, and don't request a scalar epilogue.
10066   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10067   // LoopAccessInfo (due to code dependency and not being able to reliably get
10068   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10069   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10070   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10071   // back to the old way and vectorize with versioning when forced. See D81345.)
10072   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10073                                                       PGSOQueryType::IRPass) &&
10074                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10075     return CM_ScalarEpilogueNotAllowedOptSize;
10076 
10077   // 2) If set, obey the directives
10078   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10079     switch (PreferPredicateOverEpilogue) {
10080     case PreferPredicateTy::ScalarEpilogue:
10081       return CM_ScalarEpilogueAllowed;
10082     case PreferPredicateTy::PredicateElseScalarEpilogue:
10083       return CM_ScalarEpilogueNotNeededUsePredicate;
10084     case PreferPredicateTy::PredicateOrDontVectorize:
10085       return CM_ScalarEpilogueNotAllowedUsePredicate;
10086     };
10087   }
10088 
10089   // 3) If set, obey the hints
10090   switch (Hints.getPredicate()) {
10091   case LoopVectorizeHints::FK_Enabled:
10092     return CM_ScalarEpilogueNotNeededUsePredicate;
10093   case LoopVectorizeHints::FK_Disabled:
10094     return CM_ScalarEpilogueAllowed;
10095   };
10096 
10097   // 4) if the TTI hook indicates this is profitable, request predication.
10098   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10099                                        LVL.getLAI()))
10100     return CM_ScalarEpilogueNotNeededUsePredicate;
10101 
10102   return CM_ScalarEpilogueAllowed;
10103 }
10104 
10105 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10106   // If Values have been set for this Def return the one relevant for \p Part.
10107   if (hasVectorValue(Def, Part))
10108     return Data.PerPartOutput[Def][Part];
10109 
10110   if (!hasScalarValue(Def, {Part, 0})) {
10111     Value *IRV = Def->getLiveInIRValue();
10112     Value *B = ILV->getBroadcastInstrs(IRV);
10113     set(Def, B, Part);
10114     return B;
10115   }
10116 
10117   Value *ScalarValue = get(Def, {Part, 0});
10118   // If we aren't vectorizing, we can just copy the scalar map values over
10119   // to the vector map.
10120   if (VF.isScalar()) {
10121     set(Def, ScalarValue, Part);
10122     return ScalarValue;
10123   }
10124 
10125   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10126   bool IsUniform = RepR && RepR->isUniform();
10127 
10128   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10129   // Check if there is a scalar value for the selected lane.
10130   if (!hasScalarValue(Def, {Part, LastLane})) {
10131     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10132     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
10133            "unexpected recipe found to be invariant");
10134     IsUniform = true;
10135     LastLane = 0;
10136   }
10137 
10138   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10139   // Set the insert point after the last scalarized instruction or after the
10140   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10141   // will directly follow the scalar definitions.
10142   auto OldIP = Builder.saveIP();
10143   auto NewIP =
10144       isa<PHINode>(LastInst)
10145           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10146           : std::next(BasicBlock::iterator(LastInst));
10147   Builder.SetInsertPoint(&*NewIP);
10148 
10149   // However, if we are vectorizing, we need to construct the vector values.
10150   // If the value is known to be uniform after vectorization, we can just
10151   // broadcast the scalar value corresponding to lane zero for each unroll
10152   // iteration. Otherwise, we construct the vector values using
10153   // insertelement instructions. Since the resulting vectors are stored in
10154   // State, we will only generate the insertelements once.
10155   Value *VectorValue = nullptr;
10156   if (IsUniform) {
10157     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10158     set(Def, VectorValue, Part);
10159   } else {
10160     // Initialize packing with insertelements to start from undef.
10161     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10162     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10163     set(Def, Undef, Part);
10164     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10165       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10166     VectorValue = get(Def, Part);
10167   }
10168   Builder.restoreIP(OldIP);
10169   return VectorValue;
10170 }
10171 
10172 // Process the loop in the VPlan-native vectorization path. This path builds
10173 // VPlan upfront in the vectorization pipeline, which allows to apply
10174 // VPlan-to-VPlan transformations from the very beginning without modifying the
10175 // input LLVM IR.
10176 static bool processLoopInVPlanNativePath(
10177     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10178     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10179     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10180     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10181     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10182     LoopVectorizationRequirements &Requirements) {
10183 
10184   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10185     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10186     return false;
10187   }
10188   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10189   Function *F = L->getHeader()->getParent();
10190   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10191 
10192   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10193       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10194 
10195   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10196                                 &Hints, IAI);
10197   // Use the planner for outer loop vectorization.
10198   // TODO: CM is not used at this point inside the planner. Turn CM into an
10199   // optional argument if we don't need it in the future.
10200   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10201                                Requirements, ORE);
10202 
10203   // Get user vectorization factor.
10204   ElementCount UserVF = Hints.getWidth();
10205 
10206   CM.collectElementTypesForWidening();
10207 
10208   // Plan how to best vectorize, return the best VF and its cost.
10209   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10210 
10211   // If we are stress testing VPlan builds, do not attempt to generate vector
10212   // code. Masked vector code generation support will follow soon.
10213   // Also, do not attempt to vectorize if no vector code will be produced.
10214   if (VPlanBuildStressTest || EnableVPlanPredication ||
10215       VectorizationFactor::Disabled() == VF)
10216     return false;
10217 
10218   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10219 
10220   {
10221     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10222                              F->getParent()->getDataLayout());
10223     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10224                            &CM, BFI, PSI, Checks);
10225     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10226                       << L->getHeader()->getParent()->getName() << "\"\n");
10227     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10228   }
10229 
10230   // Mark the loop as already vectorized to avoid vectorizing again.
10231   Hints.setAlreadyVectorized();
10232   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10233   return true;
10234 }
10235 
10236 // Emit a remark if there are stores to floats that required a floating point
10237 // extension. If the vectorized loop was generated with floating point there
10238 // will be a performance penalty from the conversion overhead and the change in
10239 // the vector width.
10240 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10241   SmallVector<Instruction *, 4> Worklist;
10242   for (BasicBlock *BB : L->getBlocks()) {
10243     for (Instruction &Inst : *BB) {
10244       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10245         if (S->getValueOperand()->getType()->isFloatTy())
10246           Worklist.push_back(S);
10247       }
10248     }
10249   }
10250 
10251   // Traverse the floating point stores upwards searching, for floating point
10252   // conversions.
10253   SmallPtrSet<const Instruction *, 4> Visited;
10254   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10255   while (!Worklist.empty()) {
10256     auto *I = Worklist.pop_back_val();
10257     if (!L->contains(I))
10258       continue;
10259     if (!Visited.insert(I).second)
10260       continue;
10261 
10262     // Emit a remark if the floating point store required a floating
10263     // point conversion.
10264     // TODO: More work could be done to identify the root cause such as a
10265     // constant or a function return type and point the user to it.
10266     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10267       ORE->emit([&]() {
10268         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10269                                           I->getDebugLoc(), L->getHeader())
10270                << "floating point conversion changes vector width. "
10271                << "Mixed floating point precision requires an up/down "
10272                << "cast that will negatively impact performance.";
10273       });
10274 
10275     for (Use &Op : I->operands())
10276       if (auto *OpI = dyn_cast<Instruction>(Op))
10277         Worklist.push_back(OpI);
10278   }
10279 }
10280 
10281 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10282     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10283                                !EnableLoopInterleaving),
10284       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10285                               !EnableLoopVectorization) {}
10286 
10287 bool LoopVectorizePass::processLoop(Loop *L) {
10288   assert((EnableVPlanNativePath || L->isInnermost()) &&
10289          "VPlan-native path is not enabled. Only process inner loops.");
10290 
10291 #ifndef NDEBUG
10292   const std::string DebugLocStr = getDebugLocString(L);
10293 #endif /* NDEBUG */
10294 
10295   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
10296                     << L->getHeader()->getParent()->getName() << "\" from "
10297                     << DebugLocStr << "\n");
10298 
10299   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
10300 
10301   LLVM_DEBUG(
10302       dbgs() << "LV: Loop hints:"
10303              << " force="
10304              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10305                      ? "disabled"
10306                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10307                             ? "enabled"
10308                             : "?"))
10309              << " width=" << Hints.getWidth()
10310              << " interleave=" << Hints.getInterleave() << "\n");
10311 
10312   // Function containing loop
10313   Function *F = L->getHeader()->getParent();
10314 
10315   // Looking at the diagnostic output is the only way to determine if a loop
10316   // was vectorized (other than looking at the IR or machine code), so it
10317   // is important to generate an optimization remark for each loop. Most of
10318   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10319   // generated as OptimizationRemark and OptimizationRemarkMissed are
10320   // less verbose reporting vectorized loops and unvectorized loops that may
10321   // benefit from vectorization, respectively.
10322 
10323   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10324     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10325     return false;
10326   }
10327 
10328   PredicatedScalarEvolution PSE(*SE, *L);
10329 
10330   // Check if it is legal to vectorize the loop.
10331   LoopVectorizationRequirements Requirements;
10332   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10333                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10334   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10335     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10336     Hints.emitRemarkWithHints();
10337     return false;
10338   }
10339 
10340   // Check the function attributes and profiles to find out if this function
10341   // should be optimized for size.
10342   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10343       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10344 
10345   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10346   // here. They may require CFG and instruction level transformations before
10347   // even evaluating whether vectorization is profitable. Since we cannot modify
10348   // the incoming IR, we need to build VPlan upfront in the vectorization
10349   // pipeline.
10350   if (!L->isInnermost())
10351     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10352                                         ORE, BFI, PSI, Hints, Requirements);
10353 
10354   assert(L->isInnermost() && "Inner loop expected.");
10355 
10356   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10357   // count by optimizing for size, to minimize overheads.
10358   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10359   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10360     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10361                       << "This loop is worth vectorizing only if no scalar "
10362                       << "iteration overheads are incurred.");
10363     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10364       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10365     else {
10366       LLVM_DEBUG(dbgs() << "\n");
10367       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10368     }
10369   }
10370 
10371   // Check the function attributes to see if implicit floats are allowed.
10372   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10373   // an integer loop and the vector instructions selected are purely integer
10374   // vector instructions?
10375   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10376     reportVectorizationFailure(
10377         "Can't vectorize when the NoImplicitFloat attribute is used",
10378         "loop not vectorized due to NoImplicitFloat attribute",
10379         "NoImplicitFloat", ORE, L);
10380     Hints.emitRemarkWithHints();
10381     return false;
10382   }
10383 
10384   // Check if the target supports potentially unsafe FP vectorization.
10385   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10386   // for the target we're vectorizing for, to make sure none of the
10387   // additional fp-math flags can help.
10388   if (Hints.isPotentiallyUnsafe() &&
10389       TTI->isFPVectorizationPotentiallyUnsafe()) {
10390     reportVectorizationFailure(
10391         "Potentially unsafe FP op prevents vectorization",
10392         "loop not vectorized due to unsafe FP support.",
10393         "UnsafeFP", ORE, L);
10394     Hints.emitRemarkWithHints();
10395     return false;
10396   }
10397 
10398   bool AllowOrderedReductions;
10399   // If the flag is set, use that instead and override the TTI behaviour.
10400   if (ForceOrderedReductions.getNumOccurrences() > 0)
10401     AllowOrderedReductions = ForceOrderedReductions;
10402   else
10403     AllowOrderedReductions = TTI->enableOrderedReductions();
10404   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10405     ORE->emit([&]() {
10406       auto *ExactFPMathInst = Requirements.getExactFPInst();
10407       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10408                                                  ExactFPMathInst->getDebugLoc(),
10409                                                  ExactFPMathInst->getParent())
10410              << "loop not vectorized: cannot prove it is safe to reorder "
10411                 "floating-point operations";
10412     });
10413     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10414                          "reorder floating-point operations\n");
10415     Hints.emitRemarkWithHints();
10416     return false;
10417   }
10418 
10419   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10420   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10421 
10422   // If an override option has been passed in for interleaved accesses, use it.
10423   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10424     UseInterleaved = EnableInterleavedMemAccesses;
10425 
10426   // Analyze interleaved memory accesses.
10427   if (UseInterleaved) {
10428     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10429   }
10430 
10431   // Use the cost model.
10432   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10433                                 F, &Hints, IAI);
10434   CM.collectValuesToIgnore();
10435   CM.collectElementTypesForWidening();
10436 
10437   // Use the planner for vectorization.
10438   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10439                                Requirements, ORE);
10440 
10441   // Get user vectorization factor and interleave count.
10442   ElementCount UserVF = Hints.getWidth();
10443   unsigned UserIC = Hints.getInterleave();
10444 
10445   // Plan how to best vectorize, return the best VF and its cost.
10446   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10447 
10448   VectorizationFactor VF = VectorizationFactor::Disabled();
10449   unsigned IC = 1;
10450 
10451   if (MaybeVF) {
10452     VF = *MaybeVF;
10453     // Select the interleave count.
10454     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10455   }
10456 
10457   // Identify the diagnostic messages that should be produced.
10458   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10459   bool VectorizeLoop = true, InterleaveLoop = true;
10460   if (VF.Width.isScalar()) {
10461     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10462     VecDiagMsg = std::make_pair(
10463         "VectorizationNotBeneficial",
10464         "the cost-model indicates that vectorization is not beneficial");
10465     VectorizeLoop = false;
10466   }
10467 
10468   if (!MaybeVF && UserIC > 1) {
10469     // Tell the user interleaving was avoided up-front, despite being explicitly
10470     // requested.
10471     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10472                          "interleaving should be avoided up front\n");
10473     IntDiagMsg = std::make_pair(
10474         "InterleavingAvoided",
10475         "Ignoring UserIC, because interleaving was avoided up front");
10476     InterleaveLoop = false;
10477   } else if (IC == 1 && UserIC <= 1) {
10478     // Tell the user interleaving is not beneficial.
10479     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10480     IntDiagMsg = std::make_pair(
10481         "InterleavingNotBeneficial",
10482         "the cost-model indicates that interleaving is not beneficial");
10483     InterleaveLoop = false;
10484     if (UserIC == 1) {
10485       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10486       IntDiagMsg.second +=
10487           " and is explicitly disabled or interleave count is set to 1";
10488     }
10489   } else if (IC > 1 && UserIC == 1) {
10490     // Tell the user interleaving is beneficial, but it explicitly disabled.
10491     LLVM_DEBUG(
10492         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10493     IntDiagMsg = std::make_pair(
10494         "InterleavingBeneficialButDisabled",
10495         "the cost-model indicates that interleaving is beneficial "
10496         "but is explicitly disabled or interleave count is set to 1");
10497     InterleaveLoop = false;
10498   }
10499 
10500   // Override IC if user provided an interleave count.
10501   IC = UserIC > 0 ? UserIC : IC;
10502 
10503   // Emit diagnostic messages, if any.
10504   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10505   if (!VectorizeLoop && !InterleaveLoop) {
10506     // Do not vectorize or interleaving the loop.
10507     ORE->emit([&]() {
10508       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10509                                       L->getStartLoc(), L->getHeader())
10510              << VecDiagMsg.second;
10511     });
10512     ORE->emit([&]() {
10513       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10514                                       L->getStartLoc(), L->getHeader())
10515              << IntDiagMsg.second;
10516     });
10517     return false;
10518   } else if (!VectorizeLoop && InterleaveLoop) {
10519     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10520     ORE->emit([&]() {
10521       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10522                                         L->getStartLoc(), L->getHeader())
10523              << VecDiagMsg.second;
10524     });
10525   } else if (VectorizeLoop && !InterleaveLoop) {
10526     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10527                       << ") in " << DebugLocStr << '\n');
10528     ORE->emit([&]() {
10529       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10530                                         L->getStartLoc(), L->getHeader())
10531              << IntDiagMsg.second;
10532     });
10533   } else if (VectorizeLoop && InterleaveLoop) {
10534     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10535                       << ") in " << DebugLocStr << '\n');
10536     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10537   }
10538 
10539   bool DisableRuntimeUnroll = false;
10540   MDNode *OrigLoopID = L->getLoopID();
10541   {
10542     // Optimistically generate runtime checks. Drop them if they turn out to not
10543     // be profitable. Limit the scope of Checks, so the cleanup happens
10544     // immediately after vector codegeneration is done.
10545     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10546                              F->getParent()->getDataLayout());
10547     if (!VF.Width.isScalar() || IC > 1)
10548       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10549 
10550     using namespace ore;
10551     if (!VectorizeLoop) {
10552       assert(IC > 1 && "interleave count should not be 1 or 0");
10553       // If we decided that it is not legal to vectorize the loop, then
10554       // interleave it.
10555       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10556                                  &CM, BFI, PSI, Checks);
10557 
10558       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10559       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10560 
10561       ORE->emit([&]() {
10562         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10563                                   L->getHeader())
10564                << "interleaved loop (interleaved count: "
10565                << NV("InterleaveCount", IC) << ")";
10566       });
10567     } else {
10568       // If we decided that it is *legal* to vectorize the loop, then do it.
10569 
10570       // Consider vectorizing the epilogue too if it's profitable.
10571       VectorizationFactor EpilogueVF =
10572           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10573       if (EpilogueVF.Width.isVector()) {
10574 
10575         // The first pass vectorizes the main loop and creates a scalar epilogue
10576         // to be vectorized by executing the plan (potentially with a different
10577         // factor) again shortly afterwards.
10578         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10579         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10580                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10581 
10582         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10583         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10584                         DT);
10585         ++LoopsVectorized;
10586 
10587         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10588         formLCSSARecursively(*L, *DT, LI, SE);
10589 
10590         // Second pass vectorizes the epilogue and adjusts the control flow
10591         // edges from the first pass.
10592         EPI.MainLoopVF = EPI.EpilogueVF;
10593         EPI.MainLoopUF = EPI.EpilogueUF;
10594         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10595                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10596                                                  Checks);
10597 
10598         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10599         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10600                         DT);
10601         ++LoopsEpilogueVectorized;
10602 
10603         if (!MainILV.areSafetyChecksAdded())
10604           DisableRuntimeUnroll = true;
10605       } else {
10606         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10607                                &LVL, &CM, BFI, PSI, Checks);
10608 
10609         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10610         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10611         ++LoopsVectorized;
10612 
10613         // Add metadata to disable runtime unrolling a scalar loop when there
10614         // are no runtime checks about strides and memory. A scalar loop that is
10615         // rarely used is not worth unrolling.
10616         if (!LB.areSafetyChecksAdded())
10617           DisableRuntimeUnroll = true;
10618       }
10619       // Report the vectorization decision.
10620       ORE->emit([&]() {
10621         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10622                                   L->getHeader())
10623                << "vectorized loop (vectorization width: "
10624                << NV("VectorizationFactor", VF.Width)
10625                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10626       });
10627     }
10628 
10629     if (ORE->allowExtraAnalysis(LV_NAME))
10630       checkMixedPrecision(L, ORE);
10631   }
10632 
10633   Optional<MDNode *> RemainderLoopID =
10634       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10635                                       LLVMLoopVectorizeFollowupEpilogue});
10636   if (RemainderLoopID.hasValue()) {
10637     L->setLoopID(RemainderLoopID.getValue());
10638   } else {
10639     if (DisableRuntimeUnroll)
10640       AddRuntimeUnrollDisableMetaData(L);
10641 
10642     // Mark the loop as already vectorized to avoid vectorizing again.
10643     Hints.setAlreadyVectorized();
10644   }
10645 
10646   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10647   return true;
10648 }
10649 
10650 LoopVectorizeResult LoopVectorizePass::runImpl(
10651     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10652     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10653     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10654     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10655     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10656   SE = &SE_;
10657   LI = &LI_;
10658   TTI = &TTI_;
10659   DT = &DT_;
10660   BFI = &BFI_;
10661   TLI = TLI_;
10662   AA = &AA_;
10663   AC = &AC_;
10664   GetLAA = &GetLAA_;
10665   DB = &DB_;
10666   ORE = &ORE_;
10667   PSI = PSI_;
10668 
10669   // Don't attempt if
10670   // 1. the target claims to have no vector registers, and
10671   // 2. interleaving won't help ILP.
10672   //
10673   // The second condition is necessary because, even if the target has no
10674   // vector registers, loop vectorization may still enable scalar
10675   // interleaving.
10676   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10677       TTI->getMaxInterleaveFactor(1) < 2)
10678     return LoopVectorizeResult(false, false);
10679 
10680   bool Changed = false, CFGChanged = false;
10681 
10682   // The vectorizer requires loops to be in simplified form.
10683   // Since simplification may add new inner loops, it has to run before the
10684   // legality and profitability checks. This means running the loop vectorizer
10685   // will simplify all loops, regardless of whether anything end up being
10686   // vectorized.
10687   for (auto &L : *LI)
10688     Changed |= CFGChanged |=
10689         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10690 
10691   // Build up a worklist of inner-loops to vectorize. This is necessary as
10692   // the act of vectorizing or partially unrolling a loop creates new loops
10693   // and can invalidate iterators across the loops.
10694   SmallVector<Loop *, 8> Worklist;
10695 
10696   for (Loop *L : *LI)
10697     collectSupportedLoops(*L, LI, ORE, Worklist);
10698 
10699   LoopsAnalyzed += Worklist.size();
10700 
10701   // Now walk the identified inner loops.
10702   while (!Worklist.empty()) {
10703     Loop *L = Worklist.pop_back_val();
10704 
10705     // For the inner loops we actually process, form LCSSA to simplify the
10706     // transform.
10707     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10708 
10709     Changed |= CFGChanged |= processLoop(L);
10710   }
10711 
10712   // Process each loop nest in the function.
10713   return LoopVectorizeResult(Changed, CFGChanged);
10714 }
10715 
10716 PreservedAnalyses LoopVectorizePass::run(Function &F,
10717                                          FunctionAnalysisManager &AM) {
10718     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10719     auto &LI = AM.getResult<LoopAnalysis>(F);
10720     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10721     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10722     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10723     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10724     auto &AA = AM.getResult<AAManager>(F);
10725     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10726     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10727     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10728 
10729     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10730     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10731         [&](Loop &L) -> const LoopAccessInfo & {
10732       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10733                                         TLI, TTI, nullptr, nullptr, nullptr};
10734       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10735     };
10736     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10737     ProfileSummaryInfo *PSI =
10738         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10739     LoopVectorizeResult Result =
10740         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10741     if (!Result.MadeAnyChange)
10742       return PreservedAnalyses::all();
10743     PreservedAnalyses PA;
10744 
10745     // We currently do not preserve loopinfo/dominator analyses with outer loop
10746     // vectorization. Until this is addressed, mark these analyses as preserved
10747     // only for non-VPlan-native path.
10748     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10749     if (!EnableVPlanNativePath) {
10750       PA.preserve<LoopAnalysis>();
10751       PA.preserve<DominatorTreeAnalysis>();
10752     }
10753     if (!Result.MadeCFGChange)
10754       PA.preserveSet<CFGAnalyses>();
10755     return PA;
10756 }
10757 
10758 void LoopVectorizePass::printPipeline(
10759     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10760   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10761       OS, MapClassName2PassName);
10762 
10763   OS << "<";
10764   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10765   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10766   OS << ">";
10767 }
10768